refactor: whole plugin

migrate from https://github.com/g1eny0ung/grafana-chaos-mesh-datasource

Signed-off-by: Yue Yang <g1enyy0ung@gmail.com>
This commit is contained in:
Yue Yang 2021-03-09 11:04:21 +08:00
parent c8105245a4
commit 0748dd44d9
46 changed files with 4222 additions and 4312 deletions

View File

@ -1,67 +0,0 @@
version: 2.1
parameters:
ssh-fingerprint:
type: string
default: ${GITHUB_SSH_FINGERPRINT}
aliases:
# Workflow filters
- &filter-only-master
branches:
only: master
- &filter-only-release
branches:
only: /^v[1-9]*[0-9]+\.[1-9]*[0-9]+\.x$/
workflows:
plugin_workflow:
jobs:
- build
executors:
default_exec: # declares a reusable executor
docker:
- image: srclosson/grafana-plugin-ci-alpine:latest
e2e_exec:
docker:
- image: srclosson/grafana-plugin-ci-e2e:latest
jobs:
build:
executor: default_exec
steps:
- checkout
- restore_cache:
name: restore node_modules
keys:
- build-cache-{{ .Environment.CACHE_VERSION }}-{{ checksum "yarn.lock" }}
- run:
name: Install dependencies
command: |
mkdir ci
[ -f ~/project/node_modules/.bin/grafana-toolkit ] || yarn install --frozen-lockfile
- save_cache:
name: save node_modules
paths:
- ~/project/node_modules
key: build-cache-{{ .Environment.CACHE_VERSION }}-{{ checksum "yarn.lock" }}
- run:
name: Build and test frontend
command: ./node_modules/.bin/grafana-toolkit plugin:ci-build
- run:
name: Move results to ci folder
command: ./node_modules/.bin/grafana-toolkit plugin:ci-build --finish
- run:
name: Package distribution
command: |
./node_modules/.bin/grafana-toolkit plugin:ci-package
- persist_to_workspace:
root: .
paths:
- ci/jobs/package
- ci/packages
- ci/dist
- ci/grafana-test-env
- store_artifacts:
path: ci

View File

@ -11,6 +11,3 @@ max_line_length = 120
[*.{js,ts,tsx,scss}]
quote_type = single
[*.md]
trim_trailing_whitespace = false

4
.gitignore vendored
View File

@ -20,6 +20,7 @@ lib-cov
coverage
# Compiled binary addons (https://nodejs.org/api/addons.html)
dist/
artifacts/
work/
ci/
@ -28,3 +29,6 @@ e2e-results/
# Editor
.idea
jest.config.js
yeya24-chaosmesh-datasource
*.zip

1
.husky/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
_

4
.husky/pre-commit Executable file
View File

@ -0,0 +1,4 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npm run lint-staged

View File

@ -1,3 +1,4 @@
module.exports = {
...require("./node_modules/@grafana/toolkit/src/config/prettier.plugin.config.json"),
...require('./node_modules/@grafana/toolkit/src/config/prettier.plugin.config.json'),
arrowParens: 'avoid',
};

14
CHANGELOG.md Normal file
View File

@ -0,0 +1,14 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.1.3] - 2021-03-02
### Added
- Visualize Chaos Events on the table
- Show Chaos Events on the graph with [Annotations](https://grafana.com/docs/grafana/latest/dashboards/annotations/)
- Display different Chaos Events by [Variables](https://grafana.com/docs/grafana/latest/variables/)

View File

@ -178,7 +178,7 @@
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
@ -186,7 +186,7 @@
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.

View File

@ -1,56 +1,95 @@
# Chaos Mesh Data Source
Visualize Chaos Mesh Events with Grafana.
Grafana data source plugin for Chaos Mesh.
![screenshot](https://raw.githubusercontent.com/chaos-mesh/chaos-mesh-datasource/master/docs/assets/example.png)
## Features
## Usage
- Visualize Chaos Events on the table
- Show Chaos Events on the graph with [Annotations](https://grafana.com/docs/grafana/latest/dashboards/annotations/)
- Display different Chaos Events by [Variables](https://grafana.com/docs/grafana/latest/variables/)
### Configure Data Source
## Installation
Go to Grafana -> Configuration -> Data Sources, click `Add data source` button.
```sh
grafana-cli plugins install yeya24-chaos-mesh-datasource
```
![add-data-source](https://raw.githubusercontent.com/chaos-mesh/chaos-mesh-datasource/master/docs/assets/add-datasource.png)
## Setup
Enter Chaos Mesh into the search bar and then you can see the data source.
After installed, you can add this data source in **Configuration -> Data Sources**, then you will enter the settings page:
![find data source](https://raw.githubusercontent.com/chaos-mesh/chaos-mesh-datasource/master/docs/assets/find-data-source.png)
![Data Source settings](https://raw.githubusercontent.com/chaos-mesh/chaos-mesh-datasource/master/img/settings.jpg)
Enter the URL of Chaos Dashboard, and click `Save & Test` to check availability.
Only the `URL` field needs to be filled in and the others can be ignored.
It is best to make sure your network can access this URL as well.
Assuming you have a local Chaos Mesh installed, the dashboard will default export its API in port `2333`. So, if you don't modify anything, you can simply fill `http://localhost:2333` into it.
![configure data source](https://raw.githubusercontent.com/chaos-mesh/chaos-mesh-datasource/master/docs/assets/configure-datasource.png)
Then use **port-forward** to active:
### Query Chaos Events with Panels
```sh
kubectl port-forward -n chaos-testing svc/chaos-dashboard 2333:2333
```
Add a new query panel and choose Chaos Mesh Data source. Enter the required parameters below for what experiment you want to search.
Finally, click **Save & Test** to test the connection. If it shows that the connection is successful, then the setup work has been completed.
Please note that Chaos Mesh Data source only supports `Table` type visualization.
### Options
![panel query](https://raw.githubusercontent.com/chaos-mesh/chaos-mesh-datasource/master/docs/assets/new-panel.png)
Except for the `url`, this data source plugin has such options as below:
### Query Chaos Events with Annotations
| Name | Description |
| ----- | --------------------------------------------------------------------------------------------------------------------- |
| Limit | Limit the number of returned Chaos Events. The default is 25. If you want to display more events, please increase it. |
#### Configure Annotation
## Query
Add a new annotation, choose type as `Chaos Mesh`. Enter the required parameters below for what experiment you want to search.
Mostly, there will be three options to be responsible for filtering events:
![configure annotation](https://raw.githubusercontent.com/chaos-mesh/chaos-mesh-datasource/master/docs/assets/configure-annotation.png)
- **Experiment** - Filter by the experiment name. Must be a full name.
- **Namespace** - Filter by different namespaces
- **Kind** - Filter by Chaos kinds
#### View Results
For real world usage, normally you will use these options in two situations:
To view the annotations, you should have a panel. If the annotation is enabled and there are some Chaos events at the time range, you can see the annotations in your dashboard.
- Specify all fields to locate an experiment more precisely.
- Let **Experiment** be empty to reduce the constraints of events filtering.
- Pass a variable like `$experiment` to query to control the events displaying.
There is also a link `Event Details`, you can click this link and go to Chaos Dashboard UI to see the details of that event.
## Annotations
![example](https://raw.githubusercontent.com/chaos-mesh/chaos-mesh-datasource/master/docs/assets/example.png)
Edit example:
## Development
![Data Source annotations](https://raw.githubusercontent.com/chaos-mesh/chaos-mesh-datasource/master/img/annotations.png)
If you want to develop and contribute to this data source, please check [Tutorial](https://github.com/chaos-mesh/chaos-mesh-datasource/blob/master/docs/dev.md)
For usage, you can refer to the content described by [Query](#query).
## Learn More
- [Chaos Mesh Repository](https://github.com/pingcap/chaos-mesh)
- [Chaos Mesh Website](https://chaos-mesh.org/)
- [Build a data source plugin tutorial](https://grafana.com/tutorials/build-a-data-source-plugin)
## Variables
If you choose the Variables type to query and select the data source to Chaos Mesh, You can get three different kind values.
Specify by choosing different **metric**:
- Experiment
After selection, a text input field will occur, fill in the value of the experiment name you want to settle. Usually, you will fill in the **partial** name of some experiments to get the related experiment names.
> For example, you have two experiments:
>
> random-pod-kill and random-pod-failure
>
> Then you can fill **random** in the text field to get these experiments.
- Namespace
After selection, all available namespaces will show in **Preview of values** directly. Without other operations.
- Kind
Same as **Namespace**.
## How to contribute
Pull a request or open an issue to describe your changes or problems.
## License
Same as Chaos Mesh. Under Apache-2.0 License.

View File

@ -1,26 +0,0 @@
# Test against the latest version of this Node.js version
environment:
nodejs_version: "10"
# Local NPM Modules
cache:
- node_modules
# Install scripts. (runs after repo cloning)
install:
# Get the latest stable version of Node.js or io.js
- ps: Install-Product node $env:nodejs_version
# install modules
- npm install -g yarn --quiet
- yarn install --pure-lockfile
# Post-install test scripts.
test_script:
# Output useful info for debugging.
- node --version
- npm --version
# Run the build
build_script:
- yarn dev # This will also run prettier!
- yarn build # make sure both scripts work

13
bundle.sh Executable file
View File

@ -0,0 +1,13 @@
VERSION=$1
echo "Bundled Version: $VERSION"
echo "Start to build..."
echo
yarn build
echo "Bundling..."
echo
cp -r dist yeya24-chaosmesh-datasource
zip -r yeya24-chaosmesh-datasource-$VERSION.zip yeya24-chaosmesh-datasource -x "*.DS_Store*"

201
dist/LICENSE vendored
View File

@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

56
dist/README.md vendored
View File

@ -1,56 +0,0 @@
# Chaos Mesh Data Source
Visualize Chaos Mesh Events with Grafana.
![screenshot](https://raw.githubusercontent.com/chaos-mesh/chaos-mesh-datasource/master/docs/assets/example.png)
## Usage
### Configure Data Source
Go to Grafana -> Configuration -> Data Sources, click `Add data source` button.
![add-data-source](https://raw.githubusercontent.com/chaos-mesh/chaos-mesh-datasource/master/docs/assets/add-datasource.png)
Enter Chaos Mesh into the search bar and then you can see the data source.
![find data source](https://raw.githubusercontent.com/chaos-mesh/chaos-mesh-datasource/master/docs/assets/find-data-source.png)
Enter the URL of Chaos Dashboard, and click `Save & Test` to check availability.
It is best to make sure your network can access this URL as well.
![configure data source](https://raw.githubusercontent.com/chaos-mesh/chaos-mesh-datasource/master/docs/assets/configure-datasource.png)
### Query Chaos Events with Panels
Add a new query panel and choose Chaos Mesh Data source. Enter the required parameters below for what experiment you want to search.
Please note that Chaos Mesh Data source only supports `Table` type visualization.
![panel query](https://raw.githubusercontent.com/chaos-mesh/chaos-mesh-datasource/master/docs/assets/new-panel.png)
### Query Chaos Events with Annotations
#### Configure Annotation
Add a new annotation, choose type as `Chaos Mesh`. Enter the required parameters below for what experiment you want to search.
![configure annotation](https://raw.githubusercontent.com/chaos-mesh/chaos-mesh-datasource/master/docs/assets/configure-annotation.png)
#### View Results
To view the annotations, you should have a panel. If the annotation is enabled and there are some Chaos events at the time range, you can see the annotations in your dashboard.
There is also a link `Event Details`, you can click this link and go to Chaos Dashboard UI to see the details of that event.
![example](https://raw.githubusercontent.com/chaos-mesh/chaos-mesh-datasource/master/docs/assets/example.png)
## Development
If you want to develop and contribute to this data source, please check [Tutorial](https://github.com/chaos-mesh/chaos-mesh-datasource/blob/master/docs/dev.md)
## Learn More
- [Chaos Mesh Repository](https://github.com/pingcap/chaos-mesh)
- [Chaos Mesh Website](https://chaos-mesh.org/)
- [Build a data source plugin tutorial](https://grafana.com/tutorials/build-a-data-source-plugin)

1
dist/img/logo.svg vendored

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 8.6 KiB

3
dist/module.js vendored

File diff suppressed because one or more lines are too long

View File

@ -1,14 +0,0 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */

1
dist/module.js.map vendored

File diff suppressed because one or more lines are too long

View File

@ -1,23 +0,0 @@
<div class="gf-form-group">
<div class="gf-form">
<span class="gf-form-label width-10">Kind</span>
<div class="gf-form-select-wrapper width-12">
<select class="gf-form-input" ng-model="ctrl.annotation.kind" ng-options="f.value as f.text for f in ctrl.kinds">
</select>
</div>
</div>
<div class="gf-form">
<span class="gf-form-label width-10">Experiment Namespace</span>
<div class="gf-form-select-wrapper width-12">
<select
class="gf-form-input service-dropdown"
ng-model="ctrl.annotation.namespace"
ng-options="f.value as f.text for f in ctrl.namespaces"
></select>
</div>
</div>
<div class="gf-form">
<span class="gf-form-label width-10">Experiment Name</span>
<input type="text" class="gf-form-input max-width-12" ng-model='ctrl.annotation.experiment'/>
</div>
</div>

45
dist/plugin.json vendored
View File

@ -1,45 +0,0 @@
{
"type": "datasource",
"name": "Chaos Mesh",
"id": "yeya24-chaosmesh-datasource",
"metrics": true,
"annotations": true,
"logs": false,
"streaming": false,
"tracing": false,
"info": {
"description": "A Chaos Engineering Platform for Kubernetes",
"author": {
"name": "yeya24",
"url": "https://github.com/yeya24"
},
"keywords": [
"chaos"
],
"logos": {
"small": "img/logo.svg",
"large": "img/logo.svg"
},
"links": [
{
"name": "Learn more",
"url": "https://chaos-mesh.org/"
},
{
"name": "Website",
"url": "https://github.com/chaos-mesh/chaos-mesh-datasource"
},
{
"name": "License",
"url": "https://github.com/chaos-mesh/chaos-mesh-datasource/blob/master/LICENSE"
}
],
"screenshots": [],
"version": "0.1.2",
"updated": "2020-08-20"
},
"dependencies": {
"grafanaDependency": ">=6.5.0",
"plugins": []
}
}

View File

@ -1,17 +0,0 @@
version: '3'
services:
grafana:
image: grafana/grafana:7.0.3
ports:
- '3000:3000'
volumes:
- ./:/var/lib/grafana/plugins/chaos-mesh
- grafana-storage:/var/lib/grafana
- ./provisioning:/etc/grafana/provisioning
environment:
- COMPOSE_INTERACTIVE_NO_CLI=1
- TERM=linux
- GF_LOG_LEVEL=debug
- GF_DATAPROXY_LOGGING=true
volumes:
grafana-storage:

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 149 KiB

View File

@ -1,43 +0,0 @@
# Data Source Development Tutorial
You need to install the following first:
- [yarn](https://yarnpkg.com/)
- [Docker Compose](https://docs.docker.com/compose/)
1. Install dependencies
```BASH
yarn install
```
2. Build plugin in development mode or run in watch mode
```BASH
yarn dev
```
or
```BASH
yarn watch
```
3. Build plugin in production mode
```BASH
yarn build
```
## Develop using Docker Compose
First build the data source locally
```bash
yarn dev
```
You can develop using Docker Compose easily.
```bash
docker-compose up -d
```
Then you can open `localhost:3000` at the browser and find the Chaos Mesh data source.
![find data source](https://raw.githubusercontent.com/chaos-mesh/chaos-mesh-datasource/master/docs/assets/find-data-source.png)
Remember that every time the source code changes, you need to restart the Grafana container to load the latest plugin.

View File

@ -1,41 +0,0 @@
# Tutorial for Chaos Mesh Data source
## Configure the data source
Go to Grafana -> Configuration -> Data Sources, click `Add data source` button.
![add-data-source](assets/add-datasource.png)
Enter Chaos Mesh into the search bar and then you can see the data source.
![find data source](assets/find-data-source.png)
Enter the URL of Chaos Dashboard, and click `Save & Test` to check availability.
It is best to make sure your network can access this URL as well.
![configure data source](assets/configure-datasource.png)
## Chaos Events Query
Add a new query panel and choose Chaos Mesh Data source. Enter the required parameters below for what experiment you want to search.
Please note that Chaos Mesh Data source only supports `Table` type visualization.
![panel query](assets/new-panel.png)
## Chaos Events Annotations Query
### Configure Annotation
Add a new annotation, choose type as `Chaos Mesh`. Enter the required parameters below for what experiment you want to search.
![configure annotation](assets/configure-annotation.png)
### View the results
To view the annotations, you should have a panel. If the annotation is enabled and there are some Chaos events at the time range, you can see the annotations in your dashboard.
There is also a link `Event Details`, you can click this link and go to Chaos Dashboard UI to see the details of that event.
![example](assets/example.png)

BIN
img/annotations.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
img/settings.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

View File

@ -1,8 +0,0 @@
// This file is needed because it is used by vscode and other tools that
// call `jest` directly. However, unless you are doing anything special
// do not edit this file
const standard = require('@grafana/toolkit/src/config/jest.plugin.config');
// This process will use the same config that `yarn test` is using
module.exports = standard.jestConfig();

View File

@ -1,27 +1,41 @@
{
"name": "chaos-mesh-chaos-mesh",
"version": "1.0.0",
"description": "",
"name": "yeya24-chaosmesh-datasource",
"version": "0.1.2",
"description": "Chaos Mesh Datasource",
"author": "Yue Yang <g1enyy0ung@gmail.com> (https://g1eny0ung.site)",
"license": "Apache-2.0",
"scripts": {
"build": "grafana-toolkit plugin:build",
"test": "grafana-toolkit plugin:test",
"dev": "grafana-toolkit plugin:dev",
"watch": "grafana-toolkit plugin:dev --watch"
"watch": "grafana-toolkit plugin:dev --watch",
"postinstall": "husky install",
"lint-staged": "lint-staged"
},
"author": "yeya24",
"license": "Apache-2.0",
"devDependencies": {
"@grafana/data": "7.0.1",
"@grafana/toolkit": "7.0.1",
"@grafana/ui": "7.0.1",
"@grafana/data": "^7.0.0",
"@grafana/runtime": "^7.4.2",
"@grafana/toolkit": "^7.0.0",
"@grafana/ui": "^7.0.0",
"@testing-library/jest-dom": "5.4.0",
"@testing-library/react": "^10.0.2",
"@types/lodash": "latest"
"@types/lodash": "latest",
"husky": "^5.0.9",
"import-sort-style-eslint": "^6.0.0",
"lint-staged": "^10.5.4",
"prettier": "^2.2.1",
"prettier-plugin-import-sort": "^0.0.6"
},
"engines": {
"node": ">=12"
},
"dependencies": {
"@grafana/runtime": "^7.0.3"
"lint-staged": {
"*.(j|t)s?(x)": "prettier --write"
},
"importSort": {
".js, .ts, .tsx": {
"style": "eslint",
"parser": "typescript"
}
}
}

View File

@ -0,0 +1,14 @@
import { kindOptions } from './types';
export class AnnotationQueryEditor {
static templateUrl = 'partials/annotations.editor.html';
annotation: any;
kindOptions = kindOptions;
constructor() {
this.annotation.namespace = this.annotation.namespace || 'default';
this.annotation.kind = this.annotation.kind || 'PodChaos';
}
}

View File

@ -1,28 +0,0 @@
export class AnnotationsQueryCtrl {
annotation: any;
datasource: any;
namespaces: any;
kinds = [
{ value: 'PodChaos', text: 'Pod Chaos' },
{ value: 'NetworkChaos', text: 'Network Chaos' },
{ value: 'IOChaos', text: 'IO Chaos' },
{ value: 'TimeChaos', text: 'Time Chaos' },
{ value: 'KernelChaos', text: 'Kernel Chaos' },
{ value: 'StressChaos', text: 'Stress Chaos' },
];
static templateUrl = 'partials/annotations.editor.html';
constructor() {
this.annotation.kind = this.annotation.kind || 'PodChaos';
this.namespaces = [];
this.initDropDown();
}
async initDropDown() {
this.datasource.queryNamespaces().then((result: any) => {
this.namespaces = result.data.map((ns: string) => ({ text: ns, value: ns }));
});
}
}

50
src/ChaosMeshSettings.tsx Normal file
View File

@ -0,0 +1,50 @@
import React, { SyntheticEvent } from 'react';
import { ChaosMeshOptions } from './types';
import { DataSourcePluginOptionsEditorProps } from '@grafana/data';
import { LegacyForms } from '@grafana/ui';
const { FormField, Input } = LegacyForms;
const onChangeHandler = (
key: keyof ChaosMeshOptions,
options: Props['options'],
onOptionsChange: Props['onOptionsChange']
) => (e: SyntheticEvent<HTMLInputElement>) => {
onOptionsChange({
...options,
jsonData: {
...options.jsonData,
[key]: e.currentTarget.value,
},
});
};
type Props = Pick<DataSourcePluginOptionsEditorProps<ChaosMeshOptions>, 'options' | 'onOptionsChange'>;
const ChaosMeshSettings: React.FC<Props> = props => {
const { options, onOptionsChange } = props;
return (
<>
<h3 className="page-heading">Options</h3>
<div className="gf-form-group">
<div className="gf-form">
<FormField
label="Limit"
tooltip="Limit the number of returned Chaos Events. The default is 25. If you want to display more events, please increase it."
inputEl={
<Input
value={options.jsonData.limit}
onChange={onChangeHandler('limit', options, onOptionsChange)}
placeholder="25"
/>
}
/>
</div>
</div>
</>
);
};
export default ChaosMeshSettings;

View File

@ -1,80 +1,23 @@
import React, { ChangeEvent, PureComponent } from 'react';
import { DataSourcePluginOptionsEditorProps } from '@grafana/data';
import { ChaosMeshOptions } from './types';
import { LegacyForms } from '@grafana/ui';
import ChaosMeshSettings from './ChaosMeshSettings';
import { DataSourceHttpSettings } from '@grafana/ui';
import { DataSourcePluginOptionsEditorProps } from '@grafana/data';
import React from 'react';
const { FormField } = LegacyForms;
type Props = DataSourcePluginOptionsEditorProps<ChaosMeshOptions>;
interface Props extends DataSourcePluginOptionsEditorProps<ChaosMeshOptions> {}
interface State {}
export class ConfigEditor extends PureComponent<Props, State> {
componentDidMount() {
const { options } = this.props;
options.jsonData.defaultUrl = options.url;
}
onURLChange = (event: ChangeEvent<HTMLInputElement>) => {
const { onOptionsChange, options } = this.props;
onOptionsChange({
...options,
url: event.target.value,
jsonData: {
...options.jsonData,
defaultUrl: event.target.value,
},
});
};
onLimitChange = (event: ChangeEvent<HTMLInputElement>) => {
const { onOptionsChange, options } = this.props;
onOptionsChange({
...options,
jsonData: {
...options.jsonData,
limit: parseInt(event.target.value, 10),
},
});
};
render() {
const { options } = this.props;
const { url, jsonData } = options;
const { limit } = jsonData;
export const ConfigEditor: React.FC<Props> = props => {
const { options, onOptionsChange } = props;
return (
<div className="gf-form-group">
<div className="gf-form-group">
<h3 className="page-heading">HTTP</h3>
<div className="gf-form">
<FormField
label="URL"
labelWidth={10}
inputWidth={13}
onChange={this.onURLChange}
value={url || ''}
tooltip="Specify a complete HTTP URL (for example http://your_server:2333);"
placeholder="http://localhost:2333"
<>
<DataSourceHttpSettings
defaultUrl="http://localhost:2333"
dataSourceConfig={options}
showAccessOptions={true}
onChange={onOptionsChange}
/>
</div>
</div>
<div className="gf-form-group">
<h3 className="page-heading">Options</h3>
<div className="gf-form">
<FormField
label="Limit"
labelWidth={10}
inputWidth={6}
onChange={this.onLimitChange}
value={limit || ''}
tooltip="Limit the number of returned Chaos Events. Default value is 25. If you want to display more events, please increase the limit."
placeholder="25"
/>
</div>
</div>
</div>
<ChaosMeshSettings options={options} onOptionsChange={onOptionsChange} />
</>
);
}
}
};

View File

@ -1,230 +1,234 @@
import defaults from 'lodash/defaults';
import {
AnnotationEvent,
AnnotationQueryRequest,
DataQueryError,
DataQueryRequest,
DataQueryResponse,
DataSourceApi,
DataSourceInstanceSettings,
FieldType,
MutableDataFrame,
ScopedVars,
} from '@grafana/data';
import { BackendSrvRequest, getBackendSrv, getTemplateSrv } from '@grafana/runtime';
import {
ChaosEvent,
ChaosMeshOptions,
ChaosMeshQuery,
ChaosMeshVariableQuery,
ExperimentKind,
defaultQuery,
kindOptions,
} from './types';
import { getBackendSrv } from '@grafana/runtime';
import defaults from 'lodash/defaults';
import { ChaosEvent, defaultQuery, ChaosEventsQuery, ChaosMeshOptions, ChaosEventsQueryResponse } from './types';
export class DataSource extends DataSourceApi<ChaosEventsQuery, ChaosMeshOptions> {
export class DataSource extends DataSourceApi<ChaosMeshQuery, ChaosMeshOptions> {
url: string;
defaultUrl: string;
defaultLimit: number;
limit = 25;
constructor(instanceSettings: DataSourceInstanceSettings<ChaosMeshOptions>) {
super(instanceSettings);
this.url = instanceSettings.url!;
this.defaultUrl = instanceSettings.jsonData.defaultUrl;
this.defaultLimit = 25;
if (instanceSettings.jsonData.limit) {
this.defaultLimit = instanceSettings.jsonData.limit;
this.limit = instanceSettings.jsonData.limit;
}
}
_request(url: string, data: Record<string, string> = {}) {
const options = {
url: this.url + url,
method: 'GET',
};
if (data && Object.keys(data).length) {
options.url =
options.url +
'?' +
Object.entries(data)
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
.join('&');
private _fetch<T = any>(path: string, options: Omit<BackendSrvRequest, 'url'> = {}) {
return getBackendSrv()
.fetch<T>({
url: this.url + '/api' + path,
...options,
})
.toPromise();
}
return getBackendSrv().datasourceRequest(options);
}
fetchConfig = () => this._fetch('/common/config');
checkLiveness() {
const url = '/ping';
fetchAvailableNamespaces = () => this._fetch<string[]>('/common/chaos-available-namespaces');
return this._request(url).catch((err: any) => {
console.error(err);
fetchDryEvents = (params?: Partial<ChaosMeshQuery>) =>
this._fetch<ChaosEvent[]>('/events/dry', {
params,
});
private getVariables() {
return getTemplateSrv()
.getVariables()
.map((d: any) => ({ [d.name]: d.current.value }))
.reduce((acc, d) => ({ ...acc, ...d }), {});
}
queryNamespaces() {
const url = '/api/common/namespaces';
return this._request(url).catch((err: any) => {
console.error(err);
});
private applyVariables(query: ChaosMeshQuery, scopedVars: ScopedVars) {
const vars = getTemplateSrv()
.replace(`${query.experimentName} ${query.namespace} ${query.kind}`, scopedVars)
.split(' ');
query.experimentName = vars[0];
query.namespace = vars[1];
query.kind = vars[2] as ExperimentKind;
return query;
}
queryEvents(req: ChaosEventsQuery) {
const url = '/api/events/dry';
const data: any = {
startTime: req.startTime,
finishTime: req.finishTime,
kind: req.kind,
limit: req.limit,
};
if (req.experiment) {
data.experimentName = req.experiment;
}
if (req.namespace) {
data.experimentNamespace = req.namespace;
interpolateVariablesInQueries(queries: ChaosMeshQuery[], scopedVars: ScopedVars) {
return queries.map(query => this.applyVariables(query, scopedVars));
}
return this._request(url, data).catch((err: any) => {
throw this.handleErrors(err, req);
});
}
async query(options: DataQueryRequest<ChaosMeshQuery>): Promise<DataQueryResponse> {
const { range, scopedVars } = options;
const from = range.from.toISOString();
const to = range.to.toISOString();
handleErrors = (err: any, target: ChaosEventsQuery) => {
const error: DataQueryError = {
message: (err && err.statusText) || 'Unknown error during query transaction. Please check JS console logs.',
refId: target.refId,
};
const data = await Promise.all(
options.targets.map(async target => {
const query = this.applyVariables(defaults(target, defaultQuery), scopedVars);
if (err.data) {
if (typeof err.data === 'string') {
error.message = err.data;
} else if (err.data.error) {
error.message = this.safeStringifyValue(err.data.error);
}
} else if (err.message) {
error.message = err.message;
} else if (typeof err === 'string') {
error.message = err;
}
error.status = err.status;
error.statusText = err.statusText;
return error;
};
safeStringifyValue = (value: any, space?: number) => {
if (!value) {
return '';
}
try {
return JSON.stringify(value, null, space);
} catch (error) {
console.error(error);
}
return '';
};
async query(options: DataQueryRequest<ChaosEventsQuery>): Promise<DataQueryResponse> {
const { range } = options;
const from = this.toRFC3339TimeStamp(range.from.toDate());
const to = this.toRFC3339TimeStamp(range.to.toDate());
const data = options.targets.map(target => {
const query = defaults(target, defaultQuery);
query.startTime = from;
query.finishTime = to;
query.limit = this.defaultLimit;
const frame = new MutableDataFrame({
refId: query.refId,
fields: [
{ name: 'Kind', type: FieldType.string },
{ name: 'Namespace', type: FieldType.string },
{ name: 'Experiment', type: FieldType.string },
{ name: 'Namespace', type: FieldType.string },
{ name: 'Kind', type: FieldType.string },
{ name: 'Start Time', type: FieldType.time },
{ name: 'Finish Time', type: FieldType.time },
{ name: 'Message', type: FieldType.string },
],
});
this.queryEvents(query).then((response: ChaosEventsQueryResponse) => {
response.data.forEach(event => {
const value: any = {};
value.Kind = event.kind;
value['Start Time'] = event.start_time;
value['Finish Time'] = event.finish_time;
value.Namespace = event.namespace;
value.Experiment = event.experiment;
frame.add(value);
});
});
const data = (
await this.fetchDryEvents({
...this.constructPivotalParams(query),
startTime: from,
finishTime: to,
limit: this.limit,
})
).data;
data.forEach(d =>
frame.add({
Experiment: d.experiment,
Namespace: d.namespace,
Kind: d.kind,
'Start Time': d.start_time,
'Finish Time': d.finish_time,
Message: d.message,
})
);
return frame;
});
})
);
return { data };
}
// Stole this from http://cbas.pandion.im/2009/10/generating-rfc-3339-timestamps-in.html
toRFC3339TimeStamp(date: Date) {
function pad(amount: number, width: number) {
let padding = '';
while (padding.length < width - 1 && amount < Math.pow(10, width - padding.length - 1)) {
padding += '0';
async annotationQuery(options: any): Promise<AnnotationEvent[]> {
const { range, dashboard } = options;
const from = range.from.toISOString();
const to = range.to.toISOString();
const timezone = dashboard.timezone === '' ? undefined : dashboard.timezone;
const query = defaults(options.annotation, defaultQuery);
const pParams: any = this.constructPivotalParams(query);
const vals = this.getVariables();
Object.entries(pParams).forEach((d: any) => {
const val = d[1];
const firstChar = val.charAt(0);
const rest = val.substring(1);
if (firstChar === '$' && vals[rest]) {
pParams[d[0]] = vals[rest];
}
return padding + amount.toString();
});
const data = (
await this.fetchDryEvents({
...pParams,
startTime: from,
finishTime: to,
limit: this.limit,
})
).data;
return data.map((d: ChaosEvent) => ({
title: `Experiment: ${d.experiment}`,
text: `
<span>Status: ${d.finish_time ? 'Finished' : 'Running'}</span>
<span>Started: ${new Date(d.start_time).toLocaleString('en-US', { timeZone: timezone })}</span>
${
d.finish_time
? `<span>Ended: ${new Date(d.finish_time).toLocaleString('en-US', {
timeZone: timezone,
})}</span>`
: ''
}
let offset: number = date.getTimezoneOffset();
`,
tags: [`namespace:${d.namespace}`, `kind:${d.kind}`],
time: Date.parse(d.start_time),
timeEnd: Date.parse(d.finish_time),
isRegion: true,
}));
}
async metricFindQuery(query: ChaosMeshVariableQuery) {
const { metric, experimentName } = query;
if (metric === 'experiment' && experimentName) {
return (
pad(date.getFullYear(), 4) +
'-' +
pad(date.getMonth() + 1, 2) +
'-' +
pad(date.getDate(), 2) +
'T' +
pad(date.getHours(), 2) +
':' +
pad(date.getMinutes(), 2) +
':' +
pad(date.getSeconds(), 2) +
'.' +
pad(date.getMilliseconds(), 3) +
(offset > 0 ? '-' : '+') +
pad(Math.floor(Math.abs(offset) / 60), 2) +
':' +
pad(Math.abs(offset) % 60, 2)
);
await this.fetchDryEvents({
limit: this.limit,
} as ChaosMeshQuery)
).data
.filter(d => d.experiment.includes(experimentName))
.map(d => ({ text: d.experiment }));
}
if (metric === 'namespace') {
return (await this.fetchAvailableNamespaces()).data.map(d => ({ text: d }));
}
if (metric === 'kind') {
return kindOptions.map(d => ({ text: d.value as string }));
}
return [];
}
async testDatasource() {
// Implement a health check for your data source.
try {
await this.fetchConfig();
const response = await this.checkLiveness();
if (!response) {
return { status: 'error', message: 'Cannot connect to Data source' };
}
return response.status === 200
? { status: 'success', message: 'Data source is working' }
: { status: 'error', message: response.error };
}
async annotationQuery(options: AnnotationQueryRequest<ChaosEventsQuery>): Promise<AnnotationEvent[]> {
const { range } = options;
const query = defaults(options.annotation, defaultQuery);
query.startTime = this.toRFC3339TimeStamp(range.from.toDate());
query.finishTime = this.toRFC3339TimeStamp(range.to.toDate());
query.limit = this.defaultLimit;
const response: ChaosEventsQueryResponse = await this.queryEvents(query);
return response.data.map((event: ChaosEvent) => {
const eventPage = `${this.defaultUrl}/experiments/${event.experiment_id}?name=${event.experiment}&event=${event.id}`;
const regionEvent: AnnotationEvent = {
title: `${event.experiment}`,
time: Date.parse(event.start_time),
timeEnd: Date.parse(event.finish_time),
isRegion: true,
text: `<a target="_blank" href=${eventPage}>Event Details</a>`,
tags: [`kind:${event.kind}`, `namespace:${event.namespace}`],
return {
status: 'success',
message: 'Success',
};
} catch (error) {
return {
status: 'error',
message: error,
};
return regionEvent;
});
}
}
private constructPivotalParams(query: Partial<ChaosMeshQuery>) {
const result: typeof query = {};
const { experimentName, namespace, kind } = query;
if (experimentName) {
result.experimentName = experimentName;
}
if (namespace) {
result.namespace = namespace;
}
if (kind) {
result.kind = kind;
}
return result;
}
}

View File

@ -1,124 +1,109 @@
import defaults from 'lodash/defaults';
import React, { ChangeEvent, PureComponent } from 'react';
import { ChaosMeshOptions, ChaosMeshQuery, ExperimentKind, defaultQuery, kindOptions } from './types';
import { InlineFormLabel, LegacyForms } from '@grafana/ui';
import { QueryEditorProps, SelectableValue } from '@grafana/data';
import React, { PureComponent, SyntheticEvent } from 'react';
import { DataSource } from './DataSource';
import { defaultQuery, ChaosMeshOptions, ChaosEventsQuery } from './types';
import defaults from 'lodash/defaults';
const { Input, Select } = LegacyForms;
const MarginRight4: React.FC = ({ children }) => <div style={{ marginRight: 4 }}>{children}</div>;
type Props = QueryEditorProps<DataSource, ChaosEventsQuery, ChaosMeshOptions>;
const kindOptions: Array<SelectableValue<string>> = [
{ value: 'PodChaos', label: 'Pod Chaos' },
{ value: 'NetworkChaos', label: 'Network Chaos' },
{ value: 'IOChaos', label: 'IO Chaos' },
{ value: 'TimeChaos', label: 'Time Chaos' },
{ value: 'KernelChaos', label: 'Kernel Chaos' },
{ value: 'StressChaos', label: 'Stress Chaos' },
];
type Props = QueryEditorProps<DataSource, ChaosMeshQuery, ChaosMeshOptions>;
interface State {
allNamespaces: Array<SelectableValue<string>>;
dnsServerCreate: boolean;
availableNamespaces: Array<SelectableValue<string>>;
experimentName: string;
namespace: string;
experiment: string;
kind: string;
kind: ExperimentKind;
}
export class QueryEditor extends PureComponent<Props, State> {
query: ChaosEventsQuery;
dataSource: DataSource;
query: ChaosMeshQuery;
datasource: DataSource;
constructor(props: Props) {
super(props);
this.dataSource = this.props.datasource;
this.query = defaults(this.props.query, defaultQuery);
this.datasource = this.props.datasource;
this.state = {
allNamespaces: [],
namespace: this.query.namespace!,
kind: this.query.kind,
experiment: this.query.experiment!,
dnsServerCreate: false,
availableNamespaces: [],
experimentName: this.query.experimentName || '',
namespace: this.query.namespace || 'default',
kind: this.query.kind || 'PodChaos',
};
}
componentDidMount() {
this.dataSource.queryNamespaces().then((results: any) => {
this.setState({ allNamespaces: results.data.map((ns: string) => ({ label: ns, value: ns })) });
});
this.datasource
.fetchAvailableNamespaces()
.then(({ data }) => this.setState({ availableNamespaces: data.map(d => ({ label: d, value: d })) }));
this.datasource.fetchConfig().then(({ data }) => this.setState({ dnsServerCreate: data.dns_server_create }));
}
onNamespaceChange = (item: SelectableValue<string>) => {
const namespace = item.value!;
this.query.namespace = namespace;
this.setState({ namespace }, this.onRunQuery);
onExperimentNameChange = (e: SyntheticEvent<HTMLInputElement>) => {
const name = e.currentTarget.value;
this.query.experimentName = name;
this.setState({ experimentName: name });
};
onKindChange = (item: SelectableValue<string>) => {
const kind = item.value!;
this.query.kind = kind;
this.setState({ kind }, this.onRunQuery);
onNamespaceChange = (option: SelectableValue<string>) => {
const value = option.value!;
this.query.namespace = value;
this.setState({ namespace: value }, this.onRunQuery);
};
onExperimentChange = (event: ChangeEvent<HTMLInputElement>) => {
const experiment = event.target.value;
this.query.experiment = experiment;
this.setState({ experiment });
onKindChange = (option: SelectableValue<ExperimentKind>) => {
const value = option.value!;
this.query.kind = value;
this.setState({ kind: value }, this.onRunQuery);
};
onRunQuery = () => {
const { query } = this;
this.props.onChange(query);
this.props.onChange(this.query);
this.props.onRunQuery();
};
render() {
const { experiment, allNamespaces } = this.state;
const selectedKind = kindOptions.find(o => o.value === this.query.kind);
const selectedNamespace = allNamespaces.find(o => o.value === this.query.namespace);
const { dnsServerCreate, availableNamespaces, experimentName, namespace, kind } = this.state;
return (
<div>
<div className="gf-form-inline">
<MarginRight4>
<div className="gf-form">
<InlineFormLabel width={12} tooltip="Namespace of Chaos Experiments">
Experiment Namespace
<InlineFormLabel tooltip="Filter chaos events by specifying the name of Experiments.">
Experiment
</InlineFormLabel>
<Input value={experimentName} onChange={this.onExperimentNameChange} onBlur={this.onRunQuery} />
</div>
</MarginRight4>
<MarginRight4>
<div className="gf-form">
<InlineFormLabel tooltip="Filter chaos events by choosing the Namespace of Experiments.">
Namespace
</InlineFormLabel>
<Select
value={selectedNamespace}
options={availableNamespaces}
value={availableNamespaces.find(n => n.value === namespace)}
onChange={this.onNamespaceChange}
onBlur={this.onRunQuery}
options={allNamespaces}
isSearchable={false}
/>
</div>
</MarginRight4>
<MarginRight4>
<div className="gf-form">
<InlineFormLabel width={10} tooltip="Name of the Chaos Experiment">
Experiment Name
</InlineFormLabel>
<Input
type="text"
className="gf-form-input"
value={experiment}
onChange={this.onExperimentChange}
onBlur={this.onRunQuery}
/>
</div>
</div>
<div className="gf-form">
<InlineFormLabel width={8}>Chaos Kind</InlineFormLabel>
<InlineFormLabel tooltip="Filter chaos events by choosing the Kind of Experiments.">Kind</InlineFormLabel>
<Select
width={8}
value={selectedKind}
options={dnsServerCreate ? kindOptions : kindOptions.filter(kind => kind.value !== 'DNSChaos')}
value={kindOptions.find(k => k.value === kind)}
onChange={this.onKindChange}
onBlur={this.onRunQuery}
options={kindOptions}
isSearchable={false}
/>
</div>
</MarginRight4>
</div>
);
}

View File

@ -0,0 +1,59 @@
import { InlineFormLabel, LegacyForms } from '@grafana/ui';
import React, { SyntheticEvent, useEffect, useState } from 'react';
import { ChaosMeshVariableQuery } from './types';
import { SelectableValue } from '@grafana/data';
const { Input, Select } = LegacyForms;
const metricOptions: Array<SelectableValue<string>> = [
{ label: 'Experiment', value: 'experiment' },
{ label: 'Namespace', value: 'namespace' },
{ label: 'Kind', value: 'kind' },
];
interface VariableQueryProps {
query: ChaosMeshVariableQuery;
onChange: (query: ChaosMeshVariableQuery, definition: string) => void;
}
export const VariableQueryEditor: React.FC<VariableQueryProps> = ({ query, onChange }) => {
const [state, setState] = useState(query.metric ? query : { ...query, metric: 'experiment' as 'experiment' });
const onMetricChange = (option: SelectableValue<string>) => {
setState({ ...state, metric: option.value! as any });
};
const onInputChange = (e: SyntheticEvent<HTMLInputElement>) => {
setState({ ...state, [e.currentTarget.name]: e.currentTarget.value });
};
const onRunQuery = () => onChange(state, `metric: ${state.metric}`);
useEffect(() => {
onRunQuery();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [state.metric]);
return (
<>
<div className="gf-form">
<InlineFormLabel tooltip="Specify the data metric.">Metric</InlineFormLabel>
<Select
options={metricOptions}
value={metricOptions.find(m => m.value === state.metric)}
onChange={onMetricChange}
/>
</div>
{state.metric === 'experiment' && (
<div className="gf-form">
<InlineFormLabel tooltip="Filter chaos events by specifying the name of Experiments. Support fuzzy matching. Only available when the metric is Experiment.">
Experiment
</InlineFormLabel>
<Input name="experimentName" value={state.experimentName} onChange={onInputChange} onBlur={onRunQuery} />
</div>
)}
</>
);
};

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 8.6 KiB

After

Width:  |  Height:  |  Size: 19 KiB

View File

@ -1,11 +1,12 @@
import { DataSourcePlugin } from '@grafana/data';
import { DataSource } from './DataSource';
import { AnnotationQueryEditor } from './AnnotationQueryEditor';
import { ConfigEditor } from './ConfigEditor';
import { DataSource } from './DataSource';
import { DataSourcePlugin } from '@grafana/data';
import { QueryEditor } from './QueryEditor';
import { ChaosEventsQuery, ChaosMeshOptions } from './types';
import { AnnotationsQueryCtrl } from './AnnotationsQueryCtrl';
import { VariableQueryEditor } from './VariableQueryEditor';
export const plugin = new DataSourcePlugin<DataSource, ChaosEventsQuery, ChaosMeshOptions>(DataSource)
export const plugin = new DataSourcePlugin(DataSource)
.setConfigEditor(ConfigEditor)
.setQueryEditor(QueryEditor)
.setAnnotationQueryCtrl(AnnotationsQueryCtrl);
.setAnnotationQueryCtrl(AnnotationQueryEditor)
.setVariableQueryEditor(VariableQueryEditor);

View File

@ -1,23 +1,22 @@
<div class="gf-form-group">
<div class="gf-form">
<span class="gf-form-label width-10">Kind</span>
<div class="gf-form-select-wrapper width-12">
<select class="gf-form-input" ng-model="ctrl.annotation.kind" ng-options="f.value as f.text for f in ctrl.kinds">
</select>
</div>
<label class="gf-form-label width-10">Experiment</label>
<input type="text" class="gf-form-input max-width-12" ng-model="ctrl.annotation.experimentName" />
</div>
<div class="gf-form">
<span class="gf-form-label width-10">Experiment Namespace</span>
<div class="gf-form-select-wrapper width-12">
<label class="gf-form-label width-10">Namespace</label>
<input type="text" class="gf-form-input max-width-12" ng-model="ctrl.annotation.namespace" />
</div>
<div class="gf-form">
<label class="gf-form-label width-10">Kind</label>
<div class="gf-form-select-wrapper">
<select
class="gf-form-input service-dropdown"
ng-model="ctrl.annotation.namespace"
ng-options="f.value as f.text for f in ctrl.namespaces"
class="gf-form-input width-12"
ng-model="ctrl.annotation.kind"
ng-options="f.value as f.label for f in ctrl.kindOptions"
></select>
</div>
</div>
<div class="gf-form">
<span class="gf-form-label width-10">Experiment Name</span>
<input type="text" class="gf-form-input max-width-12" ng-model='ctrl.annotation.experiment'/>
</div>
</div>

View File

@ -2,39 +2,35 @@
"type": "datasource",
"name": "Chaos Mesh",
"id": "yeya24-chaosmesh-datasource",
"category": "cloud",
"metrics": true,
"annotations": true,
"logs": false,
"streaming": false,
"tracing": false,
"info": {
"description": "A Chaos Engineering Platform for Kubernetes",
"description": "Chaos Mesh (A Chaos Engineering Platform for Kubernetes) Datasource",
"author": {
"name": "yeya24",
"url": "https://github.com/yeya24"
"name": "Yue Yang",
"email": "g1enyy0ung@gmail.com",
"url": "https://github.com/g1eny0ung"
},
"keywords": [
"chaos"
],
"keywords": ["Cloud", "Chaos Engineering", "Chaos Mesh"],
"logos": {
"small": "img/logo.svg",
"large": "img/logo.svg"
},
"links": [
{
"name": "Learn more",
"url": "https://chaos-mesh.org/"
},
{
"name": "Website",
"name": "GitHub",
"url": "https://github.com/chaos-mesh/chaos-mesh-datasource"
},
{
"name": "License",
"url": "https://github.com/chaos-mesh/chaos-mesh-datasource/blob/master/LICENSE"
},
{
"name": "Chaos Mesh Website",
"url": "https://chaos-mesh.org/"
}
],
"screenshots": [],
"version": "0.1.2",
"updated": "%TODAY%"
},

View File

@ -1,38 +1,53 @@
import { DataQuery, DataSourceJsonData } from '@grafana/data';
import { DataQuery, DataSourceJsonData, SelectableValue } from '@grafana/data';
export interface ChaosEventsQuery extends DataQuery {
export type ExperimentKind =
| 'PodChaos'
| 'NetworkChaos'
| 'IoChaos'
| 'KernelChaos'
| 'TimeChaos'
| 'StressChaos'
| 'DNSChaos';
export const kindOptions: Array<SelectableValue<ExperimentKind>> = [
{ label: 'Pod Chaos', value: 'PodChaos' },
{ label: 'Network Chaos', value: 'NetworkChaos' },
{ label: 'IO Chaos', value: 'IoChaos' },
{ label: 'Time Chaos', value: 'TimeChaos' },
{ label: 'Kernel Chaos', value: 'KernelChaos' },
{ label: 'Stress Chaos', value: 'StressChaos' },
{ label: 'DNS Chaos', value: 'DNSChaos' },
];
export interface ChaosMeshQuery extends DataQuery {
experimentName?: string;
namespace?: string;
kind: string;
experiment?: string;
kind?: ExperimentKind;
startTime: string;
finishTime: string;
limit: number;
}
export const defaultQuery: Partial<ChaosEventsQuery> = {
export const defaultQuery: Partial<ChaosMeshQuery> = {
namespace: 'default',
kind: 'PodChaos',
};
/**
* These are options configured for each DataSource instance
*/
export interface ChaosMeshVariableQuery {
metric: 'experiment' | 'namespace' | 'kind';
experimentName?: string;
}
export interface ChaosMeshOptions extends DataSourceJsonData {
defaultUrl: string;
limit: number;
limit?: number;
}
export interface ChaosEvent {
id: number;
experiment_id: string;
experiment: string;
namespace: string;
kind: string;
kind: ExperimentKind;
message: string;
start_time: string;
finish_time: string;
}
export interface ChaosEventsQueryResponse {
status: number;
data: ChaosEvent[];
}

View File

@ -2,7 +2,6 @@
"extends": "./node_modules/@grafana/toolkit/src/config/tsconfig.plugin.json",
"include": ["src", "types"],
"compilerOptions": {
"jsx": "react",
"rootDir": "./src",
"baseUrl": "./src",
"typeRoots": ["./node_modules/@types"]

6911
yarn.lock

File diff suppressed because it is too large Load Diff