83 lines
3.4 KiB
Java
83 lines
3.4 KiB
Java
package run.webup.platform;
|
|
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import java.util.*;
|
|
import org.springframework.stereotype.Component;
|
|
|
|
@Component
|
|
public class DomainDnsGateway {
|
|
private final AliyunGateway aliyun;
|
|
private final ObjectMapper json;
|
|
|
|
public DomainDnsGateway(AliyunGateway aliyun, ObjectMapper json) {
|
|
this.aliyun = aliyun;
|
|
this.json = json;
|
|
}
|
|
|
|
public String ensure(Map<String, String> config, String host, String target) {
|
|
String root = DomainNames.hostname(config.get("rootDomain"));
|
|
if (!DomainNames.under(host, root) || host.equals(root))
|
|
throw new ApiError.Failure(409, "平台项目域名不在已配置的阿里云 DNS 根域名下");
|
|
var response =
|
|
json.valueToTree(
|
|
aliyun.call(
|
|
config,
|
|
"DescribeSubDomainRecords",
|
|
"2015-01-09",
|
|
"POST",
|
|
Map.of("DomainName", root, "SubDomain", host, "PageSize", 500)));
|
|
if (response.path("TotalCount").asInt() > 500)
|
|
throw new ApiError.Failure(409, "域名已有过多解析记录,需要人工核对");
|
|
var records = response.path("DomainRecords").path("Record");
|
|
if (!records.isArray()) throw new ApiError.Failure(502, "DNS 记录列表响应不完整,未创建新记录");
|
|
for (var record : records) {
|
|
if (!"CNAME".equals(record.path("Type").asText())
|
|
|| !DomainNames.hostname(record.path("Value").asText()).equals(target)
|
|
|| "DISABLE".equals(record.path("Status").asText()))
|
|
throw new ApiError.Failure(409, "已有其他解析记录,未覆盖或删除;请先人工核对");
|
|
}
|
|
if (!records.isEmpty()) return null;
|
|
var created =
|
|
aliyun.call(
|
|
config,
|
|
"AddDomainRecord",
|
|
"2015-01-09",
|
|
"POST",
|
|
Map.of(
|
|
"DomainName",
|
|
root,
|
|
"RR",
|
|
host.substring(0, host.length() - root.length() - 1),
|
|
"Type",
|
|
"CNAME",
|
|
"Value",
|
|
target,
|
|
"TTL",
|
|
config.getOrDefault("recordTtl", "600")));
|
|
Object id = created.get("RecordId");
|
|
if (id == null) throw new ApiError.Failure(502, "DNS 创建结果不确定,请核对解析记录后重试");
|
|
return id.toString();
|
|
}
|
|
|
|
public void remove(Map<String, String> config, String recordId, String host, String target) {
|
|
var response =
|
|
json.valueToTree(
|
|
aliyun.call(
|
|
config,
|
|
"DescribeSubDomainRecords",
|
|
"2015-01-09",
|
|
"POST",
|
|
Map.of("SubDomain", host, "PageSize", 500)));
|
|
var records = response.path("DomainRecords").path("Record");
|
|
if (!records.isArray() || response.path("TotalCount").asInt() > 500)
|
|
throw new ApiError.Failure(502, "DNS 查询响应不完整,未自动删除记录");
|
|
com.fasterxml.jackson.databind.JsonNode info = null;
|
|
for (var record : records) if (recordId.equals(record.path("RecordId").asText())) info = record;
|
|
if (info == null) return;
|
|
if (!"CNAME".equals(info.path("Type").asText())
|
|
|| !target.equals(DomainNames.hostname(info.path("Value").asText())))
|
|
throw new ApiError.Failure(409, "解析记录已变化,未自动删除,请管理员核对");
|
|
aliyun.call(config, "DeleteDomainRecord", "2015-01-09", "POST", Map.of("RecordId", recordId));
|
|
}
|
|
}
|