[home]开源官网初始化

This commit is contained in:
tomsun28
2022-02-02 22:49:50 +08:00
parent 9347097905
commit c47706be17
132 changed files with 15971 additions and 1 deletions

View File

@@ -0,0 +1,81 @@
---
id: custom-datasource
title: 自定义数据源
sidebar_label: 自定义数据源
---
## 自定义数据源
自定义前建议了解`sureness`处理流程和提供的扩展接口,详见 [进阶扩展](/docs/advanced/extend-point)
- `PathTreeProvider`: 资源的数据源接口,实现从数据库,文本等加载数据,加载到对应的资源权限匹配器`DefaultPathRoleMatcher`
- `SurenessAccountProvider`: 用户的账户密钥信息接口,实现从数据库,文本等加载数据,加载到需要账户数据的`processor`
首先我们先来认识下sureness提供的两个用户信息和资源权限信息的接口用户可以实现这些接口自定义从不同的数据源给sureness提供数据。
当我们把项目从配置文件模式切换成数据库模式时,也只是简单替换了这些接口的实现类而已。
一. `PathTreeProvider` 资源权限配置信息的数据源接口,我们可以实现从数据库,文本等加载接口想要的资源权限配置数据
````
public interface PathTreeProvider {
Set<String> providePathData();
Set<String> provideExcludedResource();
}
````
此接口主要是需要实现上面这两个方法providePathData是加载资源权限配置信息也就是我们配置文件模式下sureness.yml的resourceRole信息列
provideExcludedResource是加载哪些资源可以被过滤不认证鉴权也就是sureness.yml下的excludedResource信息列如下。
````
resourceRole:
- /api/v2/host===post===[role2,role3,role4]
- /api/v2/host===get===[role2,role3,role4]
- /api/v2/host===delete===[role2,role3,role4]
- /api/v2/host===put===[role2,role3,role4]
- /api/mi/**===put===[role2,role3,role4]
- /api/v1/getSource1===get===[role1,role2]
- /api/v2/getSource2/*/*===get===[role2]
excludedResource:
- /api/v1/source3===get
- /api/v3/host===get
- /**/*.css===get
- /**/*.ico===get
- /**/*.png===get
````
而当我们使用数据库模式时实现这些信息从数据库关联读取就ok了规范返回 eg: /api/v2/host===post===[role2,role3,role4] 格式的数据列,
具体的数据库实现类参考类 - [DatabasePathTreeProvider](https://github.com/tomsun28/sureness/blob/master/sample-tom/src/main/java/com/usthe/sureness/sample/tom/sureness/provider/DatabasePathTreeProvider.java)
二. `SurenessAccountProvider`这第二个相关的接口就是用户的账户密钥信息提供接口,我们需要实现从数据库或者文本等其他数据源那里去加载我们想要的用户的账户信息数据,
这些数据提供需要账户数据的processor进行用户的认证。
````
public interface SurenessAccountProvider {
SurenessAccount loadAccount(String appId);
}
````
此接口主要需要实现上面这个loadAccount方法通过用户的唯一标识appid来从数据库或者redis缓存中查找到用户的账户信息返回即可。
用户账户信息类SurenessAccount如下
````
public class DefaultAccount implements SurenessAccount {
private String appId;
private String password;
private String salt;
private List<String> ownRoles;
private boolean disabledAccount;
private boolean excessiveAttempts;
}
````
比较简单主要是需要提供用户的密码相关信息即可供sureness认证时密钥判断正确与否。
这个具体的数据库接口实现可参考类 - [DatabaseAccountProvider](https://github.com/tomsun28/sureness/blob/master/sample-tom/src/main/java/com/usthe/sureness/sample/tom/sureness/provider/DatabaseAccountProvider.java)
具体扩展实践请参考 [Springboot项目集成-数据库方案](/docs/integrate/sample-tom)

View File

@@ -0,0 +1,35 @@
---
id: custom-processor
title: 自定义processor
sidebar_label: 自定义processor
---
processor就是对请求的用户账户信息subject真正的认证鉴权处理器我们需要实现BaseProcessor接口来实现我们自定义的认证鉴权方式。
sureness已经内置基于账户密码认证方式处理PasswordSubject的PasswordProcessor基于jwt认证方式处理JwtSubject的JwtProcessor等。
自定义前建议了解`sureness`处理流程和提供的扩展接口,详见 [进阶扩展](/docs/advanced/extend-point)
- `Processor`: `Subject`处理接口,根据Subject信息,进行认证鉴权
```
public abstract class BaseProcessor implements Processor{
public abstract boolean canSupportSubjectClass(Class<?> var);
public abstract Subject authenticated (Subject var) throws SurenessAuthenticationException;
public abstract void authorized(Subject var) throws SurenessAuthorizationException;
}
```
上面就是BaseProcessor的一些重要接口方法自定义processor需要我们去实现这些方法。
- `canSupportSubjectClass` 判断是否支持入参的此Subject类类型比如 JwtProcessor只支持JwtSubject, PasswordProcessor只支持PasswordSubject
- `authenticated` 对subject进行认证根据传入的subject信息和系统内信息进行请求用户的账户认证
- `authorized` 对subject进行鉴权鉴权判断此用户是否拥有其访问api的访问权限
sureness使用异常流程模型以上的认证失败或鉴权失败都会抛出不同类型的异常用户在最外部捕获判断实现接下来的流程。
sureness默认异常类型参考 [默认异常类型](/docs/start/default-exception)
具体扩展实践请参考 [Springboot项目集成-数据库方案](/docs/integrate/sample-tom)

View File

@@ -0,0 +1,20 @@
---
id: custom-subject-creator
title: 自定义subject creator
sidebar_label: 自定义subject creator
---
自定义`subject creator`是我们使用频率最高的扩展,当请求体对象并不是`servlet`或者`jax-rs`标准`api`时,
或者我们从request请求的不同地方获取账户信息时我们就需要自定义`subject creator`,
使其通过请求对象获取我们需要的请求信息(请求路径,请求方法,认证信息等), 从而创建出对应的`subject`.
sureness已经内置能创建出基于账户密码的PasswordSubject的BasicSubjectServletCreator
和创建出jwt类型JwtSubject的JwtSubjectServletCreator等当然我们可以自定义自己需要的subjectCreator来创建subject
自定义前建议了解`sureness`处理流程和提供的扩展接口,详见 [进阶扩展](/docs/advanced/extend-point)
- `SubjectCreate`: 创建`Subject`接口,根据请求内容创建不同类型的`Subject`对象
实现`SubjectCreate`接口方法,根据request请求的内容创建出对应需要的的`subject`
具体扩展实践请参考 [sample-spring-webflux项目集成案例](/docs/integrate/sample-spring-webflux)

View File

@@ -0,0 +1,20 @@
---
id: custom-subject
title: 自定义subject
sidebar_label: 自定义subject
---
subject包含的就是我们request请求所带的用户信息sureness已经内置基于账户密码的PasswordSubject
基于jwt的JwtSubject等当然我们可以自定义自己需要的subject来扩充自己的用户信息
自定义前建议了解`sureness`处理流程和提供的扩展接口,详见 [进阶扩展](/docs/advanced/extend-point)
- `Subject`: 认证鉴权对象接口,提供访问对象的账户密钥,请求资源,角色等信息
自定义subject需要走以下流程
1. 实现`Subject`接口,添加自定义的`subject`内容
2. 实现`SubjectCreate`接口方法,创建出自定义的`subject` 参考[自定义Subject Creator](/docs/advanced/custom-subject-creator)
3. 实现`Processor`接口,支持处理自定义的`subject` 参考[自定义Processor](/docs/advanced/custom-processor)
具体扩展实践请参考 [使用sureness30分钟项目集成案例](/docs/integrate/sample-tom)

View File

@@ -0,0 +1,22 @@
---
id: extend-point
title: 进阶扩展
sidebar_label: 扩展点
---
`sureness`支持自定义`subject`,自定义注册`subjectCreator`,自定义`processor`处理器,自定义数据源加载器等。
进阶自定义扩展之前我们先来了解下sureness的大致流程
![flow](/img/docs/flow-cn.png)
如上面的流程所讲Subject被SubjectCreate根据request请求体所创造不同的认证鉴权处理器Processor来处理所支持的Subject。
sureness提供了下面这些常用接口作为扩展点:
- `Subject`: 认证鉴权对象接口,提供访问对象的账户密钥,请求资源,角色等信息
- `SubjectCreate`: 创建`Subject`接口,根据请求内容创建不同类型的`Subject`对象
- `Processor`: `Subject`处理接口,根据Subject信息,进行认证鉴权
- `PathTreeProvider`: 资源的数据源接口,实现从数据库,文本等加载数据
- `SurenessAccountProvider`: 用户的账户密钥信息接口,实现从数据库,文本等加载数据

65
home/docs/contributing.md Normal file
View File

@@ -0,0 +1,65 @@
---
id: contributing
title: 参与贡献
sidebar_label: 参与贡献
---
Contributing to Sureness
=======================================
Very welcome to Contribute this project, go further and better with sureness.
Firstly, thanks for your interest in contributing! I hope that this will be a pleasant first experience for you, and that you will return to continue contributing.
Components of Repository:
- [sureness's kernel code--sureness-core](https://github.com/usthe/sureness/tree/master/core)
- [sureness integration springboot sample(configuration file scheme)--sample-bootstrap](https://github.com/usthe/sureness/tree/master/sample-bootstrap)
- [sureness integration springboot sample(database scheme)-sample-tom](https://github.com/usthe/sureness/tree/master/sample-tom)
- [sample projects using sureness in each framework(javalin,ktor,quarkus)--samples](https://github.com/usthe/sureness/tree/master/samples)
## How to contribute?
Most of the contributions that we receive are code contributions, but you can
also contribute to the documentation or simply report solid bugs
for us to fix.
For new contributors, please take a look at issues or pull requests with a tag called below.
[Good first issue](https://github.com/usthe/sureness/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22)
[Help wanted](https://github.com/usthe/sureness/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22)
[Good first pull request](https://github.com/usthe/sureness/issues?q=label%3A%22good+first+pull+request%22+)
## Join discussion
[Github Discussion](https://github.com/usthe/sureness/discussions)
[Gitter Channel](https://gitter.im/usthe/sureness)
----
----
参与贡献
=======================================
非常欢迎参与项目贡献,我们致力于维护一个互相帮助的快乐社区。
仓库的组成部分:
- [sureness的核心代码--sureness-core](https://github.com/usthe/sureness/tree/master/core)
- [使用sureness集成springboot搭建权限项目(配置文件方案)--sample-bootstrap](https://github.com/usthe/sureness/tree/master/sample-bootstrap)
- [使用sureness集成springboot搭建权限项目(数据库方案)--sample-tom](https://github.com/usthe/sureness/tree/master/sample-tom)
- [各个框架使用sureness的样例项目(javalin,ktor,quarkus)--samples](https://github.com/usthe/sureness/tree/master/samples)
## 如何贡献?
我们不仅仅接收代码的贡献提交您也可以通过提交文档的更新或者BUG的报告来参与社区贡献。
如果是新的贡献者请首先了解参考如下样例的提交Issues,提交Pull Requests如果工作。
[Good first issue](https://github.com/usthe/sureness/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22)
[Help wanted](https://github.com/usthe/sureness/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22)
[Good first pull request](https://github.com/usthe/sureness/issues?q=label%3A%22good+first+pull+request%22+)
## 加入交流
[Github Discussion](https://github.com/usthe/sureness/discussions)
[Gitter Channel](https://gitter.im/usthe/sureness)
QQ交流群390083213
微信公众号sureness

13
home/docs/design.md Normal file
View File

@@ -0,0 +1,13 @@
---
id: design
title: 设计文档
sidebar_label: 设计文档
---
### 高性能匹配
![pathRoleMatcher](/img/docs/PathRoleMatcher.svg)
### 处理流程
![sureness-core](/img/docs/sureness-core.svg)

View File

@@ -0,0 +1,14 @@
---
id: sample-bootstrap
title: Springboot项目集成-配置文件方案
sidebar_label: Springboot项目集成-配置文件方案
---
[Springboot项目集成-配置文件方案代码仓库地址](https://github.com/tomsun28/sureness/tree/master/sample-bootstrap)
- 基于`springboot`
- 从默认的配置文件`sureness.yml`加载账户信息,资源角色,过滤资源等信息
- 使用默认的`sureness-config`
- 使用默认的`JWT, Basic Auth, Digest Auth`方式认证鉴权
- 保护入口: `SurenessFilterExample`
- 推荐使用`postman`测试,测试样例为`sample-bootstrap-postman.json`,导入`postman`即可

View File

@@ -0,0 +1,296 @@
---
id: sample-javalin
title: Javalin项目集成
sidebar_label: Javalin项目集成
---
# Using Sureness to protect the security of Javalin REST API
[javalin-sureness sample repository](https://github.com/tomsun28/sureness/tree/master/samples/javalin-sureness)
Using Sureness to secure Javalin REST API by providing authentication(JWT,Basic,Digest) and authorization(RBAC)
## What You Will Learn
* Creating a simple REST API using Javalin
* Learn how to integrate Sureness into a Javalin application
* Learn how to issue a JWT
* Test API authentication - use JWT Auth, Basic Auth, Digest Auth to test the security of the REST API
* Test API authorization - use different users to verify that they can access the REST API
The tutorial assumes that you know what JWT, Basic Auth, Digest Auth, RBAC are. If you
do not, then you can check [jwt](https://jwt.io/introduction/), [basic auth](https://docs.oracle.com/cd/E50612_01/doc.11122/user_guide/content/authn_http_basic.html) , [digest auth](https://docs.oracle.com/cd/E50612_01/doc.11122/user_guide/content/authn_http_digest.html), [rbac](https://en.wikipedia.org/wiki/Role-based_access_control) for an introduction.
## Setting Up Dependencies
First, you will need to create a maven project and add Javalin, Sureness dependencies coordinate
````
<dependency>
<groupId>io.javalin</groupId>
<artifactId>javalin</artifactId>
<version>{{site.javalinversion}}</version>
</dependency>
<dependency>
<groupId>com.usthe.sureness</groupId>
<artifactId>sureness-core</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.30</version>
</dependency>
````
## Setting Up Javalin and Create REST API
We need to create a simple Javalin app and provide some REST API for test.
```
// init javalin
Javalin app = Javalin.create().start(8088);
```
```
// create simple rest api
// simple rest api
app.routes(() ->
path("api", () -> {
path("v3", () -> {
get("host", ctx -> ctx.result("get /api/v3/host success"));
put("book", ctx -> ctx.result("put /api/v3/book success"));
});
path("v2", () -> {
path("host", () -> {
get(ctx -> ctx.result("get /api/v2/host success"));
post(ctx -> ctx.result("post /api/v2/host success"));
put(ctx -> ctx.result("put /api/v2/host success"));
delete(ctx -> ctx.result("delete /api/v2/host success"));
});
});
path("v1", () -> {
path("source1", () -> {
get(ctx -> ctx.result("get /api/v1/source1 success"));
post(ctx -> ctx.result("post /api/v1/source1 success"));
put(ctx -> ctx.result("put /api/v1/source1 success"));
delete(ctx -> ctx.result("delete /api/v1/source1 success"));
});
});
}));
```
## Setting Up Sureness
#### 1. Use the Default Configuration to Configure Sureness
The default configuration -`DefaultSurenessConfig` uses the document datasource `sureness.yml` as the auth datasource.
It supports JWT, Basic Auth, Digest Auth authentication.
```
public static void main(String[] args) {
// init sureness default config
new DefaultSurenessConfig();
}
```
#### 2. Config Document Datasource - `sureness.yml`
Sureness authentication requires us to provide our own account data, role permission data. These data may come from document, databases,, annotations, etc. When we use sureness default configuration above, the datasource is document - `sureness.yml`.
Create a file named `sureness.yml` in the `resource` directory. Configure account data, role permission data in the `sureness.yml`. eg:
````yaml
## -- sureness.yml document dataSource-- ##
# load api resource which need be protected, config role who can access these resource.
# resources that are not configured are also authenticated and protected by default, but not authorized
# eg: /api/v2/host===post===[role2,role3] means /api/v2/host===post can be access by role2,role3
# eg: /api/v1/source2===get===[] means /api/v1/source2===get can not be access by any role
resourceRole:
- /api/v1/source1===get===[role2]
- /api/v1/source1===post===[role1]
- /api/v1/source1===delete===[role3]
- /api/v1/source1===put===[role1,role2]
- /api/v1/source2===get===[]
- /api/v2/host===post===[role2,role3]
- /api/v2/host===get===[role2,role3]
- /api/v2/host===delete===[role2,role3]
- /api/v2/host===put===[role2,role3]
- /api/v3/*===*===[role1,role2,role3]
# load api resource which do not need be protected, means them need be excluded.
# these api resource can be access by everyone
excludedResource:
- /api/v3/host===get
- /**/*.html===get
- /**/*.js===get
- /**/*.css===get
- /**/*.ico===get
# account info
# there are three account: admin, root, tom
# eg: admin has [role1,role2] ROLE, unencrypted password is admin, encrypted password is 0192023A7BBD73250516F069DF18B500
# eg: root has role1, unencrypted password is 23456
# eg: tom has role3, unencrypted password is 32113
account:
- appId: admin
# if add salt, the password is encrypted password - the result: MD5(password+salt)
# digest auth not support encrypted password
# if no salt, the password is unencrypted password
credential: 0192023A7BBD73250516F069DF18B500
salt: 123
role: [role1,role2]
- appId: root
credential: 23456
role: [role1,role2]
- appId: tom
credential: 32113
role: [role3]
````
#### 3. Add an Interceptor Intercepting All Requests
The essence of sureness is to intercept all rest requests for authenticating and authorizing. The interceptor can be a filter or interceptor, it intercepts all request to check them. In Javalin, we use `app.before()`.
```
// intercept all rest requests for authenticating and authorizing
app.before(ctx -> {
SubjectSum subject = SurenessSecurityManager.getInstance().checkIn(ctx.req);
// when auth error , the exception throw, you should use app.exception() catch it and define return
if (subject != null) {
SurenessContextHolder.bindSubject(subject);
}
});
app.after(ctx -> SurenessContextHolder.unbindSubject());
```
#### 4. Last, Implement Auth Exception Handling Process
Sureness uses exception handling process:
- If auth success, method - `checkIn()` will return a `SubjectSum` object containing user information.
- If auth failure, method - `checkIn()` will throw different types of auth exceptions.
We need to continue the subsequent process based on these exceptions.(eg: return the request response)
Here we need to customize the exceptions thrown by `checkIn`, passed directly when auth success, catch exception when auth failure and do something:
````
// when auth error , the exception throw, you should use app.exception() catch it and define return
app.exception(UnknownAccountException.class, (e, ctx) -> {
log.debug("this request user account not exist");
ctx.status(401).result(e.getMessage());
}).exception(IncorrectCredentialsException.class, (e, ctx) -> {
log.debug("this account credential is incorrect");
ctx.status(401).result(e.getMessage());
}).exception(ExpiredCredentialsException.class, (e, ctx) -> {
log.debug("this account credential expired");
ctx.status(401).result(e.getMessage());
}).exception(NeedDigestInfoException.class, (e, ctx) -> {
log.debug("you should try once again with digest auth information");
ctx.status(401).header("WWW-Authenticate", e.getAuthenticate());
}).exception(UnauthorizedException.class, (e, ctx) -> {
log.debug("this account can not access this resource");
ctx.status(403).result(e.getMessage());
}).exception(Exception.class, (e, ctx) -> {
log.error("other exception happen: ", e);
ctx.status(500).result(e.getMessage());
});
````
## Provide an Issue JWT Api
Now we provide a REST API to issue JWT. We can use this JWT to test JWT auth.
````
// issue jwt rest api
app.get("/auth/token", ctx -> {
SubjectSum subjectSum = SurenessContextHolder.getBindSubject();
if (subjectSum == null) {
ctx.result("Please auth!");
} else {
String principal = (String) subjectSum.getPrincipal();
List<String> roles = (List<String>) subjectSum.getRoles();
// issue jwt
String jwt = JsonWebTokenUtil.issueJwt(UUID.randomUUID().toString(), principal,
"token-server", 3600L, roles);
ctx.result(jwt);
}
});
````
**All done, we can test now!**
## Test
Through the above steps, a complete auth function project is completed. Someone maybe think that with only these few steps, where is its complete function and what can it support?
This built project is based on the RBAC permission model and supports Baisc authentication, Digest authentication and JWT authentication. It can fine-grained control the user's access to the restful api provided by the Javalin. That is to control which users can access which api.
Let's test it. (we use postman and chrome to test.)
### Test Authentication
#### 1. Basic Auth Test
Use postman Basic auth, as shown below:
* success - input username: admin, password: admin
![success](/img/docs/javalin/test1.PNG)
* fail - input username: admin, password: 12345
![fail](/img/docs/javalin/test2.PNG)
#### 2. Digest Auth Test
Note: If password has been encrypted, Digest auth not support.(So the account admin not support Digest auth).
Use chrome to Digest auth, as shown below:
![success](/img/docs/javalin/test3.PNG)
![success](/img/docs/javalin/test4.PNG)
#### 3. JWT Auth Test
First, we should access **[GET /auth/token]** api to get a JWT to use, as shown below:
![success](/img/docs/javalin/test5.PNG)
Then, use the JWT as Bearer Token to access REST API, as shown below:
![success](/img/docs/javalin/test6.PNG)
### Test Authorization
* success - user **tom** has role **role3**, the api **[DELETE - /api/v2/host]** support **role3** access, so **tom** can access api **[DELETE - /api/v2/host]** success, as shown below:
![success](/img/docs/javalin/test7.PNG)
* fail - user **tom** only has role **role3**, the api **[GET - /api/v1/source1]** only support **role2** access, not support **role3**, so **tom** can not access api **[GET - /api/v1/source1]**, as shown below:
![fail](/img/docs/javalin/test8.PNG)
## Conclusion
Javalin is a framework dedicated to simplicity and ease of use, and so is Sureness.
We hope you enjoy this tutorial. Of course, the tutorial only introduces a simple introduction. Our account data, role permission data can not only be written in `sureness.yml`, but also loaded and obtained from the database and annotations. We can also customize the authentication method, data source, etc.
Finally, thank you again for reading.
[DEMO SOURCE CODE ON GITHUB](https://github.com/usthe/sureness/tree/master/samples/javalin-sureness)

View File

@@ -0,0 +1,17 @@
---
id: sample-ktor
title: Ktor项目集成
sidebar_label: Ktor项目集成
---
[ktor-sureness例子项目仓库地址](https://github.com/tomsun28/sureness/tree/master/samples/ktor-sureness)
- 基于`ktor, servlet`
- 从默认的配置文件`sureness.yml`加载账户信息,资源角色,过滤资源等信息
- 使用默认的`sureness-config`
- 使用默认的`JWT, Basic Auth, Digest Auth`方式认证鉴权
- 例子中包含`REST API`
- 保护入口: `Application.kt`
- 推荐使用`postman`测试

View File

@@ -0,0 +1,423 @@
---
id: sample-micronaut
title: Micronaut项目集成
sidebar_label: Micronaut项目集成
---
Using Sureness to secure micronaut REST API by providing authentication(JWT,Basic,Digest) and authorization(RBAC)
## What You Will Learn
* Creating a simple REST API using micronaut
* Learn how to integrate Sureness into a micronaut application
* Test API authentication - use JWT Auth, Basic Auth, Digest Auth to test the security of the REST API
* Test API authorization - use different users to verify that they can access the REST API
The tutorial assumes that you know what JWT, Basic Auth, Digest Auth, RBAC are. If you
do not, then you can check [jwt](https://jwt.io/introduction/), [basic auth](https://docs.oracle.com/cd/E50612_01/doc.11122/user_guide/content/authn_http_basic.html) , [digest auth](https://docs.oracle.com/cd/E50612_01/doc.11122/user_guide/content/authn_http_digest.html), [rbac](https://en.wikipedia.org/wiki/Role-based_access_control) for an introduction.
## Setting Up Dependencies
First, you will need to create a maven project and add micronautn, Sureness dependencies coordinate
````
<properties>
<release.version>8</release.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<packaging>jar</packaging>
<jdk.version>1.8</jdk.version>
<micronaut.version>2.4.3</micronaut.version>
<micronaut-maven-plugin.version>1.1.8</micronaut-maven-plugin.version>
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
<exec.mainClass>com.usthe.sureness.micronaut.Application</exec.mainClass>
<micronaut.runtime>netty</micronaut.runtime>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-bom</artifactId>
<version>${micronaut.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>com.usthe.sureness</groupId>
<artifactId>sureness-core</artifactId>
</dependency>
<dependency>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-inject</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-validation</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.micronaut.test</groupId>
<artifactId>micronaut-test-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-http-client</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-http-server-netty</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-runtime</artifactId>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>io.micronaut.build</groupId>
<artifactId>micronaut-maven-plugin</artifactId>
<version>${micronaut-maven-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<annotationProcessorPaths combine.children="append">
<path>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-inject-java</artifactId>
<version>${micronaut.version}</version>
</path>
<path>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-validation</artifactId>
<version>${micronaut.version}</version>
</path>
</annotationProcessorPaths>
<compilerArgs>
<arg>-Amicronaut.processing.group=com.usthe.sureness</arg>
<arg>-Amicronaut.processing.module=micronaut-sureness</arg>
</compilerArgs>
</configuration>
</plugin>
</plugins>
</build>
````
- [User Guide](https://docs.micronaut.io/2.4.3/guide/index.html)
- [API Reference](https://docs.micronaut.io/2.4.3/api/index.html)
- [Configuration Reference](https://docs.micronaut.io/2.4.3/guide/configurationreference.html)
- [Micronaut Guides](https://guides.micronaut.io/index.html)
We need to create a simple micronautn app and provide some REST API for test.
## Setting Up Sureness
#### 1.Run Micronaut Application
```
import io.micronaut.runtime.Micronaut;
public class Application{
public static void main(String[] args) {
Micronaut.run(Application.class, args);
}
}
```
#### 2. Config Document Datasource - `sureness.yml`
Sureness authentication requires us to provide our own account data, role permission data. These data may come from document, databases,, annotations, etc. When we use sureness default configuration above, the datasource is document - `sureness.yml`.
Create a file named `sureness.yml` in the `resource` directory. Configure account data, role permission data in the `sureness.yml`. eg:
````yaml
## -- sureness.yml document dataSource-- ##
# load api resource which need be protected, config role who can access these resource.
# resources that are not configured are also authenticated and protected by default, but not authorized
# eg: /api/v2/host===post===[role2,role3] means /api/v2/host===post can be access by role2,role3
# eg: /api/v1/source2===get===[] means /api/v1/source2===get can not be access by any role
resourceRole:
- /api/v1/source1===get===[role2]
- /api/v1/source1===post===[role1]
- /api/v1/source1===delete===[role3]
- /api/v1/source1===put===[role1,role2]
- /api/v1/source2===get===[]
- /api/v2/host===post===[role2,role3]
- /api/v2/host===get===[role2,role3]
- /api/v2/host===delete===[role2,role3]
- /api/v2/host===put===[role2,role3]
- /api/v3/*===*===[role1,role2,role3]
# load api resource which do not need be protected, means them need be excluded.
# these api resource can be access by everyone
excludedResource:
- /api/v3/host===get
- /**/*.html===get
- /**/*.js===get
- /**/*.css===get
- /**/*.ico===get
# account info
# there are three account: admin, root, tom
# eg: admin has [role1,role2] ROLE, unencrypted password is admin, encrypted password is 0192023A7BBD73250516F069DF18B500
# eg: root has role1, unencrypted password is 23456
# eg: tom has role3, unencrypted password is 32113
account:
- appId: admin
# if add salt, the password is encrypted password - the result: MD5(password+salt)
# digest auth not support encrypted password
# if no salt, the password is unencrypted password
credential: 0192023A7BBD73250516F069DF18B500
salt: 123
role: [role1,role2]
- appId: root
credential: 23456
role: [role1,role2]
- appId: tom
credential: 32113
role: [role3]
````
#### 3. Add an Interceptor Intercepting All Requests
The essence of sureness is to intercept all rest requests for authenticating and authorizing. The interceptor can be a filter or interceptor, it intercepts all request to check them. In Micronaut, we use Filter
```java
@Filter("/**")
public class MicronautSurenessFilterExample implements HttpServerFilter {
private static final Logger logger = LoggerFactory.getLogger(MicronautSurenessFilterExample.class);
@Inject
private SurenessSecurityManager securityManager ;
@Override
public Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> request,
ServerFilterChain chain) {
Integer statusCode = null;
String errorMsg = null;
try {
SubjectSum subject =securityManager.checkIn(request);
if (subject != null) {
SurenessContextHolder.bindSubject(subject);
}
} catch (ProcessorNotFoundException | UnknownAccountException | UnsupportedSubjectException e4) {
logger.debug("this request is illegal");
statusCode = HttpStatus.BAD_REQUEST.getCode();
errorMsg = e4.getMessage();
} catch (DisabledAccountException | ExcessiveAttemptsException e2 ) {
logger.debug("the account is disabled");
statusCode = HttpStatus.FORBIDDEN.getCode();
errorMsg = e2.getMessage();
} catch (IncorrectCredentialsException | ExpiredCredentialsException e3) {
logger.debug("this account credential is incorrect or expired");
statusCode = HttpStatus.FORBIDDEN.getCode();
errorMsg = e3.getMessage();
} catch (UnauthorizedException e5) {
logger.debug("this account can not access this resource");
statusCode = HttpStatus.FORBIDDEN.getCode();
errorMsg = e5.getMessage();
} catch (RuntimeException e) {
logger.error("other exception happen: ", e);
statusCode = HttpStatus.FORBIDDEN.getCode();
errorMsg = e.getMessage();
}
if (statusCode != null && errorMsg != null) {
String finalErrorMsg = errorMsg;
Integer finalStatusCode = statusCode;
logger.info(statusCode+"--->"+errorMsg);
try {
URI location = new URI("/auth/error");
request = request.mutate().headers(httpHeaders -> {
httpHeaders.add("statusCode", String.valueOf(finalStatusCode));
httpHeaders.add("errorMsg", finalErrorMsg);
}).uri(location);
}catch (URISyntaxException e){
logger.error("uri error");
}
}
return chain.proceed(request);
}
@Override
public int getOrder() {
return ServerFilterPhase.SECURITY.order();
}
}
```
SurenessSecurityManager configuration
```java
import io.micronaut.context.annotation.Factory;
@Factory
public class SurenessConfiguration {
private static final Logger logger = LoggerFactory.getLogger(SurenessConfiguration.class);
@Factory
public SurenessSecurityManager init() {
SurenessAccountProvider accountProvider = new DocumentAccountProvider();
List<Processor> processorList = new LinkedList<>();
NoneProcessor noneProcessor = new NoneProcessor();
processorList.add(noneProcessor);
PasswordProcessor passwordProcessor = new PasswordProcessor();
passwordProcessor.setAccountProvider(accountProvider);
processorList.add(passwordProcessor);
DefaultProcessorManager processorManager = new DefaultProcessorManager(processorList);
if (logger.isDebugEnabled()) {
logger.debug("DefaultProcessorManager init");
}
PathTreeProvider pathTreeProvider = new DocumentPathTreeProvider();
DefaultPathRoleMatcher pathRoleMatcher = new DefaultPathRoleMatcher();
pathRoleMatcher.setPathTreeProvider(pathTreeProvider);
pathRoleMatcher.buildTree();
if (logger.isDebugEnabled()) {
logger.debug("DefaultPathRoleMatcher init");
}
// SubjectFactory init
SubjectFactory subjectFactory = new SurenessSubjectFactory();
List<SubjectCreate> subjectCreates = Arrays.asList(
new NoneSubjectReactiveCreator(),
new BasicSubjectReactiveCreator());
subjectFactory.registerSubjectCreator(subjectCreates);
if (logger.isDebugEnabled()) {
logger.debug("SurenessSubjectFactory init");
}
// surenessSecurityManager init
SurenessSecurityManager securityManager = SurenessSecurityManager.getInstance();
securityManager.setPathRoleMatcher(pathRoleMatcher);
securityManager.setSubjectFactory(subjectFactory);
securityManager.setProcessorManager(processorManager);
if (logger.isDebugEnabled()) {
logger.debug("SurenessSecurityManager init");
}
return securityManager;
}
}
```
#### 4. Last, Implement Auth Exception Handling Process
Sureness uses exception handling process:
- If auth success, method - `checkIn()` will return a `SubjectSum` object containing user information.
- If auth failure, method - `checkIn()` will throw different types of auth exceptions.
We need to continue the subsequent process based on these exceptions.(eg: return the request response)
Here we need to customize the exceptions thrown by `checkIn`, passed directly when auth success, catch exception when auth failure and do something:
````
// when auth error , add error msg to HttpRequest
if (statusCode != null && errorMsg != null) {
String finalErrorMsg = errorMsg;
Integer finalStatusCode = statusCode;
logger.info(statusCode+"--->"+errorMsg);
try {
URI location = new URI("/auth/error");
request = request.mutate().headers(httpHeaders -> {
httpHeaders.add("statusCode", String.valueOf(finalStatusCode));
httpHeaders.add("errorMsg", finalErrorMsg);
}).uri(location);
}catch (URISyntaxException e){
logger.error("uri error");
}
}
````
**All done, we can test now!**
## Test
Through the above steps, a complete auth function project is completed. Someone maybe think that with only these few steps, where is its complete function and what can it support?
This built project is based on the RBAC permission model and supports Baisc authentication, Digest authentication and JWT authentication. It can fine-grained control the user's access to the restful api provided by the Javalin. That is to control which users can access which api.
Let's test it. (we use postman and chrome to test.)
### Test Authentication
#### 1. Basic Auth Test
Use postman Basic auth, as shown below:
* success - input username: admin, password: admin
![success](/img/docs/micronaut/success.png)
* fail - input username: admin, password: admin1234
![fail](/img/docs/micronaut/error.png)
## Conclusion
micronaut is a framework dedicated to simplicity and ease of use, and so is Sureness.
We hope you enjoy this tutorial. Of course, the tutorial only introduces a simple introduction. Our account data, role permission data can not only be written in `sureness.yml`, but also loaded and obtained from the database and annotations. We can also customize the authentication method, data source, etc.
Finally, thank you again for reading.
[DEMO SOURCE CODE ON GITHUB](https://github.com/usthe/sureness/tree/master/samples/javalin-sureness)

View File

@@ -0,0 +1,16 @@
---
id: sample-quarkus
title: Quarkus项目集成
sidebar_label: Quarkus项目集成
---
[quarkus-sureness例子项目仓库地址](https://github.com/tomsun28/sureness/tree/master/samples/quarkus-sureness)
- 基于`quarkus, jax-rs`
- 从默认的配置文件`sureness.yml`加载账户信息,资源角色,过滤资源等信息
- 使用默认的`sureness-config`
- 使用默认的`JWT, Basic Auth, Digest Auth`方式认证鉴权
- 例子中包含`REST API`
- 保护入口: `SurenessFilterExample`
- 推荐使用`postman`测试

View File

@@ -0,0 +1,15 @@
---
id: sample-spring-webflux
title: Spring-Webflux项目集成
sidebar_label: Spring-Webflux项目集成
---
[spring-webflux-sureness例子项目仓库地址](https://github.com/tomsun28/sureness/tree/master/samples/spring-webflux-sureness)
- 基于`spring-webflux`
- 自定义 `subject creator (BasicSubjectReactiveCreator, JwtSubjectReactiveCreator, NoneSubjectReactiveCreator)` 适配 `ServerHttpRequest` 请求体
- 从默认的配置文件`sureness.yml`加载账户信息,资源角色,过滤资源等信息
- 使用默认的`JWT, Basic Auth`方式认证鉴权
- 例子中包含`REST API`
- 保护入口: `SurenessFilterExample`
- 推荐使用`postman`测试

View File

@@ -0,0 +1,19 @@
---
id: sample-tom
title: Springboot项目集成-数据库方案
sidebar_label: Springboot项目集成-数据库方案
---
- 基于`springboot,jpa...`
- 自定义数据源,使用从数据库加载账户信息,资源角色,过滤资源等信息,这样便于动态调整(见`AccountProvider ResourceProvider`)
- 除了使用了默认的`JWT, Basic Auth`方式认证鉴权,新增自定义认证鉴权(自定义`subject subjectCreator processor...`)
- 推荐使用`postman`测试,测试样例为`sample-tom-postman.json`,导入`postman`即可
样例中包含2种自定义认证鉴权方式:
1. 自定义了一个单独的`subjectCreator``CustomPasswdSubjectCreator`
演示功能就是自定义的从不同地方获取请求体的账户密码,来创建默认的`PasswordSubject`,走默认的账户密码认证流程
2. 自定义了一整套流程(包含`subject subjectCreator processor`) 见 `CustomTokenSubject CustomTokenSubjectCreator CustomTokenProcessor`
演示功能就是自定义一个简单的`token`作为`subject`对象,对其自定义创建获取方式-`creator`和自定义认证鉴权处理流程-`processor`.
此自定义流程也演示了一个简单的`token`刷新流程

57
home/docs/introduce.md Normal file
View File

@@ -0,0 +1,57 @@
---
id: introduce
title: HertzBeat赫兹节拍
sidebar_label: 介绍
slug: /
---
> 易用友好的高性能监控告警系统。
![tan-cloud](https://img.shields.io/badge/网站监控-4EB1BA.svg)
![tan-cloud](https://img.shields.io/badge/PING连通性监控-blue.svg)
![tan-cloud](https://img.shields.io/badge/端口可用性监控-green.svg)
![tan-cloud](https://img.shields.io/badge/数据库监控-yellow.svg)
![tan-cloud](https://img.shields.io/badge/自定义监控-orange.svg)
![tan-cloud](https://img.shields.io/badge/阈值告警-red.svg)
![tan-cloud](https://img.shields.io/badge/告警转发通知-blueviolet.svg)
## 📫 前言
> 毕业后投入很多业余时间也做了一些开源项目,[Sureness](https://github.com/dromara/sureness) [Bootshiro](https://gitee.com/tomsun28/bootshiro) [Issues-translate-action](https://github.com/usthe/issues-translate-action) ,
> 当时上班有空就回答网友问题,下班回家写开源代码,远程帮人看问题,还总感觉时间不够用,当时想如果不去上班能做自己热爱的该多好。
> 年轻就要折腾何况还是自己很想做的。于是乎21年底我放弃激励裸辞开始全职开源了(这里感谢老婆大人的全力支持),也是第一次全职创业。
> 自己在APM领域做了多年当然这次创业加开源的方向也就是老本行APM监控系统我们开发一个支持多种监控指标(更多监控类型指标正在适配中),拥有自定义监控,支持阈值告警通知等功能,面向开发者友好的开源监控项目-HertzBeat赫兹节拍。
> 想到很多开发者和团队拥有云上资源可能只需要使用监控服务而并不想部署监控系统我们也提供了可以直接登陆使用的SAAS云监控版本-[TanCloud探云](https://console.tancloud.cn)。
> 希望大家多多支持点赞,非常感谢。
## 🎡 <font color="green">介绍</font>
> [HertzBeat赫兹节拍](https://github.com/dromara/sureness) 是由[TanCloud](https://tancloud.cn)开源的一个支持网站APIPING端口数据库等监控类型拥有易用友好的可视化操作界面的开源监控告警项目。
> 当然,我们也提供了对应的[SAAS云监控版本](https://console.tancloud.cn),中小团队和个人无需再为了监控自己的网站资源,而去部署一套繁琐的监控系统,[登陆即可免费开始](https://console.tancloud.cn)监控之旅。
> HertzBeat 支持自定义监控只用通过配置YML文件我们就可以自定义需要的监控类型和指标来满足常见的个性化需求。
> HertzBeat 模块化,`manager, collector, scheduler, warehouse, alerter` 各个模块解耦合,方便理解与定制开发。
> HertzBeat 支持更自由化的告警配置(计算表达式),支持告警通知,告警模版
> 欢迎登陆 HertzBeat 的 [云环境TanCloud]((https://console.tancloud.cn)) 试用发现更多。
> 我们正在快速迭代中,欢迎参与加入共建项目开源生态。
> `HertzBeat`的多类型支持,易扩展,低耦合,希望能帮助开发者和中小团队快速搭建自有监控系统。
## 🥐 模块
- **[manager](manager)** 提供监控管理,系统管理基础服务
> 提供对监控的管理,监控应用配置的管理,系统用户租户后台管理等。
- **[collector](collector)** 提供监控数据采集服务
> 使用通用协议远程采集获取对端指标数据。
- **[scheduler](scheduler)** 提供监控任务调度服务
> 采集任务管理,一次性任务和周期性任务的调度分发。
- **[warehouse](warehouse)** 提供监控数据仓储服务
> 采集指标结果数据管理,数据落盘,查询,计算统计。
- **[alerter](alerter)** 提供告警服务
> 告警计算触发,监控状态联动,告警配置,告警通知。
- **[web-app](web-app)** 提供可视化控制台页面
> 监控告警系统可视化控制台前端(angular+ts+zorro)
![hertzBeat](/img/docs/hertzbeat-stru.svg)

21
home/docs/sponsor.md Normal file
View File

@@ -0,0 +1,21 @@
---
id: sponsor
title: 赞助
sidebar_label: 赞助
---
**sureness对个人或企业完全免费如果您喜欢这个项目并且愿意提供帮助请作者喝杯咖啡吧**
### 微信支付宝
![wechat-alipay](/img/docs/pay.png)
### paypal
[https://paypal.me/tomsun28](https://paypal.me/tomsun28)

View File

@@ -0,0 +1,35 @@
---
id: docker-deploy
title: 通过Docker方式安装HertzBeat
sidebar_label: Docker方式部署
---
### 🐕 开始使用
- 如果您不想部署而是直接使用我们提供SAAS监控云-[TanCloud探云](https://console.tancloud.cn),即刻[登陆注册](https://console.tancloud.cn)免费使用。
- 如果您是想将HertzBeat部署到内网环境搭建监控系统请参考下面的部署文档进行操作。
### 🐵 依赖服务部署
> HertzBeat最少依赖于 关系型数据库[MYSQL8+](https://www.mysql.com/) 和 时序性数据库[TDengine2+](https://www.taosdata.com/getting-started)
##### 安装MYSQL
1. docker安装MYSQl
`docker run -d --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 mysql`
2. 创建名称为hertzBeat的数据库
3. 执行位于项目仓库script目录下的数据库脚本 schema.sql
##### 安装TDengine
1. docker安装TDengine
`docker run -d -p 6030-6049:6030-6049 -p 6030-6049:6030-6049/udp --name tdengine tdengine/tdengine`
2. 创建名称为hertzBeat的数据库
### 🍞 HertzBeat安装
> HertzBeat支持通过源码安装启动Docker容器运行和安装包方式安装部署。
#### Docker方式快速安装
`docker run -d -p 1157:1157 --name hertzbeat tancloud/hertzbeat:latest`
#### 通过安装包安装
todo
**HAVE FUN**

View File

@@ -0,0 +1,30 @@
---
id: mysql-init
title: 依赖服务MYSQL安装初始化
sidebar_label: MYSQL安装初始化
---
MYSQL是一款值得信赖的关系型数据库HertzBeat使用其存储监控信息告警信息配置信息等结构化关系数据。
> 如果您已有MYSQL环境可直接跳到SQL脚本执行那一步。
### 通过Docker方式安装MYSQL
1. 下载安装Docker环境
Docker 工具自身的下载请参考 [Docker官网文档](https://docs.docker.com/get-docker/)。
安装完毕后终端查看Docker版本是否正常输出。
```
$ docker -v
Docker version 20.10.12, build e91ed57
```
2. Docker安装MYSQl
```
$ docker run -d --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 mysql:latest
526aa188da767ae94b244226a2b2eec2b5f17dd8eff594533d9ec0cd0f3a1ccd
```
使用```$ docker ps```查看数据库是否启动成功
### SQL脚本执行
1. 进入MYSQL或使用客户端连接MYSQL服务
2. 创建名称为hertzbeat的数据库
3. 执行位于项目仓库script目录下的数据库建表初始化脚本 schema.sql
4. 查看hertzbeat数据库是否成功建表

View File

@@ -0,0 +1,35 @@
---
id: package-deploy
title: 通过安装包安装HertzBeat
sidebar_label: 安装包方式部署
---
### 🐕 开始使用
- 如果您不想部署而是直接使用我们提供SAAS监控云-[TanCloud探云](https://console.tancloud.cn),即刻[登陆注册](https://console.tancloud.cn)免费使用。
- 如果您是想将HertzBeat部署到内网环境搭建监控系统请参考下面的部署文档进行操作。
### 🐵 依赖服务部署
> HertzBeat最少依赖于 关系型数据库[MYSQL8+](https://www.mysql.com/) 和 时序性数据库[TDengine2+](https://www.taosdata.com/getting-started)
##### 安装MYSQL
1. docker安装MYSQl
`docker run -d --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 mysql`
2. 创建名称为hertzBeat的数据库
3. 执行位于项目仓库script目录下的数据库脚本 schema.sql
##### 安装TDengine
1. docker安装TDengine
`docker run -d -p 6030-6049:6030-6049 -p 6030-6049:6030-6049/udp --name tdengine tdengine/tdengine`
2. 创建名称为hertzBeat的数据库
### 🍞 HertzBeat安装
> HertzBeat支持通过源码安装启动Docker容器运行和安装包方式安装部署。
#### Docker方式快速安装
`docker run -d -p 1157:1157 --name hertzbeat tancloud/hertzbeat:latest`
#### 通过安装包安装
todo
**HAVE FUN**

View File

@@ -0,0 +1,44 @@
---
id: quickstart
title: 快速开始
sidebar_label: 快速开始
---
### 🐕 开始使用
- 如果您不想部署而是直接使用我们提供SAAS监控云-[TanCloud探云](https://console.tancloud.cn),即刻[登陆注册](https://console.tancloud.cn)免费使用。
- 如果您是想将HertzBeat部署到内网环境搭建监控系统请参考下面的部署文档进行操作。
### 🐵 依赖服务部署
> HertzBeat最少依赖于 关系型数据库[MYSQL8+](https://www.mysql.com/) 和 时序性数据库[TDengine2+](https://www.taosdata.com/getting-started)
##### 安装MYSQL
1. docker安装MYSQl
`docker run -d --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 mysql`
2. 创建名称为hertzbeat的数据库
3. 执行位于项目仓库script目录下的数据库脚本 schema.sql
详细步骤参考 [依赖服务MYSQL安装初始化](mysql-init.md)
##### 安装TDengine
1. docker安装TDengine
`docker run -d -p 6030-6049:6030-6049 -p 6030-6049:6030-6049/udp --name tdengine tdengine/tdengine`
2. 创建名称为hertzbeat的数据库
详细步骤参考 [依赖服务TDengine安装初始化](tdengine-init.md)
### 🍞 HertzBeat安装
> HertzBeat支持通过源码安装启动Docker容器运行和安装包方式安装部署。
#### Docker方式快速安装
`docker run -d -p 1157:1157 --name hertzbeat tancloud/hertzbeat:latest`
详细步骤参考 [通过Docker方式安装HertzBeat](docker-deploy.md)
#### 通过安装包安装
todo
详细步骤参考 [通过安装包安装HertzBeat](package-deploy.md)
**HAVE FUN**

View File

@@ -0,0 +1,50 @@
---
id: tdengine-init
title: 依赖服务TDengine安装初始化
sidebar_label: TDengine安装初始化
---
TDengine是一款国产的开源物联网时序型数据库我们使用其替换了InfluxDb来存储采集到的监控指标数据。
> 如果您已有TDengine环境可直接跳到创建数据库实例那一步。
### 通过Docker方式安装TDengine
> 可参考官方网站[安装教程](https://www.taosdata.com/docs/cn/v2.0/getting-started/docker)
1. 下载安装Docker环境
Docker 工具自身的下载请参考 [Docker官网文档](https://docs.docker.com/get-docker/)。
安装完毕后终端查看Docker版本是否正常输出。
```
$ docker -v
Docker version 20.10.12, build e91ed57
```
2. Docker安装TDengine
```
$ docker run -d -p 6030-6049:6030-6049 -p 6030-6049:6030-6049/udp --name tdengine tdengine/tdengine
526aa188da767ae94b244226a2b2eec2b5f17dd8eff594533d9ec0cd0f3a1ccd
```
使用```$ docker ps```查看数据库是否启动成功
### 创建数据库实例
1. 进入数据库Docker容器
```
$ docker exec -it tdengine /bin/bash
root@tdengine-server:~/TDengine-server-2.4.0.4#
```
2. 创建名称为hertzbeat的数据库
进入容器后,执行 taos shell 客户端程序。
```
root@tdengine-server:~/TDengine-server-2.4.0.4# taos
Welcome to the TDengine shell from Linux, Client Version:2.4.0.4
Copyright (c) 2020 by TAOS Data, Inc. All rights reserved.
taos>
```
执行创建数据库命令
```
taos> show databases;
taos> CREATE DATABASE hertzbeat KEEP 90 DAYS 10 BLOCKS 6 UPDATE 1;
```
上述语句将创建一个名为 hertzbeat 的库这个库的数据将保留90天超过90天将被自动删除每 10 天一个数据文件,内存块数为 6允许更新数据
3. 查看hertzbeat数据库是否成功创建
```
taos> show databases;
taos> use hertzbeat;
```