通过Java调用OceanBase云平台API

最近由于工作原因又开始捣鼓OceanBase,OceanBase云平台(OCP)提供了强大的管理和监控功能,而且对外开放API接口,可以将部分监控整合到自己的平台,所以写了个Java调用OCP API的demo做为自己的技术储备,也想分享给大家。也因为最近对Eclipse Vertx和异步编程非常兴趣,所以案例使用是Vertx的WebClient,而非Apache HttpClient, 不过,不管用什么库,原理是相似的。

先介绍下环境,我这边用的是OCP企业版4.2.2,OB不同版本之间差异还是很大的,其它版本不一定适用。参考的是官方文档(https://www.oceanbase.com/docs/common-ocp-1000000000585101):云平台OCP --> “参考指南” --> “API参考”。

客户端鉴权

OCP开放API的客户端鉴权,支持使用AK/SK和HTTP Basic两种认证模式。

HTTP Basic认证模式

HTTP Basic通过用户名和密码进行鉴权,相对比较简单,但因为是明文传输,并不安全,特别是使用http时,用户名和密码可以在传输过程中被抓包解析出来。对于可控的内网,也可以做为便捷的方法。以下是实现代码(为了文档更好的阅读,完整的代码放在文章的资源中https://download.csdn.net/download/Li_Xiang_996/89517863?spm=1001.2101.3001.9499)。

// 先构建'"用户名":"用户密码"字符串, 然后将字符进行Base64编码,就可以得到authorization。
byte[] strContents = (userName.trim() + ":" + password.trim()).getBytes();
String base64Contents = Base64.getUrlEncoder().encodeToString(strContents);
String authorization = "Basic " + base64Contents;
// 然后调用API时候,将authorization放到HTTP请求消息头Authorization中即可。
client.something.putHeader("Authorization", authorization).send();

API(AK/SK)认证模式

OB得官方文档有详细介绍如何使用,可以参考。一些题外话,OB的官方文档相较之前有非常巨大的进步,值得点赞。

首先需要在OCP中创建(申请) AK/SK,登录OCP,右边导航点开"系统管理" ->“用户管理”。用户列表中选择一个用户或者创建一个新用户,需要注意的是,当获取了用户的AccessKey,也就获得了该用户的权限。

选择用户,进入对应的用户的设置页面,在“AccessKey”部分,点击"一键创建 AccessKey",即可获取该用户的AK/SK。后续我们就可以通过AK/SK来进行API访问。

认证原理大致是: 客户端将(将要)对API的请求按照指定的格式拼接成一个消息(字符串),然后用申请到的AK对应的SK,通过HMACSHA1算法对消息进行加签(生成消息的哈希串)。

 消息体格式
String message = 
  "POST\n" +    //HTTP请求方法, 大写英文。包括: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS和TRACE。
  "186974DB33A090A16D3E2CA35F547B56\n" + // 请求体, md5编码, 可以为空(如使用HTTP GET时候), 当换行(\n)符号不能省略。
  "application/json\n" +                 // 消息体的类型。OCP统一使用application/json类型的消息体。
  "Fri, 5 Jul 2024 06:49:37 GMT\n" +    // 请求发起时间, 其遵循RFC1123格式, 必须是GMT时区?
  "10.100.6.161:8080\n" +               // OCP服务器地址+端口
  "x-ocp-date:Fri, 5 Jul 2024 06:49:37 GMT\n" +  //
  "/api/v2/compute/idcs" //API请求的路径, 以及请求的查询参数, 请求参数可以为空, 如果有多个必须按参数名(升序排序), 否则无法通过验证
 hmacSha1加签
byte[] hash = hmacSha1(accessKeySecret, message.getBytes(StandardCharsets.UTF_8));
String signature = Base64.getEncoder().encodeToString(hash); 
String authorization = "OCP-ACCESS-KEY-HMACSHA1 " + accessKey + ":" + signature;

// 然后调用API时候,将authorization放到HTTP请求消息头Authorization中即可。
client.something.putHeader("Authorization", authorization).send();

服务器端行为没看过代码, 纯属个人猜测, 看个乐吧:服务器端(数据库中)保存了用户AK/SK表, 服务器根据接收到请求的Authorization, 可获取客户端的AK,就可以查询到关联用户,即可进行权限检查(是否有权执行); 进一步取出对应的SK,根据服务器获取的客户端请求(通过客户端相同的格式)构建消息体, 并使用SK和相同的HASH算法(HMACSHA1)对消息体进行加签(计算HASH),如果两者签名相同, 那么这通过验证,返回结果,类似于证书的校验过程。

调用OCP API

以查询告警事件列表为例,请求路径"GET /api/v2/alarm/alarms", 请求参数我们指定每页显示5条记录(size=5), 显示第一页(page=1)。

final String baseUri = "/api/v2/alarm/alarms";
Map<String, String> queryParams = new HashMap<>();
queryParams.put("page", "1");
queryParams.put("size", "5");
String uri = AuthorizationBuilder.buildUri(baseUri, queryParams); // buildUri方法会拼接baseUri于查询参数, 参数按参数名升序组织。

 请求时间, 取当前时间, RFC1123格式, 必须为GMT时区
ZonedDateTime requestTime = ZonedDateTime.now(ZoneId.of("GMT"));
String rfc1123RequestTime = DateTimeFormatter.RFC_1123_DATE_TIME.format(requestTime);
根据请求构建authorization, 与上面描述的过程一样,具体看源代码。
String authorization = AuthorizationBuilder.newApiAuthorizationBuilder(accessKey, accessKeySecret)
		.setRequestTimestamp(requestTime)
		.setHost(server)
		.setUri(uri)
		.build();
WebClientOptions options = new WebClientOptions().setConnectTimeout(3000);
Vertx vertx = Vertx.vertx();
WebClient client = WebClient.create(vertx, options);
Future<HttpResponse<Buffer>> future = client.get(port, host, uri)
		.putHeader("content-type", AuthorizationBuilder.CONTENT_TYPE_JSON)
		.putHeader("Authorization", authorization)
		.putHeader("x-ocp-date", rfc1123RequestTime)
		.send();
future .onSuccess(AlarmsApi::printResult).onFailure(e -> e.printStackTrace());

//解析并打印API返回结果
public static void printResult(HttpResponse<Buffer> response) {
	JsonObject jsonBody = response.bodyAsJsonObject();
	boolean successful = jsonBody.getBoolean("successful");
	if (successful) {
		JsonObject data = jsonBody.getJsonObject("data");
		JsonArray contents = data.getJsonArray("contents");
		System.out.println("###### 告警事件列表(Top 5) ######");
		for (int i = 0; i < contents.size(); i++) {
			JsonObject alert = contents.getJsonObject(i);
			System.out.println("------- " + alert.getLong("id") + " -------" + 
					"\nname: " + alert.getString("name") + 
					"\nalarmType: " + alert.getString("alarmType") + 
					"\nstatus: " + alert.getString("status")+ 
					"\nresolvedAt: " + alert.getString("resolvedAt") + 
					"\ntarget: " + alert.getString("target") + 
					"\ndescription: " + alert.getString("description") + "\n");
		}
	} else {
		System.out.println("API返回失败! status = " + jsonBody.getInteger("status"));
		System.out.println(jsonBody.encodePrettily());
	}
}

执行效果如下:

##### 告警事件列表(Top 5) ######
------- 1000211 -------
name: 服务器CPU平均load1超限
alarmType: ob_host_load1_per_cpu_over_threshold
status: Inactive
resolvedAt: 2024-07-04T21:10:56Z
target: alarm_template_id=0:host=192.168.100.21
description: 集群:metadb,主机:192.168.100.21,告警:服务器CPU平均load1超限。CPU平均load1值 1.552 超过 1.5。

------- 1000210 -------
name: 服务器CPU平均load1超限
alarmType: ob_host_load1_per_cpu_over_threshold
status: Inactive
resolvedAt: 2024-07-04T20:56:06Z
target: alarm_template_id=0:host=192.168.100.21
description: 集群:metadb,主机:192.168.100.21,告警:服务器CPU平均load1超限。CPU平均load1值 1.737 超过 1.5。
...

更复杂的调用

OCP API除了查询还有管理功能(增删改),以"主机模块"的机型相关API为例。

  • 查询机型信息列表: GET /api/v2/compute/hostTypes
  • 添加主机机型信息: POST /api/v2/compute/hostTypes
  • 删除机型信息: DELETE /api/v2/compute/hostTypes/{hostTypeId}
    Demo代码:
 新增机型HuaWei_Kunpeng
String postBody = "{\"name\": \"HuaWei_Kunpeng\", \"description\": \"128C 512GB\"}";
String baseUri = "/api/v2/compute/hostTypes";
ZonedDateTime requestTime = ZonedDateTime.now(ZoneId.of("GMT"));
String rfc1123RequestTime = DateTimeFormatter.RFC_1123_DATE_TIME.format(requestTime);

String authorization = AuthorizationBuilder.newApiAuthorizationBuilder(accessKey, accessKeySecret)
		.setHttpMethod(HTTP_POST)
		.setRequestTimestamp(requestTime)
		.setHost(server)
		.setUri(uri)
		.setRequestBody(postBody)
		.build();
WebClientOptions options = new WebClientOptions().setConnectTimeout(3000);
WebClient client = WebClient.create(vertx, options);

Future<HttpResponse<Buffer>> futrue = client.post(port, host, uri)
	.putHeader("content-type", CONTENT_TYPE_JSON)
	.putHeader("Authorization", authorization)
	.putHeader("x-ocp-date", rfc1123RequestTime)
	.sendBuffer(Buffer.buffer(postBody));

 删除机型id = 1000010
int hostTypeId = 1000010;
String uri = "/api/v2/compute/hostTypes/" + hostTypeId;
ZonedDateTime requestTime = ZonedDateTime.now(ZoneId.of("GMT"));
String rfc1123RequestTime = DateTimeFormatter.RFC_1123_DATE_TIME.format(requestTime);

String authorization = AuthorizationBuilder.newApiAuthorizationBuilder()
		.setHttpMethod(HTTP_DELETE)
		.setAccessKey(accessKey)
		.setAccessKeySecret(accessKeySecret)
		.setRequestTimestamp(requestTime)
		.setHost(server)
		.setUri(uri)
		.build();
WebClientOptions options = new WebClientOptions().setConnectTimeout(3000);
WebClient client = WebClient.create(vertx, options);
Future<HttpResponse<Buffer>> future = client.delete(port, host, uri)
	.putHeader("content-type", CONTENT_TYPE_JSON)
	.putHeader("Authorization", authorization)
	.putHeader("x-ocp-date", rfc1123RequestTime)
	.send();

依葫芦画瓢,一通百通。在调用返回信息里面有一个“traceId”,我们可以通过这个traceId在服务器端找到对应的日志信息。对于API失败调试有一定的辅助作用。例如,执行删除机型的返回如下:

==> 删除新增的主机类型(1000010) ...
主机类型删除成功。
{
  "duration" : 43,
  "server" : "b587654b4d",
  "status" : 200,
  "successful" : true,
  "timestamp" : "2024-07-05T15:34:08.576+08:00",
  "traceId" : "80070430b9814a99" ==>
}

对应OCP的日志信息:

### OCP日志位置
[admin@oat-ocp ocp]$ pwd
/home/admin/logs/ocp

### 通过traceId为关键字搜索。
[admin@oat-ocp ocp]$ grep "80070430b9814a99" ocp-server.*
ocp-server.0.out:2024-07-05 15:34:08.555  INFO 9 --- [http-nio-0.0.0.0-8080-exec-2,80070430b9814a99,ce0c2accd19f] c.o.o.s.c.trace.RequestTracingAspect     : API: [DELETE /api/v2/compute/hostTypes/1000010?null, client=10.100.6.16, traceId=80070430b9814a99, method=NoDataResponse com.oceanbase.ocp.server.common.controller.ComputeController.deleteHostType(Long), args=1000010,]
ocp-server.0.out:2024-07-05 15:34:08.562  INFO 9 --- [http-nio-0.0.0.0-8080-exec-2,80070430b9814a99,ce0c2accd19f] c.o.o.c.h.service.HostTypeServiceImpl    : Deleted hostType: 1000010
ocp-server.0.out:2024-07-05 15:34:08.576  INFO 9 --- [http-nio-0.0.0.0-8080-exec-2,80070430b9814a99,ce0c2accd19f] c.o.o.s.c.trace.RequestTracingAspect     : API OK: [DELETE /api/v2/compute/hostTypes/1000010 client=10.100.6.16, traceId=80070430b9814a99, duration=43 ms]
  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值