sudo87 commented on code in PR #12737:
URL: https://github.com/apache/cloudstack/pull/12737#discussion_r3156105193


##########
plugins/dns/powerdns/src/main/java/org/apache/cloudstack/dns/powerdns/PowerDnsClient.java:
##########
@@ -0,0 +1,377 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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.
+
+package org.apache.cloudstack.dns.powerdns;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.dns.exception.DnsAuthenticationException;
+import org.apache.cloudstack.dns.exception.DnsConflictException;
+import org.apache.cloudstack.dns.exception.DnsNotFoundException;
+import org.apache.cloudstack.dns.exception.DnsOperationException;
+import org.apache.cloudstack.dns.exception.DnsProviderException;
+import org.apache.cloudstack.dns.exception.DnsTransportException;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpDelete;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPatch;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpPut;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
+import org.apache.http.util.EntityUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.cloud.utils.StringUtils;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+public class PowerDnsClient implements AutoCloseable {
+    public static final Logger logger = 
LoggerFactory.getLogger(PowerDnsClient.class);
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    private static final int CONNECT_TIMEOUT_MS = 5_000;
+    private static final int SOCKET_TIMEOUT_MS = 10_000;
+    private static final int MAX_CONNECTIONS_TOTAL = 50;
+    private static final int MAX_CONNECTIONS_PER_ROUTE = 10;
+    private static final String API_PREFIX = "/api/v1";
+    public static final String DEFAULT_SERVER_NAME = "localhost";
+
+    private final CloseableHttpClient httpClient;
+
+    public PowerDnsClient() {
+        PoolingHttpClientConnectionManager connectionManager = new 
PoolingHttpClientConnectionManager();
+        connectionManager.setMaxTotal(MAX_CONNECTIONS_TOTAL);
+        connectionManager.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
+
+        RequestConfig requestConfig = RequestConfig.custom()
+                .setConnectTimeout(CONNECT_TIMEOUT_MS)
+                .setConnectionRequestTimeout(CONNECT_TIMEOUT_MS)
+                .setSocketTimeout(SOCKET_TIMEOUT_MS)
+                .build();
+
+        this.httpClient = HttpClientBuilder.create()
+                .setConnectionManager(connectionManager)
+                .setDefaultRequestConfig(requestConfig)
+                .evictIdleConnections(30, TimeUnit.SECONDS)
+                .disableCookieManagement()
+                .build();
+    }
+
+    public String resolveServerId(String baseUrl, Integer port, String apiKey, 
String externalServerId) throws DnsProviderException {
+        if (StringUtils.isNotBlank(externalServerId)) {
+            return validateServerId(baseUrl, port, apiKey, externalServerId);
+        }
+        return discoverAuthoritativeServerId(baseUrl, port, apiKey);
+    }
+
+    public String validateServerId(String baseUrl, Integer port, String 
apiKey, String externalServerId) throws DnsProviderException {
+        String encodedServer = URLEncoder.encode(externalServerId, 
StandardCharsets.UTF_8);
+        HttpGet request = new HttpGet(buildUrl(baseUrl, port, "/servers/" + 
encodedServer));
+        JsonNode server = execute(request, apiKey, 200);
+        if 
(!ApiConstants.AUTHORITATIVE.equalsIgnoreCase(server.path("daemon_type").asText(null)))
 {
+            throw new DnsOperationException(String.format("Server %s is not 
authoritative type=%s", externalServerId,
+                    server.path("daemon_type").asText(null)));
+        }
+        return externalServerId;
+    }
+
+    public String discoverAuthoritativeServerId(String baseUrl, Integer port, 
String apiKey) throws DnsProviderException {
+        String url = buildUrl(baseUrl, port , "/servers");
+        HttpGet request = new HttpGet(url);
+        JsonNode servers = execute(request, apiKey, 200);
+        if (servers == null || !servers.isArray() || servers.isEmpty()) {
+            throw new DnsOperationException("No servers returned by PowerDNS 
API");
+        }
+        String fallbackId = null;
+        for (JsonNode server : servers) {
+            String daemonType = server.path("daemon_type").asText(null);
+            if (!ApiConstants.AUTHORITATIVE.equalsIgnoreCase(daemonType)) {
+                continue;
+            }
+            String serverId = server.path(ApiConstants.ID).asText(null);
+            if (StringUtils.isBlank(serverId)) {
+                continue;
+            }
+            // Prefer localhost if present
+            if (DEFAULT_SERVER_NAME.equals(serverId)) {
+                return serverId;
+            }
+            if (fallbackId == null) {
+                fallbackId = serverId;
+            }
+        }
+        if (fallbackId != null) {
+            return fallbackId;
+        }
+        throw new DnsOperationException("No authoritative PowerDNS server 
found");
+    }
+
+    public String createZone(String baseUrl, Integer port, String apiKey, 
String externalServerId, String zoneName,
+                             String zoneKind, boolean dnsSecFlag, List<String> 
nameServers) throws DnsProviderException {
+
+        validateServerId(baseUrl, port, apiKey, externalServerId);
+        String normalizedZone = normalizeZone(zoneName);
+        ObjectNode json = MAPPER.createObjectNode();
+        json.put(ApiConstants.NAME, normalizedZone);
+        json.put(ApiConstants.KIND, zoneKind);
+        json.put(ApiConstants.DNS_SEC, dnsSecFlag);
+        if (!CollectionUtils.isEmpty(nameServers)) {
+            ArrayNode nsArray = json.putArray(ApiConstants.NAME_SERVERS);
+            for (String ns : nameServers) {
+                nsArray.add(ns.endsWith(".") ? ns : ns + ".");
+            }
+        }
+        HttpPost request = new HttpPost(buildUrl(baseUrl, port, "/servers/" + 
externalServerId + "/zones"));
+        request.setEntity(new StringEntity(json.toString(), 
StandardCharsets.UTF_8));
+        JsonNode response = execute(request, apiKey, 201);

Review Comment:
   Client throws DnsConflictException and it is shown in the API response as 
error:
   ```
   DNS zone: %s already exists"



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to