package com.vincent.rsf.httpaudit.config; import com.vincent.rsf.httpaudit.props.HttpAuditProperties; import com.vincent.rsf.httpaudit.service.OpenSearchHttpAuditLogSink; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.opensearch.client.RestClient; import org.opensearch.client.RestClientBuilder; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import java.util.ArrayList; import java.util.List; /** * log-storage-mode 为 2 或 3 时加载 */ @Configuration @Conditional(OnOpenSearchLogStorageEnabled.class) public class HttpAuditOpenSearchConfiguration { @Bean(destroyMethod = "close") public RestClient httpAuditOpenSearchRestClient(HttpAuditProperties props) { HttpAuditProperties.OpenSearch oc = props.getOpenSearch(); RestClientBuilder builder = RestClient.builder(buildHosts(oc)); builder.setRequestConfigCallback(rc -> rc .setConnectTimeout((int) oc.getConnectTimeout().toMillis()) .setSocketTimeout((int) oc.getSocketTimeout().toMillis())); if (StringUtils.isNotBlank(oc.getUsername())) { CredentialsProvider cp = new BasicCredentialsProvider(); cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(oc.getUsername(), oc.getPassword() == null ? "" : oc.getPassword())); builder.setHttpClientConfigCallback(hcb -> hcb.setDefaultCredentialsProvider(cp)); } return builder.build(); } @Bean public OpenSearchHttpAuditLogSink openSearchHttpAuditLogSink( @Qualifier("httpAuditOpenSearchRestClient") RestClient httpAuditOpenSearchRestClient, HttpAuditProperties props) { return new OpenSearchHttpAuditLogSink(httpAuditOpenSearchRestClient, props); } private static HttpHost[] buildHosts(HttpAuditProperties.OpenSearch oc) { String scheme = oc.getScheme() == null ? "http" : oc.getScheme(); List hosts = new ArrayList<>(); for (String raw : oc.getUris()) { if (raw == null || raw.trim().isEmpty()) { continue; } String s = raw.trim(); int colon = s.lastIndexOf(':'); if (colon > 0 && colon < s.length() - 1) { String h = s.substring(0, colon); int port = Integer.parseInt(s.substring(colon + 1)); hosts.add(new HttpHost(h, port, scheme)); } else { hosts.add(new HttpHost(s, 9200, scheme)); } } if (hosts.isEmpty()) { hosts.add(new HttpHost("localhost", 9200, scheme)); } return hosts.toArray(new HttpHost[0]); } }