index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ai/floom/java-sdk/1.0.0/ai/floom
|
java-sources/ai/floom/java-sdk/1.0.0/ai/floom/response/FloomResponseValue.java
|
package ai.floom.response;
import lombok.Data;
@Data
public class FloomResponseValue {
public String format;
public String value;
public String type;
public String b64;
public String url;
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/metrics/k8s
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/metrics/k8s/starter/CommonMetricsFilter.java
|
/**
* Licensed to the Foremast 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.metrics.k8s.starter;
import ai.foremast.micrometer.autoconfigure.MetricsProperties;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.config.MeterFilter;
import io.micrometer.core.instrument.config.MeterFilterReply;
import org.springframework.util.StringUtils;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
/**
* Common Metrics Filter is to hide the metrics by default, and show the metrics what are in the whitelist.
*
* If the metric is enabled in properties, keep it enabled.
* If the metric is disabled in properties, keep it disabled.
* If the metric starts with "PREFIX", enable it. otherwise disable the metric
*
* @author Sheldon Shao
* @version 1.0
*/
public class CommonMetricsFilter implements MeterFilter {
private MetricsProperties properties;
private String[] prefixes = new String[] {};
private Set<String> whitelist = new HashSet<>();
private Set<String> blacklist = new HashSet<>();
private K8sMetricsProperties k8sMetricsProperties;
private boolean actionEnabled = false;
private LinkedHashMap<String, String> tagRules = new LinkedHashMap<>();
public CommonMetricsFilter(K8sMetricsProperties k8sMetricsProperties, MetricsProperties properties) {
this.properties = properties;
this.k8sMetricsProperties = k8sMetricsProperties;
this.actionEnabled = k8sMetricsProperties.isEnableCommonMetricsFilterAction();
String list = k8sMetricsProperties.getCommonMetricsBlacklist();
if (list != null && !list.isEmpty()) {
String[] array = StringUtils.tokenizeToStringArray(list, ",", true, true);
for(String str: array) {
str = filter(str.trim());
blacklist.add(str);
}
}
list = k8sMetricsProperties.getCommonMetricsWhitelist();
if (list != null && !list.isEmpty()) {
String[] array = StringUtils.tokenizeToStringArray(list, ",", true, true);
for(String str: array) {
str = filter(str.trim());
whitelist.add(str);
}
}
list = k8sMetricsProperties.getCommonMetricsPrefix();
if (list != null && !list.isEmpty()) {
prefixes = StringUtils.tokenizeToStringArray(list, ",", true, true);
}
String tagRuleExpressions = k8sMetricsProperties.getCommonMetricsTagRules();
if (tagRuleExpressions != null) {
String[] array = StringUtils.tokenizeToStringArray(tagRuleExpressions, ",", true, true);
for(String str: array) {
str = str.trim();
String[] nameAndValue = str.split(":");
if (nameAndValue == null || nameAndValue.length != 2) {
throw new IllegalStateException("Invalid common tag name value pair:" + str);
}
tagRules.put(nameAndValue[0].trim(), nameAndValue[1].trim());
}
}
}
/**
* Filter for "[PREFIX]_*"
*
* @param id
* @return MeterFilterReply
*/
public MeterFilterReply accept(Meter.Id id) {
if (!k8sMetricsProperties.isEnableCommonMetricsFilter()) {
return MeterFilter.super.accept(id);
}
String metricName = id.getName();
Boolean enabled = lookupWithFallbackToAll(this.properties.getEnable(), id, null);
if (enabled != null) {
return enabled ? MeterFilterReply.NEUTRAL : MeterFilterReply.DENY;
}
if (whitelist.contains(metricName)) {
return MeterFilterReply.NEUTRAL;
}
if (blacklist.contains(metricName)) {
return MeterFilterReply.DENY;
}
for(String prefix: prefixes) {
if (metricName.startsWith(prefix)) {
return MeterFilterReply.ACCEPT;
}
}
for(String key: tagRules.keySet()) {
String expectedValue = tagRules.get(key);
if (expectedValue != null) {
if (expectedValue.equals(id.getTag(key))) {
return MeterFilterReply.ACCEPT;
}
}
}
return MeterFilterReply.DENY;
}
protected String filter(String metricName) {
return metricName.replace('_', '.');
}
public void enableMetric(String metricName) {
metricName = filter(metricName);
if (blacklist.contains(metricName)) {
blacklist.remove(metricName);
}
if (!whitelist.contains(metricName)) {
whitelist.add(metricName);
}
}
public void disableMetric(String metricName) {
metricName = filter(metricName);
if (whitelist.contains(metricName)) {
whitelist.remove(metricName);
}
if (!blacklist.contains(metricName)) {
blacklist.add(metricName);
}
}
private <T> T lookup(Map<String, T> values, Meter.Id id, T defaultValue) {
if (values.isEmpty()) {
return defaultValue;
}
return doLookup(values, id, () -> defaultValue);
}
private <T> T lookupWithFallbackToAll(Map<String, T> values, Meter.Id id, T defaultValue) {
if (values.isEmpty()) {
return defaultValue;
}
return doLookup(values, id, () -> values.getOrDefault("all", defaultValue));
}
private <T> T doLookup(Map<String, T> values, Meter.Id id, Supplier<T> defaultValue) {
String name = id.getName();
while (name != null && !name.isEmpty()) {
T result = values.get(name);
if (result != null) {
return result;
}
int lastDot = name.lastIndexOf('.');
name = (lastDot != -1) ? name.substring(0, lastDot) : "";
}
return defaultValue.get();
}
public String[] getPrefixes() {
return prefixes;
}
public void setPrefixes(String[] prefixes) {
this.prefixes = prefixes;
}
public boolean isActionEnabled() {
return actionEnabled;
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/metrics/k8s
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/metrics/k8s/starter/K8sMetricsAutoConfiguration.java
|
package ai.foremast.metrics.k8s.starter;
import ai.foremast.micrometer.autoconfigure.MeterRegistryCustomizer;
import ai.foremast.micrometer.autoconfigure.MetricsProperties;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.regex.Pattern;
/**
* Auto metrics configurations
*/
@Configuration
public class K8sMetricsAutoConfiguration implements MeterRegistryCustomizer {
@Autowired
K8sMetricsProperties k8sMetricsProperties;
@Autowired
ConfigurableApplicationContext appContext;
private static final String HTTP_SERVER_REQUESTS = "http.server.requests";
@Bean
public K8sMetricsProperties k8sMetricsProperties() {
return k8sMetricsProperties = new K8sMetricsProperties();
}
@Bean
public CommonMetricsFilter commonMetricsFilter(K8sMetricsProperties k8sMetricsProperties, MetricsProperties properties) {
return new CommonMetricsFilter(k8sMetricsProperties, properties);
}
@Override
public void customize(MeterRegistry registry) {
String commonTagNameValuePair = k8sMetricsProperties.getCommonTagNameValuePairs();
if (commonTagNameValuePair != null && !commonTagNameValuePair.isEmpty()) {
String[] pairs = commonTagNameValuePair.split(",");
for(String p : pairs) {
String[] nameAndValue = p.split(":");
if (nameAndValue == null || nameAndValue.length != 2) {
throw new IllegalStateException("Invalid common tag name value pair:" + p);
}
String valuePattern = nameAndValue[1];
int sepIndex = valuePattern.indexOf('|');
String[] patterns = null;
if (sepIndex > 0) {
patterns = valuePattern.split(Pattern.quote("|"));
}
else {
patterns = new String[] { valuePattern };
}
for(int i = 0; i < patterns.length; i ++) {
String value = null;
if (patterns[i].startsWith("ENV.")) {
value = System.getenv(patterns[i].substring(4));
}
else {
value = System.getProperty(patterns[i]);
if ((value == null || value.isEmpty()) && appContext != null) {
value = appContext.getEnvironment().getProperty(patterns[i]);
}
}
if (value != null && !value.isEmpty()) {
registry.config().commonTags(nameAndValue[0], value);
break;
}
}
}
}
String statuses = k8sMetricsProperties.getInitializeForStatuses();
if (statuses != null || !statuses.isEmpty()) {
String[] statusCodes = statuses.split(",");
for(String code: statusCodes) {
if (k8sMetricsProperties.hasCaller()) {
registry.timer(HTTP_SERVER_REQUESTS, "exception", "None", "method", "GET", "status", code, "uri", "/**", "caller", "*");
}
else {
registry.timer(HTTP_SERVER_REQUESTS, "exception", "None", "method", "GET", "status", code, "uri", "/**");
}
}
}
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/metrics/k8s
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/metrics/k8s/starter/K8sMetricsProperties.java
|
package ai.foremast.metrics.k8s.starter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class K8sMetricsProperties {
@Value( "${k8s.metrics.common-tag-name-value-pairs}" )
private String commonTagNameValuePairs = "app:ENV.APP_NAME|info.app.name";
@Value("${k8s.metrics.initialize-for-statuses}")
private String initializeForStatuses = "404,501";
public static final String APP_ASSET_ALIAS_HEADER = "X-CALLER";
@Value("${k8s.metrics.caller-header}")
private String callerHeader = APP_ASSET_ALIAS_HEADER;
@Value("${k8s.metrics.enable-common-metrics-filter}")
private boolean enableCommonMetricsFilter = false;
@Value("${k8s.metrics.common-metrics-whitelist}")
private String commonMetricsWhitelist = null;
@Value("${k8s.metrics.common-metrics-blacklist}")
private String commonMetricsBlacklist = null;
@Value("${k8s.metrics.common-metrics-prefix}")
private String commonMetricsPrefix = null;
@Value("${k8s.metrics.enable-common-metrics-filter-action}")
private boolean enableCommonMetricsFilterAction = false;
@Value("${k8s.metrics.common-metrics-tag-rules}")
private String commonMetricsTagRules = null;
public String getInitializeForStatuses() {
return initializeForStatuses;
}
public void setInitializeForStatuses(String initializeForStatuses) {
this.initializeForStatuses = initializeForStatuses;
}
public String getCommonTagNameValuePairs() {
return commonTagNameValuePairs;
}
public void setCommonTagNameValuePairs(String commonTagNameValuePairs) {
this.commonTagNameValuePairs = commonTagNameValuePairs;
}
public String getCallerHeader() {
return callerHeader;
}
public boolean hasCaller() {
return callerHeader != null && !callerHeader.isEmpty();
}
public void setCallerHeader(String callerHeader) {
this.callerHeader = callerHeader;
}
public boolean isEnableCommonMetricsFilter() {
return enableCommonMetricsFilter;
}
public void setEnableCommonMetricsFilter(boolean enableCommonMetricsFilter) {
this.enableCommonMetricsFilter = enableCommonMetricsFilter;
}
public String getCommonMetricsWhitelist() {
return commonMetricsWhitelist;
}
public void setCommonMetricsWhitelist(String commonMetricsWhitelist) {
this.commonMetricsWhitelist = commonMetricsWhitelist;
}
public String getCommonMetricsBlacklist() {
return commonMetricsBlacklist;
}
public void setCommonMetricsBlacklist(String commonMetricsBlacklist) {
this.commonMetricsBlacklist = commonMetricsBlacklist;
}
public String getCommonMetricsPrefix() {
return commonMetricsPrefix;
}
public void setCommonMetricsPrefix(String commonMetricsPrefix) {
this.commonMetricsPrefix = commonMetricsPrefix;
}
public boolean isEnableCommonMetricsFilterAction() {
return enableCommonMetricsFilterAction;
}
public void setEnableCommonMetricsFilterAction(boolean enableCommonMetricsFilterAction) {
this.enableCommonMetricsFilterAction = enableCommonMetricsFilterAction;
}
public String getCommonMetricsTagRules() {
return commonMetricsTagRules;
}
public void setCommonMetricsTagRules(String commonMetricsTagRules) {
this.commonMetricsTagRules = commonMetricsTagRules;
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/TimedUtils.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer;
import io.micrometer.core.annotation.Timed;
import io.micrometer.core.annotation.TimedSet;
import org.springframework.core.annotation.*;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;
public final class TimedUtils {
private TimedUtils() {
}
public static Set<Timed> findTimedAnnotations(Method method) {
Timed t = AnnotationUtils.findAnnotation(method, Timed.class);
//noinspection ConstantConditions
if (t != null)
return Collections.singleton(t);
TimedSet ts = AnnotationUtils.findAnnotation(method, TimedSet.class);
if (ts != null) {
return Arrays.stream(ts.value()).collect(Collectors.toSet());
}
return Collections.emptySet();
}
public static Set<Timed> findTimedAnnotations(Class<?> clazz) {
Timed t = AnnotationUtils.findAnnotation(clazz, Timed.class);
//noinspection ConstantConditions
if (t != null)
return Collections.singleton(t);
TimedSet ts = AnnotationUtils.findAnnotation(clazz, TimedSet.class);
if (ts != null) {
return Arrays.stream(ts.value()).collect(Collectors.toSet());
}
return Collections.emptySet();
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/autoconfigure/MeterRegistryConfigurer.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.binder.MeterBinder;
import io.micrometer.core.instrument.config.MeterFilter;
import java.util.Collection;
import java.util.Collections;
/**
* Applies {@link MeterRegistryCustomizer customizers}, {@link MeterFilter filters},
* {@link MeterBinder binders} and {@link Metrics#addRegistry
* global registration} to {@link MeterRegistry meter registries}.
*
* @author Jon Schneider
* @author Phillip Webb
*/
class MeterRegistryConfigurer {
private final Collection<MeterRegistryCustomizer<?>> customizers;
private final Collection<MeterFilter> filters;
private final Collection<MeterBinder> binders;
private final boolean addToGlobalRegistry;
MeterRegistryConfigurer(Collection<MeterBinder> binders,
Collection<MeterFilter> filters,
Collection<MeterRegistryCustomizer<?>> customizers,
boolean addToGlobalRegistry) {
this.binders = (binders != null ? binders : Collections.emptyList());
this.filters = (filters != null ? filters : Collections.emptyList());
this.customizers = (customizers != null ? customizers : Collections.emptyList());
this.addToGlobalRegistry = addToGlobalRegistry;
}
void configure(MeterRegistry registry) {
// Customizers must be applied before binders, as they may add custom
// tags or alter timer or summary configuration.
customize(registry);
addFilters(registry);
addBinders(registry);
if (this.addToGlobalRegistry && registry != Metrics.globalRegistry) {
Metrics.addRegistry(registry);
}
}
@SuppressWarnings("unchecked")
private void customize(MeterRegistry registry) {
// Customizers must be applied before binders, as they may add custom tags or alter
// timer or summary configuration.
for (MeterRegistryCustomizer customizer : this.customizers) {
try {
customizer.customize(registry);
} catch (ClassCastException ignored) {
// This is essentially what LambdaSafe.callbacks(..).invoke(..) is doing
// in Spring Boot 2, just trapping ClassCastExceptions since the generic type
// has been erased by this point.
}
}
}
private void addFilters(MeterRegistry registry) {
this.filters.forEach(registry.config()::meterFilter);
}
private void addBinders(MeterRegistry registry) {
this.binders.forEach((binder) -> binder.bindTo(registry));
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/autoconfigure/MeterRegistryCustomizer.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.lang.NonNullApi;
/**
* Callback interface that can be used to customize the primary auto-configured {@link MeterRegistry}.
* <p>
* Configurers are guaranteed to be applied before any {@link Meter} is registered with
* the registry.
*
* @author Jon Schneider
*/
@FunctionalInterface
@NonNullApi
public interface MeterRegistryCustomizer<M extends MeterRegistry> {
/**
* Configure the given registry.
*
* @param registry the registry to configure
*/
void customize(M registry);
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/autoconfigure/MeterRegistryPostProcessor.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.MeterBinder;
import io.micrometer.core.instrument.config.MeterFilter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.config.BeanPostProcessor;
import java.util.*;
/**
* {@link BeanPostProcessor} that delegates to a lazily created
* {@link MeterRegistryConfigurer} to post-process {@link MeterRegistry} beans.
*
* @author Jon Schneider
* @author Phillip Webb
* @author Andy Wilkinson
*/
class MeterRegistryPostProcessor implements BeanPostProcessor, BeanFactoryAware {
private BeanFactory beanFactory;
private volatile MeterRegistryConfigurer configurer;
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof MeterRegistry) {
getConfigurer().configure((MeterRegistry) bean);
}
return bean;
}
private MeterRegistryConfigurer getConfigurer() {
if (this.configurer == null) {
Collection<MeterBinder> meterBinders = Collections.emptyList();
Collection<MeterFilter> meterFilters = Collections.emptyList();
Collection<MeterRegistryCustomizer<?>> meterRegistryCustomizers = Collections.emptyList();
MetricsProperties properties = beanFactory.getBean(MetricsProperties.class);
if (beanFactory instanceof ListableBeanFactory) {
ListableBeanFactory listableBeanFactory = (ListableBeanFactory)beanFactory;
meterBinders = listableBeanFactory.getBeansOfType(MeterBinder.class).values();
meterFilters = listableBeanFactory.getBeansOfType(MeterFilter.class).values();
Map<String, MeterRegistryCustomizer> map = listableBeanFactory.getBeansOfType(MeterRegistryCustomizer.class);
meterRegistryCustomizers = new ArrayList<>();
for(MeterRegistryCustomizer c : map.values()) {
meterRegistryCustomizers.add(c);
}
}
this.configurer = new MeterRegistryConfigurer(
meterBinders,
meterFilters,
meterRegistryCustomizers, properties.isUseGlobalRegistry());
}
return this.configurer;
}
private <T> List<T> getOrEmpty(List<T> list) {
return list != null ? list : Collections.emptyList();
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/autoconfigure/MeterValue.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure;
import io.micrometer.core.instrument.Meter;
import ai.foremast.micrometer.autoconfigure.export.StringToDurationConverter;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
/**
* A meter value that is used when configuring micrometer. Can be a String representation
* of either a {@link Long} (applicable to timers and distribution summaries) or a
* {@link Duration} (applicable to only timers).
*
* @author Phillip Webb
*/
final class MeterValue {
private static final StringToDurationConverter durationConverter = new StringToDurationConverter();
private final Object value;
MeterValue(long value) {
this.value = value;
}
MeterValue(Duration value) {
this.value = value;
}
/**
* Return the underlying value of the SLA in form suitable to apply to the given meter
* type.
* @param meterType the meter type
* @return the value or {@code null} if the value cannot be applied
*/
public Long getValue(Meter.Type meterType) {
if (meterType == Meter.Type.DISTRIBUTION_SUMMARY) {
return getDistributionSummaryValue();
}
if (meterType == Meter.Type.TIMER) {
return getTimerValue();
}
return null;
}
private Long getDistributionSummaryValue() {
if (this.value instanceof Long) {
return (Long) this.value;
}
return null;
}
private Long getTimerValue() {
if (this.value instanceof Long) {
return TimeUnit.MILLISECONDS.toNanos((long) this.value);
}
if (this.value instanceof Duration) {
return ((Duration) this.value).toNanos();
}
return null;
}
/**
* Return a new {@link MeterValue} instance for the given String value. The value may
* contain a simple number, or a {@link Duration duration string}.
* @param value the source value
* @return a {@link MeterValue} instance
*/
public static MeterValue valueOf(String value) {
if (isNumber(value)) {
return new MeterValue(Long.parseLong(value));
}
return new MeterValue(durationConverter.convert(value));
}
/**
* Return a new {@link MeterValue} instance for the given long value.
* @param value the source value
* @return a {@link MeterValue} instance
*/
public static MeterValue valueOf(long value) {
return new MeterValue(value);
}
private static boolean isNumber(String value) {
return value.chars().allMatch(Character::isDigit);
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/autoconfigure/MetricsAutoConfiguration.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure;
import ai.foremast.micrometer.autoconfigure.export.prometheus.PrometheusProperties;
import ai.foremast.micrometer.autoconfigure.export.prometheus.PrometheusPropertiesConfigAdapter;
import io.micrometer.core.instrument.Clock;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.jvm.ClassLoaderMetrics;
import io.micrometer.core.instrument.binder.jvm.JvmGcMetrics;
import io.micrometer.core.instrument.binder.jvm.JvmMemoryMetrics;
import io.micrometer.core.instrument.binder.jvm.JvmThreadMetrics;
import io.micrometer.core.instrument.binder.system.FileDescriptorMetrics;
import io.micrometer.core.instrument.binder.system.ProcessorMetrics;
import io.micrometer.core.instrument.binder.system.UptimeMetrics;
import io.micrometer.core.instrument.composite.CompositeMeterRegistry;
import io.micrometer.core.instrument.config.MeterFilter;
import io.micrometer.prometheus.PrometheusConfig;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import io.prometheus.client.CollectorRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import java.util.List;
/**
*
* @author Jon Schneider
*/
@Configuration
public class MetricsAutoConfiguration {
@Bean
public Clock micrometerClock() {
return Clock.SYSTEM;
}
@Bean
public static MeterRegistryPostProcessor meterRegistryPostProcessor() {
return new MeterRegistryPostProcessor();
}
@Bean
public MetricsProperties metricsProperties() {
return new MetricsProperties();
}
@Autowired
private PrometheusProperties prometheusProperties;
@Bean
public PrometheusProperties prometheusProperties() {
return prometheusProperties = new PrometheusProperties();
}
@Bean
@Order(0)
public PropertiesMeterFilter propertiesMeterFilter(MetricsProperties properties) {
return new PropertiesMeterFilter(properties);
}
@Bean
public PrometheusConfig prometheusConfig() {
return new PrometheusPropertiesConfigAdapter(prometheusProperties);
}
@Bean
public PrometheusMeterRegistry prometheusMeterRegistry(PrometheusConfig config, CollectorRegistry collectorRegistry,
Clock clock) {
return new PrometheusMeterRegistry(config, collectorRegistry, clock);
}
@Bean
public CollectorRegistry collectorRegistry() {
return new CollectorRegistry(true);
}
@Bean
@Order(0)
public MeterFilter metricsHttpServerUriTagFilter(MetricsProperties properties) {
String metricName = properties.getWeb().getServer().getRequestsMetricName();
MeterFilter filter = new OnlyOnceLoggingDenyMeterFilter(() -> String
.format("Reached the maximum number of URI tags for '%s'.", metricName));
return MeterFilter.maximumAllowableTags(metricName, "uri",
properties.getWeb().getServer().getMaxUriTags(), filter);
}
@Bean
public CompositeMeterRegistry noOpMeterRegistry(Clock clock) {
return new CompositeMeterRegistry(clock);
}
@Bean
@Primary
public CompositeMeterRegistry compositeMeterRegistry(Clock clock, List<MeterRegistry> registries) {
return new CompositeMeterRegistry(clock, registries);
}
@Bean
public UptimeMetrics uptimeMetrics() {
return new UptimeMetrics();
}
@Bean
public ProcessorMetrics processorMetrics() {
return new ProcessorMetrics();
}
@Bean
public FileDescriptorMetrics fileDescriptorMetrics() {
return new FileDescriptorMetrics();
}
//JVM
@Bean
public JvmGcMetrics jvmGcMetrics() {
return new JvmGcMetrics();
}
@Bean
public JvmMemoryMetrics jvmMemoryMetrics() {
return new JvmMemoryMetrics();
}
@Bean
public JvmThreadMetrics jvmThreadMetrics() {
return new JvmThreadMetrics();
}
@Bean
public ClassLoaderMetrics classLoaderMetrics() {
return new ClassLoaderMetrics();
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/autoconfigure/MetricsProperties.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* {@link ConfigurationProperties} for configuring Micrometer-based metrics.
*
* @author Jon Schneider
* @author Alexander Abramov
*/
//@ConfigurationProperties("management.metrics")
@Component
public class MetricsProperties {
private final Web web = new Web();
private final Distribution distribution = new Distribution();
/**
* If {@code false}, the matching meter(s) are no-op.
*/
private final Map<String, Boolean> enable = new HashMap<>();
/**
* Common tags that are applied to every meter.
*/
private final Map<String, String> tags = new LinkedHashMap<>();
/**
* Whether or not auto-configured MeterRegistry implementations should be bound to the
* global static registry on Metrics. For testing, set this to 'false' to maximize
* test independence.
*/
@Value("${management.metrics.use-global-registry}")
private boolean useGlobalRegistry = true;
public boolean isUseGlobalRegistry() {
return this.useGlobalRegistry;
}
public void setUseGlobalRegistry(boolean useGlobalRegistry) {
this.useGlobalRegistry = useGlobalRegistry;
}
public Web getWeb() {
return this.web;
}
public Map<String, Boolean> getEnable() {
return enable;
}
public Map<String, String> getTags() {
return this.tags;
}
public Distribution getDistribution() {
return distribution;
}
public static class Web {
private final Client client = new Client();
private final Server server = new Server();
public Client getClient() {
return this.client;
}
public Server getServer() {
return this.server;
}
public static class Client {
/**
* Name of the metric for sent requests.
*/
private String requestsMetricName = "http.client.requests";
/**
* Maximum number of unique URI tag values allowed. After the max number of tag values is reached,
* metrics with additional tag values are denied by filter.
*/
private int maxUriTags = 100;
public String getRequestsMetricName() {
return this.requestsMetricName;
}
public void setRequestsMetricName(String requestsMetricName) {
this.requestsMetricName = requestsMetricName;
}
public int getMaxUriTags() {
return maxUriTags;
}
public void setMaxUriTags(int maxUriTags) {
this.maxUriTags = maxUriTags;
}
}
public static class Server {
/**
* Whether or not requests handled by Spring MVC or WebFlux should be
* automatically timed. If the number of time series emitted grows too large
* on account of request mapping timings, disable this and use 'Timed' on a
* per request mapping basis as needed.
*/
private boolean autoTimeRequests = true;
/**
* Name of the metric for received requests.
*/
private String requestsMetricName = "http.server.requests";
/**
* Maximum number of unique URI tag values allowed. After the max number of
* tag values is reached, metrics with additional tag values are denied by
* filter.
*/
private int maxUriTags = 100;
public boolean isAutoTimeRequests() {
return this.autoTimeRequests;
}
public void setAutoTimeRequests(boolean autoTimeRequests) {
this.autoTimeRequests = autoTimeRequests;
}
public String getRequestsMetricName() {
return this.requestsMetricName;
}
public void setRequestsMetricName(String requestsMetricName) {
this.requestsMetricName = requestsMetricName;
}
public int getMaxUriTags() {
return this.maxUriTags;
}
public void setMaxUriTags(int maxUriTags) {
this.maxUriTags = maxUriTags;
}
}
}
public static class Distribution {
/**
* Whether meter IDs starting with the specified name should publish percentile
* histograms. For monitoring systems that support aggregable percentile
* calculation based on a histogram, this can be set to true. For other systems,
* this has no effect. The longest match wins, the key `all` can also be used to
* configure all meters.
*/
private final Map<String, Boolean> percentilesHistogram = new LinkedHashMap<>();
/**
* Specific computed non-aggregable percentiles to ship to the backend for meter
* IDs starting-with the specified name. The longest match wins, the key `all` can
* also be used to configure all meters.
*/
private final Map<String, double[]> percentiles = new LinkedHashMap<>();
/**
* Specific SLA boundaries for meter IDs starting-with the specified name. The
* longest match wins. Counters will be published for each specified boundary.
* Values can be specified as a long or as a Duration value (for timer meters,
* defaulting to ms if no unit specified).
*/
private final Map<String, ServiceLevelAgreementBoundary[]> sla = new LinkedHashMap<>();
/**
* Minimum value that meter IDs starting-with the specified name are expected to
* observe. The longest match wins. Values can be specified as a long or as a
* Duration value (for timer meters, defaulting to ms if no unit specified).
*/
private final Map<String, String> minimumExpectedValue = new LinkedHashMap<>();
/**
* Maximum value that meter IDs starting-with the specified name are expected to
* observe. The longest match wins. Values can be specified as a long or as a
* Duration value (for timer meters, defaulting to ms if no unit specified).
*/
private final Map<String, String> maximumExpectedValue = new LinkedHashMap<>();
public Map<String, Boolean> getPercentilesHistogram() {
return this.percentilesHistogram;
}
public Map<String, double[]> getPercentiles() {
return this.percentiles;
}
public Map<String, ServiceLevelAgreementBoundary[]> getSla() {
return this.sla;
}
public Map<String, String> getMinimumExpectedValue() {
return this.minimumExpectedValue;
}
public Map<String, String> getMaximumExpectedValue() {
return this.maximumExpectedValue;
}
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/autoconfigure/OnlyOnceLoggingDenyMeterFilter.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.config.MeterFilter;
import io.micrometer.core.instrument.config.MeterFilterReply;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Supplier;
/**
* {@link MeterFilter} to log only once a warning message and deny a {@link Meter}
* {@link Meter.Id}.
*
* @author Jon Schneider
* @author Dmytro Nosan
*/
public final class OnlyOnceLoggingDenyMeterFilter implements MeterFilter {
private static final Log logger = LogFactory
.getLog(OnlyOnceLoggingDenyMeterFilter.class);
private final AtomicBoolean alreadyWarned = new AtomicBoolean(false);
private final Supplier<String> message;
public OnlyOnceLoggingDenyMeterFilter(Supplier<String> message) {
Assert.notNull(message, "Message must not be null");
this.message = message;
}
@Override
public MeterFilterReply accept(Meter.Id id) {
if (logger.isWarnEnabled()
&& this.alreadyWarned.compareAndSet(false, true)) {
logger.warn(this.message.get());
}
return MeterFilterReply.DENY;
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/autoconfigure/PropertiesMeterFilter.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.Meter.Id;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.config.MeterFilter;
import io.micrometer.core.instrument.config.MeterFilterReply;
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig;
import ai.foremast.micrometer.autoconfigure.MetricsProperties.Distribution;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* {@link MeterFilter} to apply settings from {@link MetricsProperties}.
*
* @author Jon Schneider
* @author Phillip Webb
* @author Stephane Nicoll
* @author Artsiom Yudovin
* @author Alexander Abramov
*/
public class PropertiesMeterFilter implements MeterFilter {
private final MetricsProperties properties;
private final MeterFilter mapFilter;
public PropertiesMeterFilter(MetricsProperties properties) {
Assert.notNull(properties, "Properties must not be null");
this.properties = properties;
this.mapFilter = createMapFilter(properties.getTags());
}
private static MeterFilter createMapFilter(Map<String, String> tags) {
if (tags.isEmpty()) {
return new MeterFilter() {
};
}
Tags commonTags = Tags.of(tags.entrySet().stream()
.map((entry) -> Tag.of(entry.getKey(), entry.getValue()))
.collect(Collectors.toList()));
return MeterFilter.commonTags(commonTags);
}
@Override
public MeterFilterReply accept(Meter.Id id) {
boolean enabled = lookupWithFallbackToAll(this.properties.getEnable(), id, true);
return enabled ? MeterFilterReply.NEUTRAL : MeterFilterReply.DENY;
}
@Override
public Id map(Id id) {
return this.mapFilter.map(id);
}
@Override
public DistributionStatisticConfig configure(Meter.Id id,
DistributionStatisticConfig config) {
Distribution distribution = this.properties.getDistribution();
return DistributionStatisticConfig.builder()
.percentilesHistogram(
lookupWithFallbackToAll(distribution.getPercentilesHistogram(), id, null))
.percentiles(
lookupWithFallbackToAll(distribution.getPercentiles(), id, null))
.sla(convertSla(id.getType(), lookup(distribution.getSla(), id, null)))
.minimumExpectedValue(convertMeterValue(id.getType(),
lookup(distribution.getMinimumExpectedValue(), id, null)))
.maximumExpectedValue(convertMeterValue(id.getType(),
lookup(distribution.getMaximumExpectedValue(), id, null)))
.build().merge(config);
}
private long[] convertSla(Meter.Type meterType, ServiceLevelAgreementBoundary[] sla) {
if (sla == null) {
return null;
}
long[] converted = Arrays.stream(sla)
.map((candidate) -> candidate.getValue(meterType))
.filter(Objects::nonNull).mapToLong(Long::longValue).toArray();
return (converted.length != 0) ? converted : null;
}
private Long convertMeterValue(Meter.Type meterType, String value) {
return (value != null) ? MeterValue.valueOf(value).getValue(meterType) : null;
}
private <T> T lookup(Map<String, T> values, Id id, T defaultValue) {
if (values.isEmpty()) {
return defaultValue;
}
return doLookup(values, id, () -> defaultValue);
}
private <T> T lookupWithFallbackToAll(Map<String, T> values, Id id, T defaultValue) {
if (values.isEmpty()) {
return defaultValue;
}
return doLookup(values, id, () -> values.getOrDefault("all", defaultValue));
}
private <T> T doLookup(Map<String, T> values, Id id, Supplier<T> defaultValue) {
String name = id.getName();
while (StringUtils.hasLength(name)) {
T result = values.get(name);
if (result != null) {
return result;
}
int lastDot = name.lastIndexOf('.');
name = (lastDot != -1) ? name.substring(0, lastDot) : "";
}
return defaultValue.get();
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/autoconfigure/ServiceLevelAgreementBoundary.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure;
import io.micrometer.core.instrument.Meter;
import java.time.Duration;
/**
* A service level agreement boundary for use when configuring Micrometer. Can be
* specified as either a {@link Long} (applicable to timers and distribution summaries) or
* a {@link Duration} (applicable to only timers).
*
* @author Phillip Webb
*/
public final class ServiceLevelAgreementBoundary {
private final MeterValue value;
ServiceLevelAgreementBoundary(MeterValue value) {
this.value = value;
}
/**
* Return the underlying value of the SLA in form suitable to apply to the given meter
* type.
* @param meterType the meter type
* @return the value or {@code null} if the value cannot be applied
*/
public Long getValue(Meter.Type meterType) {
return this.value.getValue(meterType);
}
/**
* Return a new {@link ServiceLevelAgreementBoundary} instance for the given long
* value.
* @param value the source value
* @return a {@link ServiceLevelAgreementBoundary} instance
*/
public static ServiceLevelAgreementBoundary valueOf(long value) {
return new ServiceLevelAgreementBoundary(MeterValue.valueOf(value));
}
/**
* Return a new {@link ServiceLevelAgreementBoundary} instance for the given long
* value.
* @param value the source value
* @return a {@link ServiceLevelAgreementBoundary} instance
*/
public static ServiceLevelAgreementBoundary valueOf(String value) {
return new ServiceLevelAgreementBoundary(MeterValue.valueOf(value));
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/autoconfigure
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/autoconfigure/export/StringToDurationConverter.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure.export;
import io.micrometer.core.instrument.util.StringUtils;
import io.micrometer.core.lang.Nullable;
import org.springframework.core.annotation.Order;
import org.springframework.core.convert.converter.Converter;
import java.time.Duration;
import java.time.format.DateTimeParseException;
import java.util.Optional;
import java.util.function.Function;
/**
* A {@link Converter} to create a {@link Duration} from a {@link String}.
*
* @author Jon Schneider
* @author Andy Wilkinson
*/
//@ConfigurationPropertiesBinding
@Order(0)
public class StringToDurationConverter implements Converter<String, Duration> {
@Nullable
private static Duration simpleParse(@Nullable String rawTime) {
if (StringUtils.isEmpty(rawTime))
return null;
if (!Character.isDigit(rawTime.charAt(0)))
return null;
String time = rawTime.toLowerCase();
return tryParse(time, "ns", Duration::ofNanos)
.orElseGet(() -> tryParse(time, "ms", Duration::ofMillis)
.orElseGet(() -> tryParse(time, "s", Duration::ofSeconds)
.orElseGet(() -> tryParse(time, "m", Duration::ofMinutes)
.orElseGet(() -> tryParse(time, "h", Duration::ofHours)
.orElseGet(() -> tryParse(time, "d", Duration::ofDays)
.orElse(null))))));
}
private static Optional<Duration> tryParse(String time, String unit, Function<Long, Duration> toDuration) {
if (time.endsWith(unit)) {
String trim = time.substring(0, time.lastIndexOf(unit)).trim();
try {
return Optional.of(toDuration.apply(Long.parseLong(trim)));
} catch (NumberFormatException ignore) {
return Optional.empty();
}
}
return Optional.empty();
}
@Override
public Duration convert(@Nullable String source) {
Duration duration = simpleParse(source);
try {
return duration == null ? Duration.parse(source) : duration;
} catch (DateTimeParseException e) {
throw new IllegalArgumentException("Cannot convert '" + source + "' to Duration", e);
}
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/autoconfigure
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/autoconfigure/export/StringToTimeUnitConverter.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure.export;
//import org.springframework.boot.context.properties.ConfigurationPropertiesBinding;
import org.springframework.core.annotation.Order;
import org.springframework.core.convert.converter.Converter;
import java.util.concurrent.TimeUnit;
/**
* @author Nicolas Portmann
*/
//@ConfigurationPropertiesBinding
@Order(0)
public class StringToTimeUnitConverter implements Converter<String, TimeUnit> {
@Override
public TimeUnit convert(String source) {
return TimeUnit.valueOf(source.toUpperCase());
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/autoconfigure/export
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/autoconfigure/export/prometheus/PrometheusProperties.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure.export.prometheus;
import org.springframework.beans.factory.annotation.Value;
import java.time.Duration;
/**
* {@link ConfigurationProperties} for configuring metrics export to Prometheus.
*
* @author Jon Schneider
*/
//@ConfigurationProperties(prefix = "management.metrics.export.prometheus")
public class PrometheusProperties {
/**
* Whether to enable publishing descriptions as part of the scrape payload to
* Prometheus. Turn this off to minimize the amount of data sent on each scrape.
*/
@Value("${management.metrics.export.prometheus.descriptions}")
private boolean descriptions = true;
/**
* Step size (i.e. reporting frequency) to use.
*/
private Duration step = Duration.ofMinutes(1);
public boolean isDescriptions() {
return this.descriptions;
}
public void setDescriptions(boolean descriptions) {
this.descriptions = descriptions;
}
public Duration getStep() {
return this.step;
}
public void setStep(Duration step) {
this.step = step;
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/autoconfigure/export
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/autoconfigure/export/prometheus/PrometheusPropertiesConfigAdapter.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure.export.prometheus;
import io.micrometer.prometheus.PrometheusConfig;
import ai.foremast.micrometer.autoconfigure.export.properties.PropertiesConfigAdapter;
import java.time.Duration;
/**
* Adapter to convert {@link PrometheusProperties} to a {@link PrometheusConfig}.
*
* @author Jon Schneider
* @author Phillip Webb
*/
public class PrometheusPropertiesConfigAdapter extends PropertiesConfigAdapter<PrometheusProperties> implements PrometheusConfig {
public PrometheusPropertiesConfigAdapter(PrometheusProperties properties) {
super(properties);
}
@Override
public String get(String key) {
return null;
}
@Override
public boolean descriptions() {
return get(PrometheusProperties::isDescriptions,
PrometheusConfig.super::descriptions);
}
@Override
public Duration step() {
return get(PrometheusProperties::getStep, PrometheusConfig.super::step);
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/autoconfigure/export
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/autoconfigure/export/properties/PropertiesConfigAdapter.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure.export.properties;
import org.springframework.util.Assert;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* Base class for properties to config adapters.
*
* @param <T> The properties type
* @author Phillip Webb
* @author Nikolay Rybak
*/
public class PropertiesConfigAdapter<T> {
private T properties;
/**
* Create a new {@link PropertiesConfigAdapter} instance.
*
* @param properties the source properties
*/
public PropertiesConfigAdapter(T properties) {
Assert.notNull(properties, "Properties must not be null");
this.properties = properties;
}
/**
* Get the value from the properties or use a fallback from the {@code defaults}.
*
* @param getter the getter for the properties
* @param fallback the fallback method, usually super interface method reference
* @param <V> the value type
* @return the property or fallback value
*/
protected final <V> V get(Function<T, V> getter, Supplier<V> fallback) {
V value = getter.apply(properties);
return (value != null ? value : fallback.get());
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/autoconfigure/export
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/autoconfigure/export/properties/StepRegistryProperties.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure.export.properties;
import java.time.Duration;
/**
* Base class for properties that configure a metrics registry that pushes aggregated
* metrics on a regular interval.
*
* @author Jon Schneider
* @author Andy Wilkinson
*/
public abstract class StepRegistryProperties {
/**
* Step size (i.e. reporting frequency) to use.
*/
private Duration step = Duration.ofMinutes(1);
/**
* Whether exporting of metrics to this backend is enabled.
*/
private boolean enabled = true;
/**
* Connection timeout for requests to this backend.
*/
private Duration connectTimeout = Duration.ofSeconds(1);
/**
* Read timeout for requests to this backend.
*/
private Duration readTimeout = Duration.ofSeconds(10);
/**
* Number of threads to use with the metrics publishing scheduler.
*/
private Integer numThreads = 2;
/**
* Number of measurements per request to use for this backend. If more measurements
* are found, then multiple requests will be made.
*/
private Integer batchSize = 10000;
public Duration getStep() {
return this.step;
}
public void setStep(Duration step) {
this.step = step;
}
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Duration getConnectTimeout() {
return this.connectTimeout;
}
public void setConnectTimeout(Duration connectTimeout) {
this.connectTimeout = connectTimeout;
}
public Duration getReadTimeout() {
return this.readTimeout;
}
public void setReadTimeout(Duration readTimeout) {
this.readTimeout = readTimeout;
}
public Integer getNumThreads() {
return this.numThreads;
}
public void setNumThreads(Integer numThreads) {
this.numThreads = numThreads;
}
public Integer getBatchSize() {
return this.batchSize;
}
public void setBatchSize(Integer batchSize) {
this.batchSize = batchSize;
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/autoconfigure/export
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/autoconfigure/export/properties/StepRegistryPropertiesConfigAdapter.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure.export.properties;
import io.micrometer.core.instrument.step.StepRegistryConfig;
import java.time.Duration;
/**
* Base class for {@link StepRegistryProperties} to {@link StepRegistryConfig} adapters.
*
* @param <T> The properties type
* @author Jon Schneider
* @author Phillip Webb
*/
public abstract class StepRegistryPropertiesConfigAdapter<T extends StepRegistryProperties>
extends PropertiesConfigAdapter<T> implements StepRegistryConfig {
public StepRegistryPropertiesConfigAdapter(T properties) {
super(properties);
}
@Override
public String prefix() {
return null;
}
@Override
public String get(String key) {
return null;
}
@Override
public Duration step() {
return get(T::getStep, StepRegistryConfig.super::step);
}
@Override
public boolean enabled() {
return get(T::isEnabled, StepRegistryConfig.super::enabled);
}
@Override
public Duration connectTimeout() {
return get(T::getConnectTimeout, StepRegistryConfig.super::connectTimeout);
}
@Override
public Duration readTimeout() {
return get(T::getReadTimeout, StepRegistryConfig.super::readTimeout);
}
@Override
public int numThreads() {
return get(T::getNumThreads, StepRegistryConfig.super::numThreads);
}
@Override
public int batchSize() {
return get(T::getBatchSize, StepRegistryConfig.super::batchSize);
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/web
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/web/servlet/DefaultWebMvcTagsProvider.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.web.servlet;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.lang.NonNullApi;
import io.micrometer.core.lang.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
/**
* Default implementation of {@link WebMvcTagsProvider}.
*
* @author Jon Schneider
*/
@NonNullApi
public class DefaultWebMvcTagsProvider implements WebMvcTagsProvider {
/**
* Supplies default tags to long task timers.
*
* @param request The HTTP request.
* @param handler The request method that is responsible for handling the request.
* @return A set of tags added to every Spring MVC HTTP request
*/
@Override
public Iterable<Tag> httpLongRequestTags(@Nullable HttpServletRequest request, @Nullable Object handler) {
return Arrays.asList(WebMvcTags.method(request), WebMvcTags.uri(request, null));
}
/**
* Supplies default tags to the Web MVC server programming model.
*
* @param request The HTTP request.
* @param response The HTTP response.
* @param ex The current exception, if any
* @return A set of tags added to every Spring MVC HTTP request.
*/
@Override
public Iterable<Tag> httpRequestTags(@Nullable HttpServletRequest request,
@Nullable HttpServletResponse response,
@Nullable Object handler,
@Nullable Throwable ex) {
return Arrays.asList(WebMvcTags.method(request), WebMvcTags.uri(request, response),
WebMvcTags.exception(ex), WebMvcTags.status(response));
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/web
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/web/servlet/HandlerMappingIntrospector.java
|
/**
* Licensed to the Foremast 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.web.servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
/**
* Helper class to get information from the {@code HandlerMapping} that would
* serve a specific request.
*
* <p>Provides the following methods:
* <ul>
* <li>{@link #getHandlerExecutionChain} — obtain a {@code HandlerMapping}
* to check request-matching criteria against.
* <li>{@link #getCorsConfiguration} — obtain the CORS configuration for the
* request.
* </ul>
*
* @author Rossen Stoyanchev
* @since 4.3.1
*/
public class HandlerMappingIntrospector implements ApplicationContextAware, InitializingBean {
private ApplicationContext applicationContext;
private List<HandlerMapping> handlerMappings;
/**
* Constructor for use with {@link ApplicationContextAware}.
*/
public HandlerMappingIntrospector() {
}
/**
* Constructor that detects the configured {@code HandlerMapping}s in the
* given {@code ApplicationContext} or falls back on
* "DispatcherServlet.properties" like the {@code DispatcherServlet}.
* @deprecated as of 4.3.12, in favor of {@link #setApplicationContext}
*/
public HandlerMappingIntrospector(ApplicationContext context) {
this.handlerMappings = initHandlerMappings(context);
}
/**
* Return the configured HandlerMapping's.
*/
public List<HandlerMapping> getHandlerMappings() {
return (this.handlerMappings != null ? this.handlerMappings : Collections.emptyList());
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public void afterPropertiesSet() {
if (this.handlerMappings == null) {
Assert.notNull(this.applicationContext, "No ApplicationContext");
this.handlerMappings = initHandlerMappings(this.applicationContext);
}
}
/**
* Find the {@link HandlerMapping} that would handle the given request and
* return it as a {@link MatchableHandlerMapping} that can be used to test
* request-matching criteria.
* <p>If the matching HandlerMapping is not an instance of
* {@link MatchableHandlerMapping}, an IllegalStateException is raised.
* @param request the current request
* @return the resolved matcher, or {@code null}
* @throws Exception if any of the HandlerMapping's raise an exception
*/
public HandlerExecutionChain getHandlerExecutionChain(HttpServletRequest request) throws Exception {
Assert.notNull(this.handlerMappings, "Handler mappings not initialized");
HttpServletRequest wrapper = new RequestAttributeChangeIgnoringWrapper(request);
for (HandlerMapping handlerMapping : this.handlerMappings) {
Object handler = handlerMapping.getHandler(wrapper);
if (handler == null) {
continue;
}
if (handler instanceof HandlerExecutionChain) {
return (HandlerExecutionChain)handler;
}
throw new IllegalStateException("HandlerMapping is not a MatchableHandlerMapping");
}
return null;
}
// @Override
// public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
// Assert.notNull(this.handlerMappings, "Handler mappings not initialized");
// HttpServletRequest wrapper = new RequestAttributeChangeIgnoringWrapper(request);
// for (HandlerMapping handlerMapping : this.handlerMappings) {
// HandlerExecutionChain handler = null;
// try {
// handler = handlerMapping.getHandler(wrapper);
// }
// catch (Exception ex) {
// // Ignore
// }
// if (handler == null) {
// continue;
// }
// if (handler.getInterceptors() != null) {
// for (HandlerInterceptor interceptor : handler.getInterceptors()) {
// if (interceptor instanceof CorsConfigurationSource) {
// return ((CorsConfigurationSource) interceptor).getCorsConfiguration(wrapper);
// }
// }
// }
// if (handler.getHandler() instanceof CorsConfigurationSource) {
// return ((CorsConfigurationSource) handler.getHandler()).getCorsConfiguration(wrapper);
// }
// }
// return null;
// }
private static List<HandlerMapping> initHandlerMappings(ApplicationContext applicationContext) {
Map<String, HandlerMapping> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
applicationContext, HandlerMapping.class, true, false);
if (!beans.isEmpty()) {
List<HandlerMapping> mappings = new ArrayList<>(beans.values());
AnnotationAwareOrderComparator.sort(mappings);
return Collections.unmodifiableList(mappings);
}
return Collections.unmodifiableList(initFallback(applicationContext));
}
private static List<HandlerMapping> initFallback(ApplicationContext applicationContext) {
Properties props;
String path = "DispatcherServlet.properties";
try {
Resource resource = new ClassPathResource(path, DispatcherServlet.class);
props = PropertiesLoaderUtils.loadProperties(resource);
}
catch (IOException ex) {
throw new IllegalStateException("Could not load '" + path + "': " + ex.getMessage());
}
String value = props.getProperty(HandlerMapping.class.getName());
String[] names = StringUtils.commaDelimitedListToStringArray(value);
List<HandlerMapping> result = new ArrayList<>(names.length);
for (String name : names) {
try {
Class<?> clazz = ClassUtils.forName(name, DispatcherServlet.class.getClassLoader());
Object mapping = applicationContext.getAutowireCapableBeanFactory().createBean(clazz);
result.add((HandlerMapping) mapping);
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException("Could not find default HandlerMapping [" + name + "]");
}
}
return result;
}
/**
* Request wrapper that ignores request attribute changes.
*/
private static class RequestAttributeChangeIgnoringWrapper extends HttpServletRequestWrapper {
public RequestAttributeChangeIgnoringWrapper(HttpServletRequest request) {
super(request);
}
@Override
public void setAttribute(String name, Object value) {
// Ignore attribute change...
}
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/web
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/web/servlet/MatchableHandlerMapping.java
|
/**
* Licensed to the Foremast 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.web.servlet;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.servlet.HandlerMapping;
/**
* Additional interface that a {@link HandlerMapping} can implement to expose
* a request matching API aligned with its internal request matching
* configuration and implementation.
*
* @author Rossen Stoyanchev
* @since 4.3.1
* @see HandlerMappingIntrospector
*/
public interface MatchableHandlerMapping extends HandlerMapping {
/**
* Determine whether the given request matches the request criteria.
* @param request the current request
* @param pattern the pattern to match
* @return the result from request matching, or {@code null} if none
*/
RequestMatchResult match(HttpServletRequest request, String pattern);
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/web
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/web/servlet/MetricsServletResponse.java
|
/**
* Licensed to the Foremast 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.web.servlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;
/**
* Wrapper for servlet response to get the status in servlet 2.5
*
* @author Sheldon Shao
* @version 1.0
*/
public class MetricsServletResponse extends HttpServletResponseWrapper {
private int status = 200;
public MetricsServletResponse(HttpServletResponse response) {
super(response);
}
public void sendError(int sc, String msg) throws IOException {
this.status = sc;
super.sendError(sc, msg);
}
public void sendError(int sc) throws IOException {
this.status = sc;
super.sendError(sc);
}
/**
* Get the HTTP status code for this Response.
*
* @return The HTTP status code for this Response
*
* @since Servlet 3.0
*/
public int getStatus(){
return status;
}
public void setStatus(int sc) {
this.status = sc;
super.setStatus(sc);
}
public void setStatus(int sc, String sm) {
this.status = sc;
super.setStatus(sc, sm);
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/web
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/web/servlet/PrometheusServlet.java
|
/**
* Licensed to the Foremast 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.web.servlet;
import ai.foremast.metrics.k8s.starter.CommonMetricsFilter;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.exporter.common.TextFormat;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.StringWriter;
/**
* Prometheus Controller
* @author Sheldon Shao
* @version 1.0
*/
public class PrometheusServlet extends HttpServlet {
private CollectorRegistry collectorRegistry;
private CommonMetricsFilter commonMetricsFilter;
public void init(ServletConfig config) throws ServletException {
super.init(config);
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
this.setCollectorRegistry(ctx.getBean(CollectorRegistry.class));
this.setCommonMetricsFilter(ctx.getBean(CommonMetricsFilter.class));
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("action");
if (getCommonMetricsFilter() != null && getCommonMetricsFilter().isActionEnabled() && action != null) {
String metricName = req.getParameter("metric");
if ("enable".equalsIgnoreCase(action)) {
getCommonMetricsFilter().enableMetric(metricName);
}
else if ("disable".equalsIgnoreCase(action)) {
getCommonMetricsFilter().disableMetric(metricName);
}
resp.getWriter().write("OK");
return;
}
try {
StringWriter writer = new StringWriter();
TextFormat.write004(writer, getCollectorRegistry().metricFamilySamples());
resp.setContentType(TextFormat.CONTENT_TYPE_004);
resp.getWriter().write(writer.toString());
} catch (IOException e) {
// This actually never happens since StringWriter::write() doesn't throw any IOException
throw new RuntimeException("Writing metrics failed", e);
}
}
public CollectorRegistry getCollectorRegistry() {
return collectorRegistry;
}
public void setCollectorRegistry(CollectorRegistry collectorRegistry) {
this.collectorRegistry = collectorRegistry;
}
public CommonMetricsFilter getCommonMetricsFilter() {
return commonMetricsFilter;
}
public void setCommonMetricsFilter(CommonMetricsFilter commonMetricsFilter) {
this.commonMetricsFilter = commonMetricsFilter;
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/web
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/web/servlet/RequestMatchResult.java
|
/**
* Licensed to the Foremast 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.web.servlet;
import java.util.Map;
import org.springframework.util.Assert;
import org.springframework.util.PathMatcher;
/**
* Container for the result from request pattern matching via
* {@link MatchableHandlerMapping} with a method to further extract
* URI template variables from the pattern.
*
* @author Rossen Stoyanchev
* @since 4.3.1
*/
public class RequestMatchResult {
private final String matchingPattern;
private final String lookupPath;
private final PathMatcher pathMatcher;
/**
* Create an instance with a matching pattern.
* @param matchingPattern the matching pattern, possibly not the same as the
* input pattern, e.g. inputPattern="/foo" and matchingPattern="/foo/".
* @param lookupPath the lookup path extracted from the request
* @param pathMatcher the PathMatcher used
*/
public RequestMatchResult(String matchingPattern, String lookupPath, PathMatcher pathMatcher) {
Assert.hasText(matchingPattern, "'matchingPattern' is required");
Assert.hasText(lookupPath, "'lookupPath' is required");
Assert.notNull(pathMatcher, "'pathMatcher' is required");
this.matchingPattern = matchingPattern;
this.lookupPath = lookupPath;
this.pathMatcher = pathMatcher;
}
/**
* Extract URI template variables from the matching pattern as defined in
* {@link PathMatcher#extractUriTemplateVariables}.
* @return a map with URI template variables
*/
public Map<String, String> extractUriTemplateVariables() {
return this.pathMatcher.extractUriTemplateVariables(this.matchingPattern, this.lookupPath);
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/web
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/web/servlet/WebMvcMetricsFilter.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.web.servlet;
import ai.foremast.micrometer.autoconfigure.MetricsProperties;
import io.micrometer.core.annotation.Timed;
import io.micrometer.core.instrument.Clock;
import io.micrometer.core.instrument.LongTaskTimer;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import ai.foremast.micrometer.TimedUtils;
import io.micrometer.core.instrument.binder.jvm.ClassLoaderMetrics;
import io.micrometer.core.instrument.binder.jvm.JvmGcMetrics;
import io.micrometer.core.instrument.binder.jvm.JvmMemoryMetrics;
import io.micrometer.core.instrument.binder.jvm.JvmThreadMetrics;
import io.micrometer.core.instrument.binder.system.FileDescriptorMetrics;
import io.micrometer.core.instrument.binder.system.ProcessorMetrics;
import io.micrometer.core.instrument.binder.system.UptimeMetrics;
import io.micrometer.core.instrument.binder.tomcat.TomcatMetrics;
import io.micrometer.core.instrument.composite.CompositeMeterRegistry;
import io.micrometer.prometheus.PrometheusConfig;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import io.prometheus.client.CollectorRegistry;
import org.apache.catalina.Manager;
import org.apache.catalina.core.ApplicationContext;
import org.apache.catalina.core.ApplicationContextFacade;
import org.apache.catalina.core.StandardContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.util.NestedServletException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Intercepts incoming HTTP requests and records metrics about execution time and results.
*
* @author Jon Schneider
*/
public class WebMvcMetricsFilter implements Filter {
private static final String TIMING_SAMPLE = "micrometer.timingSample";
private static final Log logger = LogFactory.getLog(WebMvcMetricsFilter.class);
private MeterRegistry registry;
private CollectorRegistry collectorRegistry;
private MetricsProperties metricsProperties;
private WebMvcTagsProvider tagsProvider = new DefaultWebMvcTagsProvider();
private String metricName;
private boolean autoTimeRequests;
private HandlerMappingIntrospector mappingIntrospector;
private boolean exposePrometheus = false;
private String prometheusPath = "/actuator/prometheus";
private PrometheusServlet prometheusServlet;
private TomcatMetrics tomcatMetrics;
private void record(TimingSampleContext timingContext, HttpServletResponse response, HttpServletRequest request,
Object handlerObject, Throwable e) {
for (Timed timedAnnotation : timingContext.timedAnnotations) {
timingContext.timerSample.stop(Timer.builder(timedAnnotation, metricName)
.tags(tagsProvider.httpRequestTags(request, response, handlerObject, e))
.register(registry));
}
if (timingContext.timedAnnotations.isEmpty() && autoTimeRequests) {
timingContext.timerSample.stop(Timer.builder(metricName)
.tags(tagsProvider.httpRequestTags(request, response, handlerObject, e))
.register(registry));
}
for (LongTaskTimer.Sample sample : timingContext.longTaskTimerSamples) {
sample.stop();
}
}
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext());
this.metricsProperties = ctx.getBean(MetricsProperties.class);
if (this.metricsProperties.isUseGlobalRegistry()) {
this.registry = ctx.getBean(MeterRegistry.class);
} else {
PrometheusMeterRegistry registry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
this.collectorRegistry = registry.getPrometheusRegistry();
this.registry = registry;
}
this.metricName = metricsProperties.getWeb().getServer().getRequestsMetricName();
this.autoTimeRequests = metricsProperties.getWeb().getServer().isAutoTimeRequests();
this.mappingIntrospector = new HandlerMappingIntrospector(ctx);
String path = filterConfig.getInitParameter("prometheus-path");
if (path != null) {
exposePrometheus = true;
this.prometheusPath = path;
}
if (exposePrometheus) {
prometheusServlet = new PrometheusServlet();
prometheusServlet.init(new ServletConfig() {
@Override
public String getServletName() {
return "prometheus";
}
@Override
public ServletContext getServletContext() {
return filterConfig.getServletContext();
}
@Override
public String getInitParameter(String s) {
return filterConfig.getInitParameter(s);
}
@Override
public Enumeration getInitParameterNames() {
return filterConfig.getInitParameterNames();
}
});
if (collectorRegistry != null) {
prometheusServlet.setCollectorRegistry(collectorRegistry);
registry.config().meterFilter(prometheusServlet.getCommonMetricsFilter());
}
}
//Tomcat
try {
Manager manager = getManager(filterConfig.getServletContext());
tomcatMetrics = new TomcatMetrics(manager, Collections.emptyList());
tomcatMetrics.bindTo(this.registry);
}
catch(Throwable tx) {
tx.printStackTrace();
}
new UptimeMetrics().bindTo(this.registry);
new ProcessorMetrics().bindTo(this.registry);
new FileDescriptorMetrics().bindTo(this.registry);
new JvmGcMetrics().bindTo(this.registry);
new JvmMemoryMetrics().bindTo(this.registry);
new JvmThreadMetrics().bindTo(this.registry);
new ClassLoaderMetrics().bindTo(this.registry);
}
/**
* Return Tomcat Manager
* @param servletContext
* @return
*/
private Manager getManager(ServletContext servletContext) {
try {
ApplicationContextFacade applicationContextFacade = (ApplicationContextFacade) servletContext;
Field applicationContextFacadeField = ApplicationContextFacade.class.getDeclaredField("context");
applicationContextFacadeField.setAccessible(true);
ApplicationContext appContext = (ApplicationContext) applicationContextFacadeField.get(applicationContextFacade);
Field applicationContextField = ApplicationContext.class.getDeclaredField("context");
applicationContextField.setAccessible(true);
StandardContext stdContext = (StandardContext) applicationContextField.get(appContext);
return stdContext.getManager();
} catch (Exception e) {
e.printStackTrace();
//skip this as we can also use Manager as null for metrics
//"Unable to get Catalina Manager. Cause: {}", e.getMessage() , e;
}
return null;
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)servletRequest;
HttpServletResponse response = (HttpServletResponse)servletResponse;
String path = request.getServletPath();
if (exposePrometheus && prometheusPath.equals(path)) { // Handle /actuator/prometheus URL in this filter
prometheusServlet.doGet(request, response);
return;
}
HandlerExecutionChain handler = null;
try {
handler = mappingIntrospector.getHandlerExecutionChain(request);
} catch (Exception e) {
logger.debug("Unable to time request", e);
filterChain.doFilter(request, response);
return;
}
final Object handlerObject = handler == null ? null : handler.getHandler();
// If this is the second invocation of the filter in an async request, we don't
// want to start sampling again (effectively bumping the active count on any long task timers).
// Rather, we'll just use the sampling context we started on the first invocation.
TimingSampleContext timingContext = (TimingSampleContext) request.getAttribute(TIMING_SAMPLE);
if (timingContext == null) {
timingContext = new TimingSampleContext(request, handlerObject);
}
MetricsServletResponse wrapper = new MetricsServletResponse(response);
try {
filterChain.doFilter(request, wrapper);
record(timingContext, wrapper, request,
handlerObject, (Throwable) request.getAttribute(EXCEPTION_ATTRIBUTE));
} catch (NestedServletException e) {
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
record(timingContext, response, request, handlerObject, e.getCause());
throw e;
}
}
public static final String EXCEPTION_ATTRIBUTE = DispatcherServlet.class.getName() + ".EXCEPTION";
@Override
public void destroy() {
}
private class TimingSampleContext {
private final Set<Timed> timedAnnotations;
private final Timer.Sample timerSample;
private final Collection<LongTaskTimer.Sample> longTaskTimerSamples;
TimingSampleContext(HttpServletRequest request, Object handlerObject) {
timedAnnotations = annotations(handlerObject);
timerSample = Timer.start(registry);
longTaskTimerSamples = timedAnnotations.stream()
.filter(Timed::longTask)
.map(t -> LongTaskTimer.builder(t)
.tags(tagsProvider.httpLongRequestTags(request, handlerObject))
.register(registry)
.start())
.collect(Collectors.toList());
}
private Set<Timed> annotations(Object handler) {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Set<Timed> timed = TimedUtils.findTimedAnnotations(handlerMethod.getMethod());
if (timed.isEmpty()) {
return TimedUtils.findTimedAnnotations(handlerMethod.getBeanType());
}
return timed;
}
return Collections.emptySet();
}
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/web
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/web/servlet/WebMvcTags.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.web.servlet;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.lang.NonNullApi;
import io.micrometer.core.lang.Nullable;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Factory methods for {@link Tag Tags} associated with a request-response exchange that
* is instrumented by {@link WebMvcMetricsFilter}.
*
* @author Jon Schneider
* @author Andy Wilkinson
* @author Michael McFadyen
*/
@NonNullApi
public final class WebMvcTags {
private static final Tag URI_NOT_FOUND = Tag.of("uri", "NOT_FOUND");
private static final Tag URI_REDIRECTION = Tag.of("uri", "REDIRECTION");
private static final Tag URI_ROOT = Tag.of("uri", "root");
private static final Tag URI_UNKNOWN = Tag.of("uri", "UNKNOWN");
private static final Tag EXCEPTION_NONE = Tag.of("exception", "None");
private static final Tag STATUS_UNKNOWN = Tag.of("status", "UNKNOWN");
private static final Tag METHOD_UNKNOWN = Tag.of("method", "UNKNOWN");
private WebMvcTags() {
}
/**
* Creates a {@code method} tag based on the {@link HttpServletRequest#getMethod()
* method} of the given {@code request}.
*
* @param request the request
* @return the method tag whose value is a capitalized method (e.g. GET).
*/
public static Tag method(@Nullable HttpServletRequest request) {
return request == null ? METHOD_UNKNOWN : Tag.of("method", request.getMethod());
}
/**
* Creates a {@code method} tag based on the status of the given {@code response}.
*
* @param response the HTTP response
* @return the status tag derived from the status of the response
*/
public static Tag status(@Nullable HttpServletResponse response) {
return response == null || !(response instanceof MetricsServletResponse) ? STATUS_UNKNOWN : Tag.of("status",
Integer.toString(((MetricsServletResponse)response).getStatus()));
}
/**
* Creates a {@code uri} tag based on the URI of the given {@code request}. Uses the
* {@link HandlerMapping#BEST_MATCHING_PATTERN_ATTRIBUTE} best matching pattern if
* available. Falling back to {@code REDIRECTION} for 3xx responses, {@code NOT_FOUND}
* for 404 responses, {@code root} for requests with no path info, and {@code UNKNOWN}
* for all other requests.
*
* @param request the request
* @param response the response
* @return the uri tag derived from the request
*/
public static Tag uri(@Nullable HttpServletRequest request, @Nullable HttpServletResponse response) {
if (request != null) {
String pattern = getMatchingPattern(request);
if (pattern != null) {
return Tag.of("uri", pattern);
} else if (response != null) {
HttpStatus status = extractStatus(response);
if (status != null && status.is3xxRedirection()) {
return URI_REDIRECTION;
}
if (status != null && status.equals(HttpStatus.NOT_FOUND)) {
return URI_NOT_FOUND;
}
}
String pathInfo = getPathInfo(request);
if (pathInfo.isEmpty()) {
return URI_ROOT;
}
}
return URI_UNKNOWN;
}
@Nullable
private static HttpStatus extractStatus(HttpServletResponse response) {
try {
if (response instanceof MetricsServletResponse) {
return HttpStatus.valueOf(((MetricsServletResponse)response).getStatus());
}
else {
return HttpStatus.OK;
}
} catch (IllegalArgumentException ex) {
return null;
}
}
@Nullable
private static String getMatchingPattern(HttpServletRequest request) {
return (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
}
private static String getPathInfo(HttpServletRequest request) {
String uri = StringUtils.hasText(request.getPathInfo()) ?
request.getPathInfo() : "/";
return uri.replaceAll("//+", "/")
.replaceAll("/$", "");
}
/**
* Creates a {@code exception} tag based on the {@link Class#getSimpleName() simple
* name} of the class of the given {@code exception}.
*
* @param exception the exception, may be {@code null}
* @return the exception tag derived from the exception
*/
public static Tag exception(@Nullable Throwable exception) {
if (exception == null) {
return EXCEPTION_NONE;
}
String simpleName = exception.getClass().getSimpleName();
return Tag.of("exception", simpleName.isEmpty() ? exception.getClass().getName() : simpleName);
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/web
|
java-sources/ai/foremast/metrics/foremast-spring-4x-k8s-metrics/0.2.0/ai/foremast/micrometer/web/servlet/WebMvcTagsProvider.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.web.servlet;
import io.micrometer.core.instrument.LongTaskTimer;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.lang.NonNull;
import io.micrometer.core.lang.NonNullApi;
import io.micrometer.core.lang.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Provides {@link Tag Tags} for Spring MVC-based request handling.
*
* @author Jon Schneider
* @author Andy Wilkinson
*/
@NonNullApi
public interface WebMvcTagsProvider {
/**
* Provides tags to be used by {@link LongTaskTimer long task timers}.
*
* @param request the HTTP request
* @param handler the handler for the request
* @return tags to associate with metrics recorded for the request
*/
@NonNull
Iterable<Tag> httpLongRequestTags(@Nullable HttpServletRequest request, @Nullable Object handler);
/**
* Provides tags to be associated with metrics for the given {@code request} and
* {@code response} exchange.
*
* @param request the request
* @param response the response
* @param handler the handler for the request
* @param ex the current exception, if any
* @return tags to associate with metrics for the request and response exchange
*/
@NonNull
Iterable<Tag> httpRequestTags(@Nullable HttpServletRequest request,
@Nullable HttpServletResponse response,
@Nullable Object handler,
@Nullable Throwable ex);
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-15x-starter/0.1.12/ai/foremast/metrics/k8s
|
java-sources/ai/foremast/metrics/foremast-spring-boot-15x-starter/0.1.12/ai/foremast/metrics/k8s/starter/CommonMetricsFilter.java
|
package ai.foremast.metrics.k8s.starter;
import io.micrometer.spring.autoconfigure.MetricsProperties;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.config.MeterFilter;
import io.micrometer.core.instrument.config.MeterFilterReply;
import org.springframework.util.StringUtils;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
/**
* Common Metrics Filter is to hide the metrics by default, and show the metrics what are in the whitelist.
*
* If the metric is enabled in properties, keep it enabled.
* If the metric is disabled in properties, keep it disabled.
* If the metric starts with "PREFIX", enable it. otherwise disable the metric
*
* @author Sheldon Shao
* @version 1.0
*/
public class CommonMetricsFilter implements MeterFilter {
private MetricsProperties properties;
private String[] prefixes = new String[] {};
private Set<String> whitelist = new HashSet<>();
private Set<String> blacklist = new HashSet<>();
private K8sMetricsProperties k8sMetricsProperties;
private boolean actionEnabled = false;
private LinkedHashMap<String, String> tagRules = new LinkedHashMap<>();
public CommonMetricsFilter(K8sMetricsProperties k8sMetricsProperties, MetricsProperties properties) {
this.properties = properties;
this.k8sMetricsProperties = k8sMetricsProperties;
this.actionEnabled = k8sMetricsProperties.isEnableCommonMetricsFilterAction();
String list = k8sMetricsProperties.getCommonMetricsBlacklist();
if (list != null && !list.isEmpty()) {
String[] array = StringUtils.tokenizeToStringArray(list, ",", true, true);
for(String str: array) {
str = filter(str.trim());
blacklist.add(str);
}
}
list = k8sMetricsProperties.getCommonMetricsWhitelist();
if (list != null && !list.isEmpty()) {
String[] array = StringUtils.tokenizeToStringArray(list, ",", true, true);
for(String str: array) {
str = filter(str.trim());
whitelist.add(str);
}
}
list = k8sMetricsProperties.getCommonMetricsPrefix();
if (list != null && !list.isEmpty()) {
prefixes = StringUtils.tokenizeToStringArray(list, ",", true, true);
}
String tagRuleExpressions = k8sMetricsProperties.getCommonMetricsTagRules();
if (tagRuleExpressions != null) {
String[] array = StringUtils.tokenizeToStringArray(tagRuleExpressions, ",", true, true);
for(String str: array) {
str = str.trim();
String[] nameAndValue = str.split(":");
if (nameAndValue == null || nameAndValue.length != 2) {
throw new IllegalStateException("Invalid common tag name value pair:" + str);
}
tagRules.put(nameAndValue[0].trim(), nameAndValue[1].trim());
}
}
}
/**
* Filter for "[PREFIX]_*"
*
* @param id
* @return MeterFilterReply
*/
public MeterFilterReply accept(Meter.Id id) {
if (!k8sMetricsProperties.isEnableCommonMetricsFilter()) {
return MeterFilter.super.accept(id);
}
String metricName = id.getName();
Boolean enabled = lookupWithFallbackToAll(this.properties.getEnable(), id, null);
if (enabled != null) {
return enabled ? MeterFilterReply.NEUTRAL : MeterFilterReply.DENY;
}
if (whitelist.contains(metricName)) {
return MeterFilterReply.NEUTRAL;
}
if (blacklist.contains(metricName)) {
return MeterFilterReply.DENY;
}
for(String prefix: prefixes) {
if (metricName.startsWith(prefix)) {
return MeterFilterReply.ACCEPT;
}
}
for(String key: tagRules.keySet()) {
String expectedValue = tagRules.get(key);
if (expectedValue != null) {
if (expectedValue.equals(id.getTag(key))) {
return MeterFilterReply.ACCEPT;
}
}
}
return MeterFilterReply.DENY;
}
protected String filter(String metricName) {
return metricName.replace('_', '.');
}
public void enableMetric(String metricName) {
if (k8sMetricsProperties.isEnableCommonMetricsFilterAction()) {
metricName = filter(metricName);
if (blacklist.contains(metricName)) {
blacklist.remove(metricName);
}
if (!whitelist.contains(metricName)) {
whitelist.add(metricName);
}
}
}
public void disableMetric(String metricName) {
if (k8sMetricsProperties.isEnableCommonMetricsFilterAction()) {
metricName = filter(metricName);
if (whitelist.contains(metricName)) {
whitelist.remove(metricName);
}
if (!blacklist.contains(metricName)) {
blacklist.add(metricName);
}
}
}
// private <T> T lookup(Map<String, T> values, Meter.Id id, T defaultValue) {
// if (values.isEmpty()) {
// return defaultValue;
// }
// return doLookup(values, id, () -> defaultValue);
// }
private <T> T lookupWithFallbackToAll(Map<String, T> values, Meter.Id id, T defaultValue) {
if (values.isEmpty()) {
return defaultValue;
}
return doLookup(values, id, () -> values.getOrDefault("all", defaultValue));
}
private <T> T doLookup(Map<String, T> values, Meter.Id id, Supplier<T> defaultValue) {
String name = id.getName();
while (name != null && !name.isEmpty()) {
T result = values.get(name);
if (result != null) {
return result;
}
int lastDot = name.lastIndexOf('.');
name = (lastDot != -1) ? name.substring(0, lastDot) : "";
}
return defaultValue.get();
}
public String[] getPrefixes() {
return prefixes;
}
public void setPrefixes(String[] prefixes) {
this.prefixes = prefixes;
}
public boolean isActionEnabled() {
return actionEnabled;
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-15x-starter/0.1.12/ai/foremast/metrics/k8s
|
java-sources/ai/foremast/metrics/foremast-spring-boot-15x-starter/0.1.12/ai/foremast/metrics/k8s/starter/K8sMetricsAutoConfiguration.java
|
package ai.foremast.metrics.k8s.starter;
import io.micrometer.spring.autoconfigure.MeterRegistryCustomizer;
import io.micrometer.spring.autoconfigure.MetricsProperties;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.regex.Pattern;
/**
* Auto metrics configurations
*/
@Configuration
@EnableConfigurationProperties({K8sMetricsProperties.class, MetricsProperties.class})
public class K8sMetricsAutoConfiguration implements MeterRegistryCustomizer {
@Autowired
K8sMetricsProperties metricsProperties;
@Autowired
ConfigurableApplicationContext appContext;
private static final String HTTP_SERVER_REQUESTS = "http.server.requests";
@Bean
public CommonMetricsFilter commonMetricsFilter(MetricsProperties properties) {
return new CommonMetricsFilter(metricsProperties, properties);
}
@Override
public void customize(MeterRegistry registry) {
String commonTagNameValuePair = metricsProperties.getCommonTagNameValuePairs();
if (commonTagNameValuePair != null && !commonTagNameValuePair.isEmpty()) {
String[] pairs = commonTagNameValuePair.split(",");
for(String p : pairs) {
String[] nameAndValue = p.split(":");
if (nameAndValue == null || nameAndValue.length != 2) {
throw new IllegalStateException("Invalid common tag name value pair:" + p);
}
String valuePattern = nameAndValue[1];
int sepIndex = valuePattern.indexOf('|');
String[] patterns = null;
if (sepIndex > 0) {
patterns = valuePattern.split(Pattern.quote("|"));
}
else {
patterns = new String[] { valuePattern };
}
for(int i = 0; i < patterns.length; i ++) {
String value = null;
if (patterns[i].startsWith("ENV.")) {
value = System.getenv(patterns[i].substring(4));
}
else {
value = System.getProperty(patterns[i]);
if ((value == null || value.isEmpty()) && appContext != null) {
value = appContext.getEnvironment().getProperty(patterns[i]);
}
}
if (value != null && !value.isEmpty()) {
registry.config().commonTags(nameAndValue[0], value);
break;
}
}
}
}
String statuses = metricsProperties.getInitializeForStatuses();
if (statuses != null || !statuses.isEmpty()) {
String[] statusCodes = statuses.split(",");
for(String code: statusCodes) {
if (metricsProperties.hasCaller()) {
registry.timer(HTTP_SERVER_REQUESTS, "exception", "None", "method", "GET", "status", code, "uri", "/**", "caller", "*", "outcome", "SERVER_ERROR");
}
else {
registry.timer(HTTP_SERVER_REQUESTS, "exception", "None", "method", "GET", "status", code, "uri", "/**", "outcome", "SERVER_ERROR");
}
}
}
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/metrics/k8s
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/metrics/k8s/starter/ActuatorSecurityConfig.java
|
package ai.foremast.metrics.k8s.starter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@Order(101)
@EnableConfigurationProperties({K8sMetricsProperties.class})
@EnableWebSecurity
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private K8sMetricsProperties metricsProperties;
/*
This spring security configuration does the following
1. Allow access to the all APIs (/info /health /prometheus).
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
if (metricsProperties.isDisableCsrf()) { //For special use case
http.csrf().disable();
}
http.authorizeRequests()
.antMatchers("/actuator/info", "/actuator/health",
"/actuator/prometheus", "/metrics", "/prometheus")
.permitAll();
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/metrics/k8s
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/metrics/k8s/starter/CommonMetricsFilter.java
|
/**
* Licensed to the Foremast 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.metrics.k8s.starter;
import ai.foremast.micrometer.autoconfigure.MetricsProperties;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.config.MeterFilter;
import io.micrometer.core.instrument.config.MeterFilterReply;
import org.springframework.util.StringUtils;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
/**
* Common Metrics Filter is to hide the metrics by default, and show the metrics what are in the whitelist.
*
* If the metric is enabled in properties, keep it enabled.
* If the metric is disabled in properties, keep it disabled.
* If the metric starts with "PREFIX", enable it. otherwise disable the metric
*
* @author Sheldon Shao
* @version 1.0
*/
public class CommonMetricsFilter implements MeterFilter {
private MetricsProperties properties;
private String[] prefixes = new String[] {};
private Set<String> whitelist = new HashSet<>();
private Set<String> blacklist = new HashSet<>();
private K8sMetricsProperties k8sMetricsProperties;
private boolean actionEnabled = false;
private LinkedHashMap<String, String> tagRules = new LinkedHashMap<>();
public CommonMetricsFilter(K8sMetricsProperties k8sMetricsProperties, MetricsProperties properties) {
this.properties = properties;
this.k8sMetricsProperties = k8sMetricsProperties;
this.actionEnabled = k8sMetricsProperties.isEnableCommonMetricsFilterAction();
String list = k8sMetricsProperties.getCommonMetricsBlacklist();
if (list != null && !list.isEmpty()) {
String[] array = StringUtils.tokenizeToStringArray(list, ",", true, true);
for(String str: array) {
str = filter(str.trim());
blacklist.add(str);
}
}
list = k8sMetricsProperties.getCommonMetricsWhitelist();
if (list != null && !list.isEmpty()) {
String[] array = StringUtils.tokenizeToStringArray(list, ",", true, true);
for(String str: array) {
str = filter(str.trim());
whitelist.add(str);
}
}
list = k8sMetricsProperties.getCommonMetricsPrefix();
if (list != null && !list.isEmpty()) {
prefixes = StringUtils.tokenizeToStringArray(list, ",", true, true);
}
String tagRuleExpressions = k8sMetricsProperties.getCommonMetricsTagRules();
if (tagRuleExpressions != null) {
String[] array = StringUtils.tokenizeToStringArray(tagRuleExpressions, ",", true, true);
for(String str: array) {
str = str.trim();
String[] nameAndValue = str.split(":");
if (nameAndValue == null || nameAndValue.length != 2) {
throw new IllegalStateException("Invalid common tag name value pair:" + str);
}
tagRules.put(nameAndValue[0].trim(), nameAndValue[1].trim());
}
}
}
/**
* Filter for "[PREFIX]_*"
*
* @param id
* @return MeterFilterReply
*/
public MeterFilterReply accept(Meter.Id id) {
if (!k8sMetricsProperties.isEnableCommonMetricsFilter()) {
return MeterFilter.super.accept(id);
}
String metricName = id.getName();
Boolean enabled = lookupWithFallbackToAll(this.properties.getEnable(), id, null);
if (enabled != null) {
return enabled ? MeterFilterReply.NEUTRAL : MeterFilterReply.DENY;
}
if (whitelist.contains(metricName)) {
return MeterFilterReply.NEUTRAL;
}
if (blacklist.contains(metricName)) {
return MeterFilterReply.DENY;
}
for(String prefix: prefixes) {
if (metricName.startsWith(prefix)) {
return MeterFilterReply.ACCEPT;
}
}
for(String key: tagRules.keySet()) {
String expectedValue = tagRules.get(key);
if (expectedValue != null) {
if (expectedValue.equals(id.getTag(key))) {
return MeterFilterReply.ACCEPT;
}
}
}
return MeterFilterReply.DENY;
}
protected String filter(String metricName) {
return metricName.replace('_', '.');
}
public void enableMetric(String metricName) {
metricName = filter(metricName);
if (blacklist.contains(metricName)) {
blacklist.remove(metricName);
}
if (!whitelist.contains(metricName)) {
whitelist.add(metricName);
}
}
public void disableMetric(String metricName) {
metricName = filter(metricName);
if (whitelist.contains(metricName)) {
whitelist.remove(metricName);
}
if (!blacklist.contains(metricName)) {
blacklist.add(metricName);
}
}
private <T> T lookup(Map<String, T> values, Meter.Id id, T defaultValue) {
if (values.isEmpty()) {
return defaultValue;
}
return doLookup(values, id, () -> defaultValue);
}
private <T> T lookupWithFallbackToAll(Map<String, T> values, Meter.Id id, T defaultValue) {
if (values.isEmpty()) {
return defaultValue;
}
return doLookup(values, id, () -> values.getOrDefault("all", defaultValue));
}
private <T> T doLookup(Map<String, T> values, Meter.Id id, Supplier<T> defaultValue) {
String name = id.getName();
while (name != null && !name.isEmpty()) {
T result = values.get(name);
if (result != null) {
return result;
}
int lastDot = name.lastIndexOf('.');
name = (lastDot != -1) ? name.substring(0, lastDot) : "";
}
return defaultValue.get();
}
public String[] getPrefixes() {
return prefixes;
}
public void setPrefixes(String[] prefixes) {
this.prefixes = prefixes;
}
public boolean isActionEnabled() {
return actionEnabled;
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/metrics/k8s
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/metrics/k8s/starter/K8sMetricsAutoConfiguration.java
|
package ai.foremast.metrics.k8s.starter;
import ai.foremast.micrometer.autoconfigure.MeterRegistryCustomizer;
import ai.foremast.micrometer.autoconfigure.MetricsProperties;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.regex.Pattern;
/**
* Auto metrics configurations
*/
@Configuration
@EnableConfigurationProperties({K8sMetricsProperties.class, MetricsProperties.class})
public class K8sMetricsAutoConfiguration implements MeterRegistryCustomizer {
@Autowired
K8sMetricsProperties metricsProperties;
@Autowired
ConfigurableApplicationContext appContext;
private static final String HTTP_SERVER_REQUESTS = "http.server.requests";
@Bean
public CommonMetricsFilter commonMetricsFilter(MetricsProperties properties) {
return new CommonMetricsFilter(metricsProperties, properties);
}
@Override
public void customize(MeterRegistry registry) {
String commonTagNameValuePair = metricsProperties.getCommonTagNameValuePairs();
if (commonTagNameValuePair != null && !commonTagNameValuePair.isEmpty()) {
String[] pairs = commonTagNameValuePair.split(",");
for(String p : pairs) {
String[] nameAndValue = p.split(":");
if (nameAndValue == null || nameAndValue.length != 2) {
throw new IllegalStateException("Invalid common tag name value pair:" + p);
}
String valuePattern = nameAndValue[1];
int sepIndex = valuePattern.indexOf('|');
String[] patterns = null;
if (sepIndex > 0) {
patterns = valuePattern.split(Pattern.quote("|"));
}
else {
patterns = new String[] { valuePattern };
}
for(int i = 0; i < patterns.length; i ++) {
String value = null;
if (patterns[i].startsWith("ENV.")) {
value = System.getenv(patterns[i].substring(4));
}
else {
value = System.getProperty(patterns[i]);
if ((value == null || value.isEmpty()) && appContext != null) {
value = appContext.getEnvironment().getProperty(patterns[i]);
}
}
if (value != null && !value.isEmpty()) {
registry.config().commonTags(nameAndValue[0], value);
break;
}
}
}
}
String statuses = metricsProperties.getInitializeForStatuses();
if (statuses != null || !statuses.isEmpty()) {
String[] statusCodes = statuses.split(",");
for(String code: statusCodes) {
if (metricsProperties.hasCaller()) {
registry.timer(HTTP_SERVER_REQUESTS, "exception", "None", "method", "GET", "status", code, "uri", "/**", "caller", "*");
}
else {
registry.timer(HTTP_SERVER_REQUESTS, "exception", "None", "method", "GET", "status", code, "uri", "/**");
}
}
}
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/metrics/k8s
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/metrics/k8s/starter/K8sMetricsFilter.java
|
package ai.foremast.metrics.k8s.starter;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* K8s use /metrics and prometheus format metrics description by default
* So "/metrics" needs to be pointed to "/actuator/prometheus"
*/
public class K8sMetricsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
if (servletResponse instanceof HttpServletResponse) {
HttpServletResponse response = (HttpServletResponse)servletResponse;
response.sendRedirect("/prometheus");
}
else {
filterChain.doFilter(servletRequest, servletResponse);
}
}
@Override
public void destroy() {
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/metrics/k8s
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/metrics/k8s/starter/K8sMetricsProperties.java
|
package ai.foremast.metrics.k8s.starter;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "k8s.metrics")
public class K8sMetricsProperties {
private String commonTagNameValuePairs = "app:ENV.APP_NAME|info.app.name";
private String initializeForStatuses = "403,404,501,502";
public static final String APP_ASSET_ALIAS_HEADER = "X-CALLER";
private String callerHeader = APP_ASSET_ALIAS_HEADER;
private boolean disableCsrf = false;
private boolean enableCommonMetricsFilter = false;
private String commonMetricsWhitelist = null;
private String commonMetricsBlacklist = null;
private String commonMetricsPrefix = null;
private boolean enableCommonMetricsFilterAction = false;
private String commonMetricsTagRules = null;
public boolean isEnableCommonMetricsFilter() {
return enableCommonMetricsFilter;
}
public void setEnableCommonMetricsFilter(boolean enableCommonMetricsFilter) {
this.enableCommonMetricsFilter = enableCommonMetricsFilter;
}
public String getCommonMetricsWhitelist() {
return commonMetricsWhitelist;
}
public void setCommonMetricsWhitelist(String commonMetricsWhitelist) {
this.commonMetricsWhitelist = commonMetricsWhitelist;
}
public String getCommonMetricsBlacklist() {
return commonMetricsBlacklist;
}
public void setCommonMetricsBlacklist(String commonMetricsBlacklist) {
this.commonMetricsBlacklist = commonMetricsBlacklist;
}
public String getCommonMetricsPrefix() {
return commonMetricsPrefix;
}
public void setCommonMetricsPrefix(String commonMetricsPrefix) {
this.commonMetricsPrefix = commonMetricsPrefix;
}
public boolean isEnableCommonMetricsFilterAction() {
return enableCommonMetricsFilterAction;
}
public void setEnableCommonMetricsFilterAction(boolean enableCommonMetricsFilterAction) {
this.enableCommonMetricsFilterAction = enableCommonMetricsFilterAction;
}
public String getInitializeForStatuses() {
return initializeForStatuses;
}
public void setInitializeForStatuses(String initializeForStatuses) {
this.initializeForStatuses = initializeForStatuses;
}
public String getCommonTagNameValuePairs() {
return commonTagNameValuePairs;
}
public void setCommonTagNameValuePairs(String commonTagNameValuePairs) {
this.commonTagNameValuePairs = commonTagNameValuePairs;
}
public String getCallerHeader() {
return callerHeader;
}
public boolean hasCaller() {
return callerHeader != null && !callerHeader.isEmpty();
}
public void setCallerHeader(String callerHeader) {
this.callerHeader = callerHeader;
}
public boolean isDisableCsrf() {
return disableCsrf;
}
public void setDisableCsrf(boolean disableCsrf) {
this.disableCsrf = disableCsrf;
}
public String getCommonMetricsTagRules() {
return commonMetricsTagRules;
}
public void setCommonMetricsTagRules(String commonMetricsTagRules) {
this.commonMetricsTagRules = commonMetricsTagRules;
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/TimedUtils.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer;
import io.micrometer.core.annotation.Timed;
import io.micrometer.core.annotation.TimedSet;
import org.springframework.core.annotation.AnnotationUtils;
import java.lang.reflect.AnnotatedElement;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
public final class TimedUtils {
private TimedUtils() {
}
public static Set<Timed> findTimedAnnotations(AnnotatedElement element) {
Timed t = AnnotationUtils.findAnnotation(element, Timed.class);
//noinspection ConstantConditions
if (t != null)
return Collections.singleton(t);
TimedSet ts = AnnotationUtils.findAnnotation(element, TimedSet.class);
if (ts != null) {
return Arrays.stream(ts.value()).collect(Collectors.toSet());
}
return Collections.emptySet();
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/CompositeMeterRegistryAutoConfiguration.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure;
import io.micrometer.core.instrument.composite.CompositeMeterRegistry;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Import;
/**
* {@link EnableAutoConfiguration Auto-configuration} for a
* {@link CompositeMeterRegistry}.
*
* @author Andy Wilkinson
*/
@Import({ NoOpMeterRegistryConfiguration.class,
CompositeMeterRegistryConfiguration.class })
@ConditionalOnClass(CompositeMeterRegistry.class)
public class CompositeMeterRegistryAutoConfiguration {
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/CompositeMeterRegistryConfiguration.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure;
import io.micrometer.core.instrument.Clock;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.composite.CompositeMeterRegistry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.boot.autoconfigure.condition.NoneNestedConditions;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Primary;
import java.util.List;
/**
* Configuration for a {@link CompositeMeterRegistry}.
*
* @author Andy Wilkinson
*/
@Conditional(CompositeMeterRegistryConfiguration.MultipleNonPrimaryMeterRegistriesCondition.class)
class CompositeMeterRegistryConfiguration {
@Bean
@Primary
public CompositeMeterRegistry compositeMeterRegistry(Clock clock, List<MeterRegistry> registries) {
return new CompositeMeterRegistry(clock, registries);
}
static class MultipleNonPrimaryMeterRegistriesCondition extends NoneNestedConditions {
MultipleNonPrimaryMeterRegistriesCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnMissingBean(MeterRegistry.class)
static class NoMeterRegistryCondition {
}
@ConditionalOnSingleCandidate(MeterRegistry.class)
static class SingleInjectableMeterRegistry {
}
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/MeterRegistryPostProcessor.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.MeterBinder;
import io.micrometer.core.instrument.config.MeterFilter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.config.BeanPostProcessor;
import java.util.*;
/**
* {@link BeanPostProcessor} that delegates to a lazily created
* {@link MeterRegistryConfigurer} to post-process {@link MeterRegistry} beans.
*
* @author Jon Schneider
* @author Phillip Webb
* @author Andy Wilkinson
*/
class MeterRegistryPostProcessor implements BeanPostProcessor, BeanFactoryAware {
// private final ObjectProvider<List<MeterBinder>> meterBinders;
//
// private final ObjectProvider<List<MeterFilter>> meterFilters;
//
// private final ObjectProvider<List<MeterRegistryCustomizer<?>>> meterRegistryCustomizers;
//
// private final ObjectProvider<MetricsProperties> metricsProperties;
private BeanFactory beanFactory;
private volatile MeterRegistryConfigurer configurer;
// MeterRegistryPostProcessor(
// ObjectProvider<List<MeterBinder>> meterBinders,
// ObjectProvider<List<MeterFilter>> meterFilters,
// ObjectProvider<List<MeterRegistryCustomizer<?>>> meterRegistryCustomizers,
// ObjectProvider<MetricsProperties> metricsProperties) {
// this.meterBinders = meterBinders;
// this.meterFilters = meterFilters;
// this.meterRegistryCustomizers = meterRegistryCustomizers;
// this.metricsProperties = metricsProperties;
// }
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof MeterRegistry) {
getConfigurer().configure((MeterRegistry) bean);
}
return bean;
}
private MeterRegistryConfigurer getConfigurer() {
if (this.configurer == null) {
Collection<MeterBinder> meterBinders = Collections.emptyList();
Collection<MeterFilter> meterFilters = Collections.emptyList();
Collection<MeterRegistryCustomizer<?>> meterRegistryCustomizers = Collections.emptyList();
MetricsProperties properties = beanFactory.getBean(MetricsProperties.class);
if (beanFactory instanceof ListableBeanFactory) {
ListableBeanFactory listableBeanFactory = (ListableBeanFactory)beanFactory;
meterBinders = listableBeanFactory.getBeansOfType(MeterBinder.class).values();
meterFilters = listableBeanFactory.getBeansOfType(MeterFilter.class).values();
Map<String, MeterRegistryCustomizer> map = listableBeanFactory.getBeansOfType(MeterRegistryCustomizer.class);
meterRegistryCustomizers = new ArrayList<>();
for(MeterRegistryCustomizer c : map.values()) {
meterRegistryCustomizers.add(c);
}
}
this.configurer = new MeterRegistryConfigurer(
meterBinders,
meterFilters,
meterRegistryCustomizers, properties.isUseGlobalRegistry());
}
return this.configurer;
}
private <T> List<T> getOrEmpty(List<T> list) {
return list != null ? list : Collections.emptyList();
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/MetricsAutoConfiguration.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure;
import java.util.List;
import io.micrometer.core.annotation.Timed;
import io.micrometer.core.instrument.Clock;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration;
import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
/**
* {@link EnableAutoConfiguration} for Micrometer-based metrics.
*
* @author Jon Schneider
*/
@Configuration
@ConditionalOnClass(Timed.class)
@EnableConfigurationProperties(MetricsProperties.class)
@AutoConfigureAfter({
DataSourceAutoConfiguration.class,
RabbitAutoConfiguration.class,
CacheAutoConfiguration.class
})
@AutoConfigureBefore(CompositeMeterRegistryAutoConfiguration.class)
public class MetricsAutoConfiguration {
@Bean
@ConditionalOnMissingBean(Clock.class)
public Clock micrometerClock() {
return Clock.SYSTEM;
}
@Bean
public static MeterRegistryPostProcessor meterRegistryPostProcessor() {
return new MeterRegistryPostProcessor();
}
@Bean
@Order(0)
public PropertiesMeterFilter propertiesMeterFilter(MetricsProperties properties) {
return new PropertiesMeterFilter(properties);
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/MetricsProperties.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* {@link ConfigurationProperties} for configuring Micrometer-based metrics.
*
* @author Jon Schneider
* @author Alexander Abramov
*/
@ConfigurationProperties("management.metrics")
public class MetricsProperties {
private final Web web = new Web();
private final Distribution distribution = new Distribution();
/**
* If {@code false}, the matching meter(s) are no-op.
*/
private final Map<String, Boolean> enable = new HashMap<>();
/**
* Common tags that are applied to every meter.
*/
private final Map<String, String> tags = new LinkedHashMap<>();
/**
* Whether or not auto-configured MeterRegistry implementations should be bound to the
* global static registry on Metrics. For testing, set this to 'false' to maximize
* test independence.
*/
private boolean useGlobalRegistry = true;
public boolean isUseGlobalRegistry() {
return this.useGlobalRegistry;
}
public void setUseGlobalRegistry(boolean useGlobalRegistry) {
this.useGlobalRegistry = useGlobalRegistry;
}
public Web getWeb() {
return this.web;
}
public Map<String, Boolean> getEnable() {
return enable;
}
public Map<String, String> getTags() {
return this.tags;
}
public Distribution getDistribution() {
return distribution;
}
public static class Web {
private final Client client = new Client();
private final Server server = new Server();
public Client getClient() {
return this.client;
}
public Server getServer() {
return this.server;
}
public static class Client {
/**
* Name of the metric for sent requests.
*/
private String requestsMetricName = "http.client.requests";
/**
* Maximum number of unique URI tag values allowed. After the max number of tag values is reached,
* metrics with additional tag values are denied by filter.
*/
private int maxUriTags = 100;
public String getRequestsMetricName() {
return this.requestsMetricName;
}
public void setRequestsMetricName(String requestsMetricName) {
this.requestsMetricName = requestsMetricName;
}
public int getMaxUriTags() {
return maxUriTags;
}
public void setMaxUriTags(int maxUriTags) {
this.maxUriTags = maxUriTags;
}
}
public static class Server {
/**
* Whether or not requests handled by Spring MVC or WebFlux should be
* automatically timed. If the number of time series emitted grows too large
* on account of request mapping timings, disable this and use 'Timed' on a
* per request mapping basis as needed.
*/
private boolean autoTimeRequests = true;
/**
* Name of the metric for received requests.
*/
private String requestsMetricName = "http.server.requests";
/**
* Maximum number of unique URI tag values allowed. After the max number of
* tag values is reached, metrics with additional tag values are denied by
* filter.
*/
private int maxUriTags = 100;
public boolean isAutoTimeRequests() {
return this.autoTimeRequests;
}
public void setAutoTimeRequests(boolean autoTimeRequests) {
this.autoTimeRequests = autoTimeRequests;
}
public String getRequestsMetricName() {
return this.requestsMetricName;
}
public void setRequestsMetricName(String requestsMetricName) {
this.requestsMetricName = requestsMetricName;
}
public int getMaxUriTags() {
return this.maxUriTags;
}
public void setMaxUriTags(int maxUriTags) {
this.maxUriTags = maxUriTags;
}
}
}
public static class Distribution {
/**
* Whether meter IDs starting with the specified name should publish percentile
* histograms. For monitoring systems that support aggregable percentile
* calculation based on a histogram, this can be set to true. For other systems,
* this has no effect. The longest match wins, the key `all` can also be used to
* configure all meters.
*/
private final Map<String, Boolean> percentilesHistogram = new LinkedHashMap<>();
/**
* Specific computed non-aggregable percentiles to ship to the backend for meter
* IDs starting-with the specified name. The longest match wins, the key `all` can
* also be used to configure all meters.
*/
private final Map<String, double[]> percentiles = new LinkedHashMap<>();
/**
* Specific SLA boundaries for meter IDs starting-with the specified name. The
* longest match wins. Counters will be published for each specified boundary.
* Values can be specified as a long or as a Duration value (for timer meters,
* defaulting to ms if no unit specified).
*/
private final Map<String, ServiceLevelAgreementBoundary[]> sla = new LinkedHashMap<>();
/**
* Minimum value that meter IDs starting-with the specified name are expected to
* observe. The longest match wins. Values can be specified as a long or as a
* Duration value (for timer meters, defaulting to ms if no unit specified).
*/
private final Map<String, String> minimumExpectedValue = new LinkedHashMap<>();
/**
* Maximum value that meter IDs starting-with the specified name are expected to
* observe. The longest match wins. Values can be specified as a long or as a
* Duration value (for timer meters, defaulting to ms if no unit specified).
*/
private final Map<String, String> maximumExpectedValue = new LinkedHashMap<>();
public Map<String, Boolean> getPercentilesHistogram() {
return this.percentilesHistogram;
}
public Map<String, double[]> getPercentiles() {
return this.percentiles;
}
public Map<String, ServiceLevelAgreementBoundary[]> getSla() {
return this.sla;
}
public Map<String, String> getMinimumExpectedValue() {
return this.minimumExpectedValue;
}
public Map<String, String> getMaximumExpectedValue() {
return this.maximumExpectedValue;
}
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/NoOpMeterRegistryConfiguration.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure;
import io.micrometer.core.instrument.Clock;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.composite.CompositeMeterRegistry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
/**
* Configuration for a no-op meter registry when the context does not contain an
* auto-configured {@link MeterRegistry}.
*
* @author Andy Wilkinson
*/
@ConditionalOnBean(Clock.class)
@ConditionalOnMissingBean(MeterRegistry.class)
class NoOpMeterRegistryConfiguration {
@Bean
public CompositeMeterRegistry noOpMeterRegistry(Clock clock) {
return new CompositeMeterRegistry(clock);
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/SystemMetricsAutoConfiguration.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.system.FileDescriptorMetrics;
import io.micrometer.core.instrument.binder.system.ProcessorMetrics;
import io.micrometer.core.instrument.binder.system.UptimeMetrics;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* {@link EnableAutoConfiguration Auto-configuration} for system metrics.
*
* @author Jon Schneider
* @author Stephane Nicoll
* @since 1.1.0
*/
@Configuration
@AutoConfigureAfter(MetricsAutoConfiguration.class)
@ConditionalOnClass(MeterRegistry.class)
@ConditionalOnBean(MeterRegistry.class)
public class SystemMetricsAutoConfiguration {
@Bean
@ConditionalOnProperty(value = "management.metrics.binders.uptime.enabled", matchIfMissing = true)
@ConditionalOnMissingBean(UptimeMetrics.class)
public UptimeMetrics uptimeMetrics() {
return new UptimeMetrics();
}
@Bean
@ConditionalOnProperty(value = "management.metrics.binders.processor.enabled", matchIfMissing = true)
@ConditionalOnMissingBean(ProcessorMetrics.class)
public ProcessorMetrics processorMetrics() {
return new ProcessorMetrics();
}
@Bean
@ConditionalOnProperty(name = "management.metrics.binders.files.enabled", matchIfMissing = true)
@ConditionalOnMissingBean(FileDescriptorMetrics.class)
public FileDescriptorMetrics fileDescriptorMetrics() {
return new FileDescriptorMetrics();
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/export/StringToDurationConverter.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure.export;
import io.micrometer.core.instrument.util.StringUtils;
import io.micrometer.core.lang.Nullable;
import org.springframework.boot.context.properties.ConfigurationPropertiesBinding;
import org.springframework.core.annotation.Order;
import org.springframework.core.convert.converter.Converter;
import java.time.Duration;
import java.time.format.DateTimeParseException;
import java.util.Optional;
import java.util.function.Function;
/**
* A {@link Converter} to create a {@link Duration} from a {@link String}.
*
* @author Jon Schneider
* @author Andy Wilkinson
*/
@ConfigurationPropertiesBinding
@Order(0)
public class StringToDurationConverter implements Converter<String, Duration> {
@Nullable
private static Duration simpleParse(@Nullable String rawTime) {
if (StringUtils.isEmpty(rawTime))
return null;
if (!Character.isDigit(rawTime.charAt(0)))
return null;
String time = rawTime.toLowerCase();
return tryParse(time, "ns", Duration::ofNanos)
.orElseGet(() -> tryParse(time, "ms", Duration::ofMillis)
.orElseGet(() -> tryParse(time, "s", Duration::ofSeconds)
.orElseGet(() -> tryParse(time, "m", Duration::ofMinutes)
.orElseGet(() -> tryParse(time, "h", Duration::ofHours)
.orElseGet(() -> tryParse(time, "d", Duration::ofDays)
.orElse(null))))));
}
private static Optional<Duration> tryParse(String time, String unit, Function<Long, Duration> toDuration) {
if (time.endsWith(unit)) {
String trim = time.substring(0, time.lastIndexOf(unit)).trim();
try {
return Optional.of(toDuration.apply(Long.parseLong(trim)));
} catch (NumberFormatException ignore) {
return Optional.empty();
}
}
return Optional.empty();
}
@Override
public Duration convert(@Nullable String source) {
Duration duration = simpleParse(source);
try {
return duration == null ? Duration.parse(source) : duration;
} catch (DateTimeParseException e) {
throw new IllegalArgumentException("Cannot convert '" + source + "' to Duration", e);
}
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/export/StringToTimeUnitConverter.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure.export;
import org.springframework.boot.context.properties.ConfigurationPropertiesBinding;
import org.springframework.core.annotation.Order;
import org.springframework.core.convert.converter.Converter;
import java.util.concurrent.TimeUnit;
/**
* @author Nicolas Portmann
*/
@ConfigurationPropertiesBinding
@Order(0)
public class StringToTimeUnitConverter implements Converter<String, TimeUnit> {
@Override
public TimeUnit convert(String source) {
return TimeUnit.valueOf(source.toUpperCase());
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/export
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/export/prometheus/PrometheusMetricsExportAutoConfiguration.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure.export.prometheus;
import ai.foremast.micrometer.export.prometheus.PrometheusScrapeMvcEndpoint;
import io.micrometer.core.instrument.Clock;
import io.micrometer.prometheus.PrometheusConfig;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import ai.foremast.micrometer.autoconfigure.CompositeMeterRegistryAutoConfiguration;
import ai.foremast.micrometer.autoconfigure.MetricsAutoConfiguration;
import ai.foremast.micrometer.autoconfigure.export.StringToDurationConverter;
import ai.foremast.micrometer.autoconfigure.export.simple.SimpleMetricsExportAutoConfiguration;
import ai.foremast.micrometer.export.prometheus.PrometheusScrapeEndpoint;
import io.prometheus.client.CollectorRegistry;
import org.springframework.boot.actuate.autoconfigure.ManagementContextConfiguration;
import org.springframework.boot.actuate.condition.ConditionalOnEnabledEndpoint;
import org.springframework.boot.actuate.endpoint.AbstractEndpoint;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* Configuration for exporting metrics to Prometheus.
*
* @author Jon Schneider
* @author David J. M. Karlsen
* @author Johnny Lim
*/
@Configuration
@AutoConfigureBefore({CompositeMeterRegistryAutoConfiguration.class,
SimpleMetricsExportAutoConfiguration.class})
@AutoConfigureAfter(MetricsAutoConfiguration.class)
@ConditionalOnBean(Clock.class)
@ConditionalOnClass(PrometheusMeterRegistry.class)
@ConditionalOnProperty(prefix = "management.metrics.export.prometheus", name = "enabled", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(PrometheusProperties.class)
@Import(StringToDurationConverter.class)
public class PrometheusMetricsExportAutoConfiguration {
@Bean
@ConditionalOnMissingBean(PrometheusConfig.class)
public PrometheusConfig prometheusConfig(PrometheusProperties props) {
return new PrometheusPropertiesConfigAdapter(props);
}
@Bean
@ConditionalOnMissingBean(PrometheusMeterRegistry.class)
public PrometheusMeterRegistry prometheusMeterRegistry(PrometheusConfig config, CollectorRegistry collectorRegistry,
Clock clock) {
return new PrometheusMeterRegistry(config, collectorRegistry, clock);
}
@Bean
@ConditionalOnMissingBean(CollectorRegistry.class)
public CollectorRegistry collectorRegistry() {
return new CollectorRegistry(true);
}
@ManagementContextConfiguration
@ConditionalOnClass(AbstractEndpoint.class)
public static class PrometheusScrapeEndpointConfiguration {
@Bean
public PrometheusScrapeEndpoint prometheusEndpoint(CollectorRegistry collectorRegistry) {
return new PrometheusScrapeEndpoint(collectorRegistry);
}
@Bean
@ConditionalOnEnabledEndpoint("prometheus")
public PrometheusScrapeMvcEndpoint prometheusMvcEndpoint(PrometheusScrapeEndpoint delegate) {
return new PrometheusScrapeMvcEndpoint(delegate);
}
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/export
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/export/prometheus/PrometheusProperties.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure.export.prometheus;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.time.Duration;
/**
* {@link ConfigurationProperties} for configuring metrics export to Prometheus.
*
* @author Jon Schneider
*/
@ConfigurationProperties(prefix = "management.metrics.export.prometheus")
public class PrometheusProperties {
/**
* Whether to enable publishing descriptions as part of the scrape payload to
* Prometheus. Turn this off to minimize the amount of data sent on each scrape.
*/
private boolean descriptions = true;
/**
* Step size (i.e. reporting frequency) to use.
*/
private Duration step = Duration.ofMinutes(1);
public boolean isDescriptions() {
return this.descriptions;
}
public void setDescriptions(boolean descriptions) {
this.descriptions = descriptions;
}
public Duration getStep() {
return this.step;
}
public void setStep(Duration step) {
this.step = step;
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/export
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/export/prometheus/PrometheusPropertiesConfigAdapter.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure.export.prometheus;
import io.micrometer.prometheus.PrometheusConfig;
import ai.foremast.micrometer.autoconfigure.export.properties.PropertiesConfigAdapter;
import java.time.Duration;
/**
* Adapter to convert {@link PrometheusProperties} to a {@link PrometheusConfig}.
*
* @author Jon Schneider
* @author Phillip Webb
*/
class PrometheusPropertiesConfigAdapter extends PropertiesConfigAdapter<PrometheusProperties> implements PrometheusConfig {
PrometheusPropertiesConfigAdapter(PrometheusProperties properties) {
super(properties);
}
@Override
public String get(String key) {
return null;
}
@Override
public boolean descriptions() {
return get(PrometheusProperties::isDescriptions,
PrometheusConfig.super::descriptions);
}
@Override
public Duration step() {
return get(PrometheusProperties::getStep, PrometheusConfig.super::step);
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/export
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/export/simple/SimpleMetricsExportAutoConfiguration.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure.export.simple;
import io.micrometer.core.instrument.Clock;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleConfig;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import ai.foremast.micrometer.autoconfigure.CompositeMeterRegistryAutoConfiguration;
import ai.foremast.micrometer.autoconfigure.MetricsAutoConfiguration;
import ai.foremast.micrometer.autoconfigure.export.StringToDurationConverter;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* Configuration for exporting metrics to a {@link SimpleMeterRegistry}.
*
* @author Jon Schneider
*/
@Configuration
@AutoConfigureAfter(MetricsAutoConfiguration.class)
@AutoConfigureBefore(CompositeMeterRegistryAutoConfiguration.class)
@ConditionalOnBean(Clock.class)
@EnableConfigurationProperties(SimpleProperties.class)
@ConditionalOnMissingBean(MeterRegistry.class)
@ConditionalOnProperty(prefix = "management.metrics.export.simple", name = "enabled", havingValue = "true", matchIfMissing = true)
@Import(StringToDurationConverter.class)
public class SimpleMetricsExportAutoConfiguration {
@Bean
@ConditionalOnMissingBean(SimpleConfig.class)
public SimpleConfig simpleRegistryConfig(SimpleProperties props) {
return new SimplePropertiesConfigAdapter(props);
}
@Bean
@ConditionalOnMissingBean(MeterRegistry.class)
public SimpleMeterRegistry simpleMeterRegistry(SimpleConfig config, Clock clock) {
return new SimpleMeterRegistry(config, clock);
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/export
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/export/simple/SimpleProperties.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure.export.simple;
import io.micrometer.core.instrument.simple.CountingMode;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.time.Duration;
/**
* {@link ConfigurationProperties} for configuring metrics export to a
* {@link SimpleMeterRegistry}.
*
* @author Jon Schneider
*/
@ConfigurationProperties(prefix = "management.metrics.export.simple")
public class SimpleProperties {
/**
* Step size (i.e. reporting frequency) to use.
*/
private Duration step = Duration.ofMinutes(1);
/**
* Counting mode.
*/
private CountingMode mode = CountingMode.CUMULATIVE;
public Duration getStep() {
return this.step;
}
public void setStep(Duration step) {
this.step = step;
}
public CountingMode getMode() {
return this.mode;
}
public void setMode(CountingMode mode) {
this.mode = mode;
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/export
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/export/simple/SimplePropertiesConfigAdapter.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure.export.simple;
import io.micrometer.core.instrument.simple.CountingMode;
import io.micrometer.core.instrument.simple.SimpleConfig;
import ai.foremast.micrometer.autoconfigure.export.properties.PropertiesConfigAdapter;
import java.time.Duration;
/**
* Adapter to convert {@link SimpleProperties} to a {@link SimpleConfig}.
*
* @author Jon Schneider
*/
public class SimplePropertiesConfigAdapter extends PropertiesConfigAdapter<SimpleProperties> implements SimpleConfig {
public SimplePropertiesConfigAdapter(SimpleProperties properties) {
super(properties);
}
@Override
public String get(String key) {
return null;
}
@Override
public Duration step() {
return get(SimpleProperties::getStep, SimpleConfig.super::step);
}
@Override
public CountingMode mode() {
return get(SimpleProperties::getMode, SimpleConfig.super::mode);
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/web
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/web/servlet/WebMvcMetricsAutoConfiguration.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure.web.servlet;
import ai.foremast.micrometer.web.servlet.HandlerMappingIntrospector;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.config.MeterFilter;
import ai.foremast.micrometer.autoconfigure.MetricsAutoConfiguration;
import ai.foremast.micrometer.autoconfigure.MetricsProperties;
import ai.foremast.micrometer.autoconfigure.OnlyOnceLoggingDenyMeterFilter;
import ai.foremast.micrometer.autoconfigure.export.simple.SimpleMetricsExportAutoConfiguration;
import ai.foremast.micrometer.web.servlet.DefaultWebMvcTagsProvider;
import ai.foremast.micrometer.web.servlet.WebMvcMetricsFilter;
import ai.foremast.micrometer.web.servlet.WebMvcTagsProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
/**
* {@link EnableAutoConfiguration Auto-configuration} for instrumentation of Spring Web
* MVC servlet-based request mappings.
*
* @author Jon Schneider
* @author Dmytro Nosan
*/
@Configuration
@AutoConfigureAfter({ MetricsAutoConfiguration.class,
SimpleMetricsExportAutoConfiguration.class })
@ConditionalOnWebApplication
@ConditionalOnClass(DispatcherServlet.class)
@ConditionalOnBean(MeterRegistry.class)
@EnableConfigurationProperties(MetricsProperties.class)
public class WebMvcMetricsAutoConfiguration {
@Autowired
private MetricsProperties properties;
@Bean
@ConditionalOnMissingBean(WebMvcTagsProvider.class)
public DefaultWebMvcTagsProvider servletTagsProvider() {
return new DefaultWebMvcTagsProvider();
}
@SuppressWarnings("deprecation")
@Bean
public WebMvcMetricsFilter webMetricsFilter(MeterRegistry registry,
WebMvcTagsProvider tagsProvider,
WebApplicationContext ctx) {
return new WebMvcMetricsFilter(registry, tagsProvider,
properties.getWeb().getServer().getRequestsMetricName(),
properties.getWeb().getServer().isAutoTimeRequests(),
new HandlerMappingIntrospector(ctx));
}
@Bean
@Order(0)
public MeterFilter metricsHttpServerUriTagFilter() {
String metricName = this.properties.getWeb().getServer().getRequestsMetricName();
MeterFilter filter = new OnlyOnceLoggingDenyMeterFilter(() -> String
.format("Reached the maximum number of URI tags for '%s'.", metricName));
return MeterFilter.maximumAllowableTags(metricName, "uri",
this.properties.getWeb().getServer().getMaxUriTags(), filter);
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/web
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/autoconfigure/web/tomcat/TomcatMetricsAutoConfiguration.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.autoconfigure.web.tomcat;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.tomcat.TomcatMetrics;
import ai.foremast.micrometer.web.tomcat.TomcatMetricsBinder;
import org.apache.catalina.Manager;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* {@link EnableAutoConfiguration Auto-configuration} for {@link TomcatMetrics}.
*
* @author Clint Checketts
* @author Jon Schneider
* @author Andy Wilkinson
* @since 1.1.0
*/
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ TomcatMetrics.class, Manager.class })
public class TomcatMetricsAutoConfiguration {
@Bean
@ConditionalOnBean(MeterRegistry.class)
@ConditionalOnMissingBean({ TomcatMetrics.class, TomcatMetricsBinder.class })
public TomcatMetricsBinder tomcatMetricsBinder(MeterRegistry meterRegistry) {
return new TomcatMetricsBinder(meterRegistry);
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/export
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/export/prometheus/PrometheusScrapeEndpoint.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.export.prometheus;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.exporter.common.TextFormat;
import org.springframework.boot.actuate.endpoint.AbstractEndpoint;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.ResponseEntity;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import static org.springframework.http.HttpHeaders.CONTENT_TYPE;
/**
* Spring Boot Actuator endpoint that outputs Prometheus metrics in a format that
* can be scraped by the Prometheus server
*
* @author Jon Schneider
*/
@ConfigurationProperties("endpoints.prometheus")
public class PrometheusScrapeEndpoint extends AbstractEndpoint<ResponseEntity<String>> {
private final CollectorRegistry collectorRegistry;
public PrometheusScrapeEndpoint(CollectorRegistry collectorRegistry) {
super("prometheus");
this.collectorRegistry = collectorRegistry;
}
@Override
public ResponseEntity<String> invoke() {
try {
Writer writer = new StringWriter();
TextFormat.write004(writer, collectorRegistry.metricFamilySamples());
return ResponseEntity.ok()
.header(CONTENT_TYPE, TextFormat.CONTENT_TYPE_004)
.body(writer.toString());
} catch (IOException e) {
// This actually never happens since StringWriter::write() doesn't throw any IOException
throw new RuntimeException("Writing metrics failed", e);
}
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/export
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/export/prometheus/PrometheusScrapeMvcEndpoint.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.export.prometheus;
import org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter;
import org.springframework.web.bind.annotation.RequestMapping;
public class PrometheusScrapeMvcEndpoint extends EndpointMvcAdapter {
public PrometheusScrapeMvcEndpoint(PrometheusScrapeEndpoint delegate) {
super(delegate);
}
@RequestMapping
@Override
public Object invoke() {
return super.invoke();
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/web
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/web/servlet/HandlerMappingIntrospector.java
|
/**
* Licensed to the Foremast 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.web.servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
/**
* Helper class to get information from the {@code HandlerMapping} that would
* serve a specific request.
*
* <p>Provides the following methods:
* <ul>
* <li>{@link #getHandlerExecutionChain} — obtain a {@code HandlerMapping}
* to check request-matching criteria against.
* <li>{@link #getCorsConfiguration} — obtain the CORS configuration for the
* request.
* </ul>
*
* @author Rossen Stoyanchev
* @since 4.3.1
*/
public class HandlerMappingIntrospector
implements CorsConfigurationSource, ApplicationContextAware, InitializingBean {
private ApplicationContext applicationContext;
private List<HandlerMapping> handlerMappings;
/**
* Constructor for use with {@link ApplicationContextAware}.
*/
public HandlerMappingIntrospector() {
}
/**
* Constructor that detects the configured {@code HandlerMapping}s in the
* given {@code ApplicationContext} or falls back on
* "DispatcherServlet.properties" like the {@code DispatcherServlet}.
* @deprecated as of 4.3.12, in favor of {@link #setApplicationContext}
*/
@Deprecated
public HandlerMappingIntrospector(ApplicationContext context) {
this.handlerMappings = initHandlerMappings(context);
}
/**
* Return the configured HandlerMapping's.
*/
public List<HandlerMapping> getHandlerMappings() {
return (this.handlerMappings != null ? this.handlerMappings : Collections.emptyList());
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public void afterPropertiesSet() {
if (this.handlerMappings == null) {
Assert.notNull(this.applicationContext, "No ApplicationContext");
this.handlerMappings = initHandlerMappings(this.applicationContext);
}
}
/**
* Find the {@link HandlerMapping} that would handle the given request and
* return it as a {@link MatchableHandlerMapping} that can be used to test
* request-matching criteria.
* <p>If the matching HandlerMapping is not an instance of
* {@link MatchableHandlerMapping}, an IllegalStateException is raised.
* @param request the current request
* @return the resolved matcher, or {@code null}
* @throws Exception if any of the HandlerMapping's raise an exception
*/
public HandlerExecutionChain getHandlerExecutionChain(HttpServletRequest request) throws Exception {
Assert.notNull(this.handlerMappings, "Handler mappings not initialized");
HttpServletRequest wrapper = new RequestAttributeChangeIgnoringWrapper(request);
for (HandlerMapping handlerMapping : this.handlerMappings) {
Object handler = handlerMapping.getHandler(wrapper);
if (handler == null) {
continue;
}
if (handler instanceof HandlerExecutionChain) {
return (HandlerExecutionChain)handler;
}
throw new IllegalStateException("HandlerMapping is not a MatchableHandlerMapping");
}
return null;
}
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
Assert.notNull(this.handlerMappings, "Handler mappings not initialized");
HttpServletRequest wrapper = new RequestAttributeChangeIgnoringWrapper(request);
for (HandlerMapping handlerMapping : this.handlerMappings) {
HandlerExecutionChain handler = null;
try {
handler = handlerMapping.getHandler(wrapper);
}
catch (Exception ex) {
// Ignore
}
if (handler == null) {
continue;
}
if (handler.getInterceptors() != null) {
for (HandlerInterceptor interceptor : handler.getInterceptors()) {
if (interceptor instanceof CorsConfigurationSource) {
return ((CorsConfigurationSource) interceptor).getCorsConfiguration(wrapper);
}
}
}
if (handler.getHandler() instanceof CorsConfigurationSource) {
return ((CorsConfigurationSource) handler.getHandler()).getCorsConfiguration(wrapper);
}
}
return null;
}
private static List<HandlerMapping> initHandlerMappings(ApplicationContext applicationContext) {
Map<String, HandlerMapping> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
applicationContext, HandlerMapping.class, true, false);
if (!beans.isEmpty()) {
List<HandlerMapping> mappings = new ArrayList<>(beans.values());
AnnotationAwareOrderComparator.sort(mappings);
return Collections.unmodifiableList(mappings);
}
return Collections.unmodifiableList(initFallback(applicationContext));
}
private static List<HandlerMapping> initFallback(ApplicationContext applicationContext) {
Properties props;
String path = "DispatcherServlet.properties";
try {
Resource resource = new ClassPathResource(path, DispatcherServlet.class);
props = PropertiesLoaderUtils.loadProperties(resource);
}
catch (IOException ex) {
throw new IllegalStateException("Could not load '" + path + "': " + ex.getMessage());
}
String value = props.getProperty(HandlerMapping.class.getName());
String[] names = StringUtils.commaDelimitedListToStringArray(value);
List<HandlerMapping> result = new ArrayList<>(names.length);
for (String name : names) {
try {
Class<?> clazz = ClassUtils.forName(name, DispatcherServlet.class.getClassLoader());
Object mapping = applicationContext.getAutowireCapableBeanFactory().createBean(clazz);
result.add((HandlerMapping) mapping);
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException("Could not find default HandlerMapping [" + name + "]");
}
}
return result;
}
/**
* Request wrapper that ignores request attribute changes.
*/
private static class RequestAttributeChangeIgnoringWrapper extends HttpServletRequestWrapper {
public RequestAttributeChangeIgnoringWrapper(HttpServletRequest request) {
super(request);
}
@Override
public void setAttribute(String name, Object value) {
// Ignore attribute change...
}
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/web
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/web/servlet/WebMvcMetricsFilter.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.web.servlet;
import io.micrometer.core.annotation.Timed;
import io.micrometer.core.instrument.LongTaskTimer;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.lang.NonNullApi;
import ai.foremast.micrometer.TimedUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.util.NestedServletException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Intercepts incoming HTTP requests and records metrics about execution time and results.
*
* @author Jon Schneider
*/
@NonNullApi
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
public class WebMvcMetricsFilter extends OncePerRequestFilter {
private static final String TIMING_SAMPLE = "micrometer.timingSample";
private static final Log logger = LogFactory.getLog(WebMvcMetricsFilter.class);
private final MeterRegistry registry;
private final WebMvcTagsProvider tagsProvider;
private final String metricName;
private final boolean autoTimeRequests;
private final HandlerMappingIntrospector mappingIntrospector;
public WebMvcMetricsFilter(MeterRegistry registry, WebMvcTagsProvider tagsProvider,
String metricName, boolean autoTimeRequests,
HandlerMappingIntrospector mappingIntrospector) {
this.registry = registry;
this.tagsProvider = tagsProvider;
this.metricName = metricName;
this.autoTimeRequests = autoTimeRequests;
this.mappingIntrospector = mappingIntrospector;
}
@Override
protected boolean shouldNotFilterAsyncDispatch() {
return false;
}
@SuppressWarnings("ConstantConditions")
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
HandlerExecutionChain handler = null;
try {
handler = mappingIntrospector.getHandlerExecutionChain(request);
// if (matchableHandlerMapping != null) {
// handler = matchableHandlerMapping.getHandler(request);
// }
} catch (Exception e) {
logger.debug("Unable to time request", e);
filterChain.doFilter(request, response);
return;
}
final Object handlerObject = handler == null ? null : handler.getHandler();
// If this is the second invocation of the filter in an async request, we don't
// want to start sampling again (effectively bumping the active count on any long task timers).
// Rather, we'll just use the sampling context we started on the first invocation.
TimingSampleContext timingContext = (TimingSampleContext) request.getAttribute(TIMING_SAMPLE);
if (timingContext == null) {
timingContext = new TimingSampleContext(request, handlerObject);
}
try {
filterChain.doFilter(request, response);
if (request.isAsyncSupported()) {
// this won't be "started" until after the first call to doFilter
if (request.isAsyncStarted()) {
request.setAttribute(TIMING_SAMPLE, timingContext);
}
}
if (!request.isAsyncStarted()) {
record(timingContext, response, request,
handlerObject, (Throwable) request.getAttribute(DispatcherServlet.EXCEPTION_ATTRIBUTE));
}
} catch (NestedServletException e) {
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
record(timingContext, response, request, handlerObject, e.getCause());
throw e;
}
}
private void record(TimingSampleContext timingContext, HttpServletResponse response, HttpServletRequest request,
Object handlerObject, Throwable e) {
for (Timed timedAnnotation : timingContext.timedAnnotations) {
timingContext.timerSample.stop(Timer.builder(timedAnnotation, metricName)
.tags(tagsProvider.httpRequestTags(request, response, handlerObject, e))
.register(registry));
}
if (timingContext.timedAnnotations.isEmpty() && autoTimeRequests) {
timingContext.timerSample.stop(Timer.builder(metricName)
.tags(tagsProvider.httpRequestTags(request, response, handlerObject, e))
.register(registry));
}
for (LongTaskTimer.Sample sample : timingContext.longTaskTimerSamples) {
sample.stop();
}
}
private class TimingSampleContext {
private final Set<Timed> timedAnnotations;
private final Timer.Sample timerSample;
private final Collection<LongTaskTimer.Sample> longTaskTimerSamples;
TimingSampleContext(HttpServletRequest request, Object handlerObject) {
timedAnnotations = annotations(handlerObject);
timerSample = Timer.start(registry);
longTaskTimerSamples = timedAnnotations.stream()
.filter(Timed::longTask)
.map(t -> LongTaskTimer.builder(t)
.tags(tagsProvider.httpLongRequestTags(request, handlerObject))
.register(registry)
.start())
.collect(Collectors.toList());
}
private Set<Timed> annotations(Object handler) {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Set<Timed> timed = TimedUtils.findTimedAnnotations(handlerMethod.getMethod());
if (timed.isEmpty()) {
return TimedUtils.findTimedAnnotations(handlerMethod.getBeanType());
}
return timed;
}
return Collections.emptySet();
}
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/web
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/web/servlet/WebMvcTags.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.web.servlet;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.lang.NonNullApi;
import io.micrometer.core.lang.Nullable;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Factory methods for {@link Tag Tags} associated with a request-response exchange that
* is instrumented by {@link WebMvcMetricsFilter}.
*
* @author Jon Schneider
* @author Andy Wilkinson
* @author Michael McFadyen
*/
@NonNullApi
public final class WebMvcTags {
private static final Tag URI_NOT_FOUND = Tag.of("uri", "NOT_FOUND");
private static final Tag URI_REDIRECTION = Tag.of("uri", "REDIRECTION");
private static final Tag URI_ROOT = Tag.of("uri", "root");
private static final Tag URI_UNKNOWN = Tag.of("uri", "UNKNOWN");
private static final Tag EXCEPTION_NONE = Tag.of("exception", "None");
private static final Tag STATUS_UNKNOWN = Tag.of("status", "UNKNOWN");
// private static final Tag OUTCOME_UNKNOWN = Tag.of("outcome", "UNKNOWN");
// private static final Tag OUTCOME_INFORMATIONAL = Tag.of("outcome", "INFORMATIONAL");
//
// private static final Tag OUTCOME_SUCCESS = Tag.of("outcome", "SUCCESS");
//
// private static final Tag OUTCOME_REDIRECTION = Tag.of("outcome", "REDIRECTION");
//
// private static final Tag OUTCOME_CLIENT_ERROR = Tag.of("outcome", "CLIENT_ERROR");
//
// private static final Tag OUTCOME_SERVER_ERROR = Tag.of("outcome", "SERVER_ERROR");
private static final Tag METHOD_UNKNOWN = Tag.of("method", "UNKNOWN");
private WebMvcTags() {
}
/**
* Creates a {@code method} tag based on the {@link HttpServletRequest#getMethod()
* method} of the given {@code request}.
*
* @param request the request
* @return the method tag whose value is a capitalized method (e.g. GET).
*/
public static Tag method(@Nullable HttpServletRequest request) {
return request == null ? METHOD_UNKNOWN : Tag.of("method", request.getMethod());
}
/**
* Creates a {@code method} tag based on the status of the given {@code response}.
*
* @param response the HTTP response
* @return the status tag derived from the status of the response
*/
public static Tag status(@Nullable HttpServletResponse response) {
return response == null ? STATUS_UNKNOWN : Tag.of("status", Integer.toString(response.getStatus()));
}
/**
* Creates a {@code uri} tag based on the URI of the given {@code request}. Uses the
* {@link HandlerMapping#BEST_MATCHING_PATTERN_ATTRIBUTE} best matching pattern if
* available. Falling back to {@code REDIRECTION} for 3xx responses, {@code NOT_FOUND}
* for 404 responses, {@code root} for requests with no path info, and {@code UNKNOWN}
* for all other requests.
*
* @param request the request
* @param response the response
* @return the uri tag derived from the request
*/
public static Tag uri(@Nullable HttpServletRequest request, @Nullable HttpServletResponse response) {
if (request != null) {
String pattern = getMatchingPattern(request);
if (pattern != null) {
return Tag.of("uri", pattern);
} else if (response != null) {
HttpStatus status = extractStatus(response);
if (status != null && status.is3xxRedirection()) {
return URI_REDIRECTION;
}
if (status != null && status.equals(HttpStatus.NOT_FOUND)) {
return URI_NOT_FOUND;
}
}
String pathInfo = getPathInfo(request);
if (pathInfo.isEmpty()) {
return URI_ROOT;
}
}
return URI_UNKNOWN;
}
@Nullable
private static HttpStatus extractStatus(HttpServletResponse response) {
try {
return HttpStatus.valueOf(response.getStatus());
} catch (IllegalArgumentException ex) {
return null;
}
}
@Nullable
private static String getMatchingPattern(HttpServletRequest request) {
return (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
}
private static String getPathInfo(HttpServletRequest request) {
String uri = StringUtils.hasText(request.getPathInfo()) ?
request.getPathInfo() : "/";
return uri.replaceAll("//+", "/")
.replaceAll("/$", "");
}
/**
* Creates a {@code exception} tag based on the {@link Class#getSimpleName() simple
* name} of the class of the given {@code exception}.
*
* @param exception the exception, may be {@code null}
* @return the exception tag derived from the exception
*/
public static Tag exception(@Nullable Throwable exception) {
if (exception == null) {
return EXCEPTION_NONE;
}
String simpleName = exception.getClass().getSimpleName();
return Tag.of("exception", simpleName.isEmpty() ? exception.getClass().getName() : simpleName);
}
// /**
// * Creates an {@code outcome} tag based on the status of the given {@code response}.
// * @param response the HTTP response
// * @return the outcome tag derived from the status of the response
// * @since 1.1.0
// */
// public static Tag outcome(@Nullable HttpServletResponse response) {
// if (response != null) {
// HttpStatus status = extractStatus(response);
// if (status != null) {
// if (status.is1xxInformational()) {
// return OUTCOME_INFORMATIONAL;
// }
// if (status.is2xxSuccessful()) {
// return OUTCOME_SUCCESS;
// }
// if (status.is3xxRedirection()) {
// return OUTCOME_REDIRECTION;
// }
// if (status.is4xxClientError()) {
// return OUTCOME_CLIENT_ERROR;
// }
// }
// return OUTCOME_SERVER_ERROR;
// }
// return OUTCOME_UNKNOWN;
// }
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/web
|
java-sources/ai/foremast/metrics/foremast-spring-boot-1x-k8s-metrics-starter/0.1.7/ai/foremast/micrometer/web/tomcat/TomcatMetricsBinder.java
|
/**
* Copyright 2019 Pivotal Software, Inc.
* <p>
* Licensed 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.micrometer.web.tomcat;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.binder.tomcat.TomcatMetrics;
import org.apache.catalina.Container;
import org.apache.catalina.Context;
import org.apache.catalina.Manager;
import org.springframework.boot.context.embedded.EmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedWebApplicationContext;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import java.util.Collections;
/**
* Binds {@link TomcatMetrics} in response to the {@link ApplicationReadyEvent}.
*
* @author Andy Wilkinson
* @since 1.1.0
*/
public class TomcatMetricsBinder implements ApplicationListener<ApplicationReadyEvent> {
private final MeterRegistry meterRegistry;
private final Iterable<Tag> tags;
public TomcatMetricsBinder(MeterRegistry meterRegistry) {
this(meterRegistry, Collections.emptyList());
}
public TomcatMetricsBinder(MeterRegistry meterRegistry, Iterable<Tag> tags) {
this.meterRegistry = meterRegistry;
this.tags = tags;
}
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
ApplicationContext applicationContext = event.getApplicationContext();
Manager manager = findManager(applicationContext);
new TomcatMetrics(manager, this.tags).bindTo(this.meterRegistry);
}
private Manager findManager(ApplicationContext applicationContext) {
if (applicationContext instanceof EmbeddedWebApplicationContext) {
EmbeddedServletContainer container = ((EmbeddedWebApplicationContext) applicationContext).getEmbeddedServletContainer();
if (container instanceof TomcatEmbeddedServletContainer) {
Context context = findContext((TomcatEmbeddedServletContainer) container);
if (context != null) {
return context.getManager();
}
}
}
return null;
}
private Context findContext(TomcatEmbeddedServletContainer tomcatWebServer) {
for (Container container : tomcatWebServer.getTomcat().getHost().findChildren()) {
if (container instanceof Context) {
return (Context) container;
}
}
return null;
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-k8s-metrics-starter/0.2.0/ai/foremast/metrics/k8s
|
java-sources/ai/foremast/metrics/foremast-spring-boot-k8s-metrics-starter/0.2.0/ai/foremast/metrics/k8s/starter/ActuatorSecurityConfig.java
|
package ai.foremast.metrics.k8s.starter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@Order(101)
@EnableConfigurationProperties({K8sMetricsProperties.class})
@ConditionalOnClass(AuthenticationManager.class)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private K8sMetricsProperties k8sMetricsProperties;
/*
This spring security configuration does the following
1. Allow access to specific APIs (/info /health /prometheus).
2. Allow access to "/actuator/k8s-metrics/*"
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
if (k8sMetricsProperties.isDisableCsrf()) {
http.csrf().disable();
}
http.authorizeRequests()
.antMatchers("/actuator/info", "/actuator/health", "/actuator/prometheus", "/metrics", "/actuator/k8s-metrics/*")
.permitAll();
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-k8s-metrics-starter/0.2.0/ai/foremast/metrics/k8s
|
java-sources/ai/foremast/metrics/foremast-spring-boot-k8s-metrics-starter/0.2.0/ai/foremast/metrics/k8s/starter/ActuatorSecurityFluxConfig.java
|
package ai.foremast.metrics.k8s.starter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers;
@Configuration
@Order(101)
@EnableConfigurationProperties({K8sMetricsProperties.class})
@ConditionalOnClass(AuthenticationManager.class)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
public class ActuatorSecurityFluxConfig {
@Autowired
private K8sMetricsProperties k8sMetricsProperties;
/*
This spring security configuration does the following
1. Allow access to specific APIs (/info /health /prometheus).
2. Allow access to "/actuator/k8s-metrics/*"
*/
@Bean
public SecurityWebFilterChain apiHttpSecurity(
ServerHttpSecurity http) {
if (k8sMetricsProperties.isDisableCsrf()) {
http.csrf().disable();
}
http.securityMatcher(ServerWebExchangeMatchers.pathMatchers("/actuator/info", "/actuator/health", "/actuator/prometheus", "/metrics", "/actuator/k8s-metrics/*"))
.authorizeExchange().anyExchange().permitAll();
return http.build();
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-k8s-metrics-starter/0.2.0/ai/foremast/metrics/k8s
|
java-sources/ai/foremast/metrics/foremast-spring-boot-k8s-metrics-starter/0.2.0/ai/foremast/metrics/k8s/starter/CallerWebFluxTagsProvider.java
|
package ai.foremast.metrics.k8s.starter;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.springframework.boot.actuate.metrics.web.reactive.server.WebFluxTagsProvider;
import org.springframework.boot.actuate.metrics.web.reactive.server.WebFluxTags;
import org.springframework.web.server.ServerWebExchange;
public class CallerWebFluxTagsProvider implements WebFluxTagsProvider {
private static final Tag CALLER_UNKNOWN = Tag.of("caller", "UNKNOWN");
private String headerName;
public CallerWebFluxTagsProvider(String headerName) {
this.headerName = headerName;
}
public Tag caller(ServerWebExchange exchange) {
if (exchange != null) {
String header = exchange.getRequest().getHeaders().getFirst((headerName));
return header != null ? Tag.of("caller", header.trim()) : CALLER_UNKNOWN;
}
return CALLER_UNKNOWN;
}
@Override
public Iterable<Tag> httpRequestTags(ServerWebExchange exchange, Throwable ex) {
return Tags.of(new Tag[]{WebFluxTags.method(exchange), WebFluxTags.uri(exchange), WebFluxTags.exception(ex), WebFluxTags.status(exchange), caller(exchange)});
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-k8s-metrics-starter/0.2.0/ai/foremast/metrics/k8s
|
java-sources/ai/foremast/metrics/foremast-spring-boot-k8s-metrics-starter/0.2.0/ai/foremast/metrics/k8s/starter/CallerWebMvcTagsProvider.java
|
package ai.foremast.metrics.k8s.starter;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import org.springframework.boot.actuate.metrics.web.servlet.WebMvcTags;
import org.springframework.boot.actuate.metrics.web.servlet.WebMvcTagsProvider;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CallerWebMvcTagsProvider implements WebMvcTagsProvider {
private static final Tag CALLER_UNKNOWN = Tag.of("caller", "UNKNOWN");
private String headerName;
public CallerWebMvcTagsProvider(String headerName) {
this.headerName = headerName;
}
public Tag caller(HttpServletRequest request) {
if (request != null) {
String header = request.getHeader(headerName);
return header != null ? Tag.of("caller", header.trim()) : CALLER_UNKNOWN;
}
return CALLER_UNKNOWN;
}
@Override
public Iterable<Tag> getTags(HttpServletRequest request, HttpServletResponse response, Object handler, Throwable exception) {
return Tags.of(new Tag[]{WebMvcTags.method(request), WebMvcTags.uri(request, response), WebMvcTags.exception(exception), WebMvcTags.status(response), caller(request)});
}
@Override
public Iterable<Tag> getLongRequestTags(HttpServletRequest request, Object handler) {
return Tags.of(new Tag[]{WebMvcTags.method(request), WebMvcTags.uri(request, (HttpServletResponse)null), caller(request)});
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-k8s-metrics-starter/0.2.0/ai/foremast/metrics/k8s
|
java-sources/ai/foremast/metrics/foremast-spring-boot-k8s-metrics-starter/0.2.0/ai/foremast/metrics/k8s/starter/CommonMetricsFilter.java
|
/**
* Licensed to the Foremast 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 ai.foremast.metrics.k8s.starter;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.config.MeterFilter;
import io.micrometer.core.instrument.config.MeterFilterReply;
import org.springframework.boot.actuate.autoconfigure.metrics.MetricsProperties;
import org.springframework.util.StringUtils;
import java.util.*;
import java.util.function.Supplier;
/**
* Common Metrics Filter is to hide the metrics by default, and show the metrics what are in the whitelist.
*
* If the metric is enabled in properties, keep it enabled.
* If the metric is disabled in properties, keep it disabled.
* If the metric starts with "PREFIX", enable it. otherwise disable the metric
*
* @author Sheldon Shao
* @version 1.0
*/
public class CommonMetricsFilter implements MeterFilter {
private MetricsProperties properties;
private String[] prefixes = new String[] {};
private LinkedHashMap<String, String> tagRules = new LinkedHashMap<>();
private Set<String> whitelist = new HashSet<>();
private Set<String> blacklist = new HashSet<>();
private K8sMetricsProperties k8sMetricsProperties;
public CommonMetricsFilter(K8sMetricsProperties k8sMetricsProperties, MetricsProperties properties) {
this.properties = properties;
this.k8sMetricsProperties = k8sMetricsProperties;
String list = k8sMetricsProperties.getCommonMetricsBlacklist();
if (list != null && !list.isEmpty()) {
String[] array = StringUtils.tokenizeToStringArray(list, ",", true, true);
for(String str: array) {
str = filter(str.trim());
blacklist.add(str);
}
}
list = k8sMetricsProperties.getCommonMetricsWhitelist();
if (list != null && !list.isEmpty()) {
String[] array = StringUtils.tokenizeToStringArray(list, ",", true, true);
for(String str: array) {
str = filter(str.trim());
whitelist.add(str);
}
}
list = k8sMetricsProperties.getCommonMetricsPrefix();
if (list != null && !list.isEmpty()) {
prefixes = StringUtils.tokenizeToStringArray(list, ",", true, true);
}
String tagRuleExpressions = k8sMetricsProperties.getCommonMetricsTagRules();
if (tagRuleExpressions != null) {
String[] array = StringUtils.tokenizeToStringArray(tagRuleExpressions, ",", true, true);
for(String str: array) {
str = str.trim();
String[] nameAndValue = str.split(":");
if (nameAndValue == null || nameAndValue.length != 2) {
throw new IllegalStateException("Invalid common tag name value pair:" + str);
}
tagRules.put(nameAndValue[0].trim(), nameAndValue[1].trim());
}
}
}
/**
* Filter for "[PREFIX]_*"
*
* @param id
* @return MeterFilterReply
*/
public MeterFilterReply accept(Meter.Id id) {
if (!k8sMetricsProperties.isEnableCommonMetricsFilter()) {
return MeterFilter.super.accept(id);
}
String metricName = id.getName();
Boolean enabled = lookupWithFallbackToAll(this.properties.getEnable(), id, null);
if (enabled != null) {
return enabled ? MeterFilterReply.NEUTRAL : MeterFilterReply.DENY;
}
if (whitelist.contains(metricName)) {
return MeterFilterReply.NEUTRAL;
}
if (blacklist.contains(metricName)) {
return MeterFilterReply.DENY;
}
for(String prefix: prefixes) {
if (metricName.startsWith(prefix)) {
return MeterFilterReply.ACCEPT;
}
}
for(String key: tagRules.keySet()) {
String expectedValue = tagRules.get(key);
if (expectedValue != null) {
if (expectedValue.equals(id.getTag(key))) {
return MeterFilterReply.ACCEPT;
}
}
}
return MeterFilterReply.DENY;
}
protected String filter(String metricName) {
return metricName.replace('_', '.');
}
public void enableMetric(String metricName) {
metricName = filter(metricName);
if (blacklist.contains(metricName)) {
blacklist.remove(metricName);
}
if (!whitelist.contains(metricName)) {
whitelist.add(metricName);
}
}
public void disableMetric(String metricName) {
metricName = filter(metricName);
if (whitelist.contains(metricName)) {
whitelist.remove(metricName);
}
if (!blacklist.contains(metricName)) {
blacklist.add(metricName);
}
}
private <T> T lookup(Map<String, T> values, Meter.Id id, T defaultValue) {
if (values.isEmpty()) {
return defaultValue;
}
return doLookup(values, id, () -> defaultValue);
}
private <T> T lookupWithFallbackToAll(Map<String, T> values, Meter.Id id, T defaultValue) {
if (values.isEmpty()) {
return defaultValue;
}
return doLookup(values, id, () -> values.getOrDefault("all", defaultValue));
}
private <T> T doLookup(Map<String, T> values, Meter.Id id, Supplier<T> defaultValue) {
String name = id.getName();
while (name != null && !name.isEmpty()) {
T result = values.get(name);
if (result != null) {
return result;
}
int lastDot = name.lastIndexOf('.');
name = (lastDot != -1) ? name.substring(0, lastDot) : "";
}
return defaultValue.get();
}
public String[] getPrefixes() {
return prefixes;
}
public void setPrefixes(String[] prefixes) {
this.prefixes = prefixes;
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-k8s-metrics-starter/0.2.0/ai/foremast/metrics/k8s
|
java-sources/ai/foremast/metrics/foremast-spring-boot-k8s-metrics-starter/0.2.0/ai/foremast/metrics/k8s/starter/ExposePrometheusAutoConfiguration.java
|
package ai.foremast.metrics.k8s.starter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.util.Set;
@Configuration
@AutoConfigureBefore(WebEndpointAutoConfiguration.class)
@EnableConfigurationProperties({WebEndpointProperties.class})
public class ExposePrometheusAutoConfiguration {
@Autowired
WebEndpointProperties webEndpointProperties;
@PostConstruct
public void enablePrometheus() {
if (webEndpointProperties != null) {
Set<String> set = webEndpointProperties.getExposure().getInclude();
if (set.isEmpty()) { //Default
set.add("info");
set.add("health");
}
set.add("prometheus");
set.add("k8s-metrics");
}
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-k8s-metrics-starter/0.2.0/ai/foremast/metrics/k8s
|
java-sources/ai/foremast/metrics/foremast-spring-boot-k8s-metrics-starter/0.2.0/ai/foremast/metrics/k8s/starter/K8sMetricsAutoConfiguration.java
|
package ai.foremast.metrics.k8s.starter;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.boot.actuate.autoconfigure.metrics.MetricsProperties;
import org.springframework.boot.actuate.metrics.web.reactive.server.DefaultWebFluxTagsProvider;
import org.springframework.boot.actuate.metrics.web.reactive.server.WebFluxTagsProvider;
import org.springframework.boot.actuate.metrics.web.servlet.DefaultWebMvcTagsProvider;
import org.springframework.boot.actuate.metrics.web.servlet.WebMvcTagsProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.regex.Pattern;
/**
* Auto metrics configurations
*/
@Configuration
@EnableConfigurationProperties({K8sMetricsProperties.class, MetricsProperties.class})
public class K8sMetricsAutoConfiguration implements MeterRegistryCustomizer {
@Autowired
K8sMetricsProperties metricsProperties;
@Autowired
ConfigurableApplicationContext appContext;
private static final String HTTP_SERVER_REQUESTS = "http.server.requests";
private K8sMetricsEndpoint k8sMetricsEndpoint;
private CommonMetricsFilter commonMetricsFilter;
@Bean
public K8sMetricsEndpoint k8sMetricsEndpoint() {
k8sMetricsEndpoint = new K8sMetricsEndpoint();
if (commonMetricsFilter != null) {
k8sMetricsEndpoint.setCommonMetricsFilter(commonMetricsFilter);
}
return k8sMetricsEndpoint;
}
@Bean
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public WebMvcTagsProvider serviceCallerTag() {
if (metricsProperties.hasCaller()) {
return new CallerWebMvcTagsProvider(metricsProperties.getCallerHeader());
}
else {
return new DefaultWebMvcTagsProvider();
}
}
@Bean
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
public WebFluxTagsProvider serviceFluxCallerTag() {
if (metricsProperties.hasCaller()) {
return new CallerWebFluxTagsProvider(metricsProperties.getCallerHeader());
}
else {
return new DefaultWebFluxTagsProvider();
}
}
@Bean
public CommonMetricsFilter commonMetricsFilter(MetricsProperties properties) {
commonMetricsFilter = new CommonMetricsFilter(metricsProperties, properties);
if (k8sMetricsEndpoint != null) {
k8sMetricsEndpoint.setCommonMetricsFilter(commonMetricsFilter);
}
return commonMetricsFilter;
}
@Override
public void customize(MeterRegistry registry) {
String commonTagNameValuePair = metricsProperties.getCommonTagNameValuePairs();
if (commonTagNameValuePair != null && !commonTagNameValuePair.isEmpty()) {
String[] pairs = commonTagNameValuePair.split(",");
for(String p : pairs) {
String[] nameAndValue = p.split(":");
if (nameAndValue == null || nameAndValue.length != 2) {
throw new IllegalStateException("Invalid common tag name value pair:" + p);
}
String valuePattern = nameAndValue[1];
int sepIndex = valuePattern.indexOf('|');
String[] patterns = null;
if (sepIndex > 0) {
patterns = valuePattern.split(Pattern.quote("|"));
}
else {
patterns = new String[] { valuePattern };
}
for(int i = 0; i < patterns.length; i ++) {
String value = null;
if (patterns[i].startsWith("ENV.")) {
value = System.getenv(patterns[i].substring(4));
}
else {
value = System.getProperty(patterns[i]);
if ((value == null || value.isEmpty()) && appContext != null) {
value = appContext.getEnvironment().getProperty(patterns[i]);
}
}
if (value != null && !value.isEmpty()) {
registry.config().commonTags(nameAndValue[0], value);
break;
}
}
}
}
String statuses = metricsProperties.getInitializeForStatuses();
if (statuses != null || !statuses.isEmpty()) {
String[] statusCodes = statuses.split(",");
for(String code: statusCodes) {
if (metricsProperties.hasCaller()) {
registry.timer(HTTP_SERVER_REQUESTS, "exception", "None", "method", "GET", "status", code, "uri", "/**", "caller", "*");
}
else {
registry.timer(HTTP_SERVER_REQUESTS, "exception", "None", "method", "GET", "status", code, "uri", "/**");
}
}
}
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-k8s-metrics-starter/0.2.0/ai/foremast/metrics/k8s
|
java-sources/ai/foremast/metrics/foremast-spring-boot-k8s-metrics-starter/0.2.0/ai/foremast/metrics/k8s/starter/K8sMetricsEndpoint.java
|
package ai.foremast.metrics.k8s.starter;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.annotation.Selector;
import org.springframework.boot.actuate.endpoint.web.annotation.WebEndpoint;
/**
*
*
* /k8s-metrics/enable/sample_metric_name
* /k8s-metrics/disable/sample_metric_name
*
*/
@WebEndpoint(
id = "k8s-metrics"
)
public class K8sMetricsEndpoint {
private CommonMetricsFilter commonMetricsFilter;
@ReadOperation(
produces = {"text/plain; version=0.1.4; charset=utf-8"}
)
public String action(@Selector String action, @Selector String metricName) {
if (commonMetricsFilter != null) {
if ("enable".equalsIgnoreCase(action)) {
commonMetricsFilter.enableMetric(metricName);
}
else if ("disable".equalsIgnoreCase(action)) {
commonMetricsFilter.disableMetric(metricName);
}
}
return "OK";
}
public CommonMetricsFilter getCommonMetricsFilter() {
return commonMetricsFilter;
}
public void setCommonMetricsFilter(CommonMetricsFilter commonMetricsFilter) {
this.commonMetricsFilter = commonMetricsFilter;
}
}
|
0
|
java-sources/ai/foremast/metrics/foremast-spring-boot-k8s-metrics-starter/0.2.0/ai/foremast/metrics/k8s
|
java-sources/ai/foremast/metrics/foremast-spring-boot-k8s-metrics-starter/0.2.0/ai/foremast/metrics/k8s/starter/K8sMetricsProperties.java
|
package ai.foremast.metrics.k8s.starter;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "k8s.metrics")
public class K8sMetricsProperties {
private String commonTagNameValuePairs = "app:ENV.APP_NAME|info.app.name";
private String initializeForStatuses = "403,404,501,502";
public static final String APP_ASSET_ALIAS_HEADER = "X-CALLER";
private String callerHeader = APP_ASSET_ALIAS_HEADER;
private boolean disableCsrf = false;
private boolean enableCommonMetricsFilter = false;
private String commonMetricsWhitelist = null;
private String commonMetricsBlacklist = null;
private String commonMetricsPrefix = null;
private String commonMetricsTagRules = null;
public String getInitializeForStatuses() {
return initializeForStatuses;
}
public void setInitializeForStatuses(String initializeForStatuses) {
this.initializeForStatuses = initializeForStatuses;
}
public String getCommonTagNameValuePairs() {
return commonTagNameValuePairs;
}
public void setCommonTagNameValuePairs(String commonTagNameValuePairs) {
this.commonTagNameValuePairs = commonTagNameValuePairs;
}
public String getCallerHeader() {
return callerHeader;
}
public boolean hasCaller() {
return callerHeader != null && !callerHeader.isEmpty();
}
public void setCallerHeader(String callerHeader) {
this.callerHeader = callerHeader;
}
public boolean isDisableCsrf() {
return disableCsrf;
}
public void setDisableCsrf(boolean disableCsrf) {
this.disableCsrf = disableCsrf;
}
public boolean isEnableCommonMetricsFilter() {
return enableCommonMetricsFilter;
}
public void setEnableCommonMetricsFilter(boolean enableCommonMetricsFilter) {
this.enableCommonMetricsFilter = enableCommonMetricsFilter;
}
public String getCommonMetricsWhitelist() {
return commonMetricsWhitelist;
}
public void setCommonMetricsWhitelist(String commonMetricsWhitelist) {
this.commonMetricsWhitelist = commonMetricsWhitelist;
}
public String getCommonMetricsBlacklist() {
return commonMetricsBlacklist;
}
public void setCommonMetricsBlacklist(String commonMetricsBlacklist) {
this.commonMetricsBlacklist = commonMetricsBlacklist;
}
public String getCommonMetricsPrefix() {
return commonMetricsPrefix;
}
public void setCommonMetricsPrefix(String commonMetricsPrefix) {
this.commonMetricsPrefix = commonMetricsPrefix;
}
public String getCommonMetricsTagRules() {
return commonMetricsTagRules;
}
public void setCommonMetricsTagRules(String commonMetricsTagRules) {
this.commonMetricsTagRules = commonMetricsTagRules;
}
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/config/FoxPayAutoConfiguration.java
|
package foxpay.api.config;
import foxpay.api.config.properties.FoxPayConfigProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("foxpay.api")
@EnableConfigurationProperties(value = {FoxPayConfigProperties.class})
public class FoxPayAutoConfiguration {
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/config
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/config/properties/FoxPayConfigProperties.java
|
package foxpay.api.config.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.io.Serializable;
@Data
@Component
@ConfigurationProperties(prefix = "fox.pay")
public class FoxPayConfigProperties implements Serializable {
/**
* 客户端身份标识
*/
private String appId;
/**
* 私钥加密(默认方式)
*/
private String privateKey;
/**
* 私钥文件地址
*/
private String privateKeyFile;
/**
* 公钥验签(默认方式)
*/
private String publicKey;
/**
* 公钥文件地址
*/
private String publicKeyFile;
/**
* 请求url
*/
private String url ;
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/constants/FoxPayHeaderConstant.java
|
package foxpay.api.constants;
public interface FoxPayHeaderConstant {
/**
* 客户端身份标识
*/
String appId = "app_id";
/**
* 签名
*/
String sign = "sign";
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/dto/OrderCloseDTO.java
|
package foxpay.api.dto;
import lombok.Data;
@Data
public class OrderCloseDTO {
/**
* 流水号
*/
private String trade_no;
/**
* 商户订单号
*/
private String order_no;
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/dto/OrderCreateDTO.java
|
package foxpay.api.dto;
import foxpay.api.enums.LocaleEnum;
import lombok.Data;
import java.io.Serializable;
@Data
public class OrderCreateDTO implements Serializable {
/**
* 商户订单标题
*/
private String subject;
/**
* 商户订单号
*/
private String order_no;
/**
* 数量
*/
private String amount;
/**
* 回调地址
*/
private String notify_url;
/**
* 订单支付成功重定向地址
*/
private String redirect_url;
/**
* 超时时间(秒) 默认30秒
*/
private Long time_out = 30L;
/**
* LocaleEnum
* 国际化:中文简体(zh-CN),中文繁体(zh-TW),英文(en-US),日文(ja-JP)
*/
private String locale = LocaleEnum.ZH_TW.getLocale();
/**
* 备注
*/
private String remark;
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/dto/OrderQueryDTO.java
|
package foxpay.api.dto;
import lombok.Data;
@Data
public class OrderQueryDTO {
/**
* 流水号
*/
private String trade_no;
/**
* 商户订单号
*/
private String order_no;
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/dto/TransDTO.java
|
package foxpay.api.dto;
import lombok.Data;
@Data
public class TransDTO {
/**
* 交易凭证
*/
private String trans_token;
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/dto/TransPrepareDTO.java
|
package foxpay.api.dto;
import lombok.Data;
@Data
public class TransPrepareDTO {
/**
* 商户订单号
*/
private String order_no;
/**
* 收款金额
*/
private String amount;
/**
* 提现地址
*/
private String to_address;
/**
* 回调通知地址
*/
private String notify_url;
/**
* 备注
*/
private String remark;
/**
* 手续费方式:2 交易金额 3 账户余额
*/
private String gas_type;
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/dto/TransQueryDTO.java
|
package foxpay.api.dto;
import lombok.Data;
@Data
public class TransQueryDTO {
/**
* 流水号
*/
private String trade_no;
/**
* 商户订单号
*/
private String order_no;
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/enums/CodeEnum.java
|
package foxpay.api.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* code enum
*/
@Getter
@AllArgsConstructor
public enum CodeEnum {
SUCCESS(10000, "success"),
CONFIG_NOT_NULL(61000, "Configuration cannot be empty"),
PARAM_NOT_NULL(61001, "The request parameter object cannot be empty"),
RESPONSE_SIGN_ERROR(61002, "Response signature exception"),
REQUEST_SIGN_ERROR(61003, "Request signature exception"),
PARAM_ERROR(61004, "Parameter exception:{}"),
CONFIG_ERROR(61005, "Configuration exception:{}"),
FILE_ERROR(61006, "Reading file exception"),
;
private final int code;
private final String message;
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/enums/FoxPayUrlEnum.java
|
package foxpay.api.enums;
import cn.hutool.http.Method;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 枚举
*/
@Getter
@AllArgsConstructor
public enum FoxPayUrlEnum {
/**
* 创建订单
*/
ORDER_CREATE("/sdk/application/createApplicationOrder", Method.POST),
/**
* 查询订单
*/
ORDER_QUERY("/sdk/application/getApplicationOrder", Method.POST),
/**
* 关闭订单
*/
CLOSE_ORDER("/sdk/application/closeApplicationOrder", Method.POST),
/**
* 查询商户资产
*/
GET_BALANCE("/sdk/application/getBalance", Method.GET),
/**
* 提现获取凭证
*/
TRANS_PREPARE("/sdk/application/transPrepare", Method.POST),
/**
* 确认提现
*/
TRANS("/sdk/application/trans", Method.POST),
/**
* 查询提现订单
*/
GET_TRANS("/sdk/application/getTrans", Method.POST);
private final String url;
private final Method method;
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/enums/LocaleEnum.java
|
package foxpay.api.enums;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 异常枚举
*/
@Getter
@AllArgsConstructor
public enum LocaleEnum {
ZH_CN("zh-CN", "中文简体"),
ZH_TW("zh-TW", "中文繁体"),
EN_US("en-US", "英文"),
JA_JP("ja-JP", "日文"),
;
private final String locale;
private final String message;
@JSONField
public String getLocale() {
return locale;
}
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/exception/FoxPayException.java
|
package foxpay.api.exception;
import cn.hutool.core.util.StrUtil;
import foxpay.api.enums.CodeEnum;
import lombok.Data;
@Data
public class FoxPayException extends RuntimeException {
/**
* 状态码
*/
private Integer code;
/**
* 错误信息
*/
private String msg;
public FoxPayException(Integer code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
public FoxPayException(CodeEnum codeEnum) {
super(codeEnum.getMessage());
this.code = codeEnum.getCode();
this.msg = codeEnum.getMessage();
}
public FoxPayException(CodeEnum codeEnum, String msg) {
super(StrUtil.format(codeEnum.getMessage(),msg));
this.code = codeEnum.getCode();
this.msg = StrUtil.format(codeEnum.getMessage(),msg);
}
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/result/FoxPayResult.java
|
package foxpay.api.result;
import lombok.Data;
import java.io.Serializable;
@Data
public class FoxPayResult implements Serializable {
private int code;
private String message;
private String data;
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/result/FoxPayVO.java
|
package foxpay.api.result;
import lombok.Data;
import java.io.Serializable;
@Data
public class FoxPayVO implements Serializable {
private int code;
private String message;
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/service/FoxOrderService.java
|
package foxpay.api.service;
import foxpay.api.dto.*;
import foxpay.api.result.FoxPayResult;
import foxpay.api.vo.*;
public interface FoxOrderService {
/**
* 创建订单
*/
OrderCreateVO orderCreate(OrderCreateDTO dto);
/**
* 查询订单
*/
OrderQueryVO orderQuery(OrderQueryDTO dto);
/**
* 关闭订单
*/
FoxPayResult orderClose(OrderCloseDTO dto);
/**
* 查询资产
*/
BalanceQueryVO balanceQuery();
/**
* 提现获取凭证
*/
TransPrepareVO transPrepare(TransPrepareDTO dto);
/**
* 确认提现
*/
TransVO trans(TransDTO dto);
/**
* 查询提现记录
*/
TransQueryVO getTrans(TransQueryDTO dto);
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/service
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/service/impl/FoxOrderServiceImpl.java
|
package foxpay.api.service.impl;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import foxpay.api.config.properties.FoxPayConfigProperties;
import foxpay.api.dto.*;
import foxpay.api.enums.CodeEnum;
import foxpay.api.enums.FoxPayUrlEnum;
import foxpay.api.exception.FoxPayException;
import foxpay.api.result.FoxPayResult;
import foxpay.api.service.FoxOrderService;
import foxpay.api.util.FoxPayRequestUtil;
import foxpay.api.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
@Slf4j
@Service
public class FoxOrderServiceImpl implements FoxOrderService {
@Autowired
private FoxPayConfigProperties foxPayConfigProperties;
/**
* 创建订单
*/
@Override
public OrderCreateVO orderCreate(OrderCreateDTO dto) {
if (dto == null) {
throw new FoxPayException(CodeEnum.PARAM_NOT_NULL);
}
if (StrUtil.isBlank(dto.getOrder_no())) {
throw new FoxPayException(CodeEnum.PARAM_ERROR, "order_no");
}
if (StrUtil.isBlank(dto.getSubject())) {
throw new FoxPayException(CodeEnum.PARAM_ERROR, "subject");
}
if (StrUtil.isBlank(dto.getAmount()) || !NumberUtil.isNumber(dto.getAmount())) {
throw new FoxPayException(CodeEnum.PARAM_ERROR, "amount");
}
BigDecimal amount = NumberUtil.toBigDecimal(dto.getAmount());
if (amount.scale() > 2) {
throw new FoxPayException(CodeEnum.PARAM_ERROR, "amount");
}
if (amount.compareTo(BigDecimal.ZERO) < 0) {
throw new FoxPayException(CodeEnum.PARAM_ERROR, "amount");
}
FoxPayResult foxPay = FoxPayRequestUtil.orderRequest(FoxPayUrlEnum.ORDER_CREATE, dto, foxPayConfigProperties);
OrderCreateVO result = new OrderCreateVO();
if (StrUtil.isNotBlank(foxPay.getData())) {
result = JSON.parseObject(foxPay.getData(), OrderCreateVO.class);
}
result.setCode(foxPay.getCode());
result.setMessage(foxPay.getMessage());
return result;
}
/**
* 查询订单
*/
@Override
public OrderQueryVO orderQuery(OrderQueryDTO dto) {
if (dto == null) {
throw new FoxPayException(CodeEnum.PARAM_NOT_NULL);
}
if (StrUtil.isBlank(dto.getOrder_no()) && StrUtil.isBlank(dto.getTrade_no())) {
throw new FoxPayException(CodeEnum.PARAM_NOT_NULL);
}
FoxPayResult foxPay = FoxPayRequestUtil.orderRequest(FoxPayUrlEnum.ORDER_QUERY, dto, foxPayConfigProperties);
OrderQueryVO result = new OrderQueryVO();
if (StrUtil.isNotBlank(foxPay.getData())) {
result = JSON.parseObject(foxPay.getData(), OrderQueryVO.class);
}
result.setCode(foxPay.getCode());
result.setMessage(foxPay.getMessage());
return result;
}
/**
* 关闭订单
*/
@Override
public FoxPayResult orderClose(OrderCloseDTO dto) {
if (dto == null) {
throw new FoxPayException(CodeEnum.PARAM_NOT_NULL);
}
if (StrUtil.isBlank(dto.getOrder_no()) && StrUtil.isBlank(dto.getTrade_no())) {
throw new FoxPayException(CodeEnum.PARAM_NOT_NULL);
}
return FoxPayRequestUtil.orderRequest(FoxPayUrlEnum.CLOSE_ORDER, dto, foxPayConfigProperties);
}
/**
* 查询资产
*/
@Override
public BalanceQueryVO balanceQuery() {
FoxPayResult foxPay = FoxPayRequestUtil.orderRequest(FoxPayUrlEnum.GET_BALANCE, null, foxPayConfigProperties);
BalanceQueryVO result = new BalanceQueryVO();
if (StrUtil.isNotBlank(foxPay.getData())) {
result = JSON.parseObject(foxPay.getData(), BalanceQueryVO.class);
}
result.setCode(foxPay.getCode());
result.setMessage(foxPay.getMessage());
return result;
}
/**
* 提现获取凭证
*/
@Override
public TransPrepareVO transPrepare(TransPrepareDTO dto) {
if (dto == null) {
throw new FoxPayException(CodeEnum.PARAM_NOT_NULL);
}
if (StrUtil.isBlank(dto.getOrder_no())) {
throw new FoxPayException(CodeEnum.PARAM_ERROR, "order_no");
}
if (StrUtil.isBlank(dto.getTo_address())) {
throw new FoxPayException(CodeEnum.PARAM_ERROR, "to_address");
}
if (StrUtil.isBlank(dto.getGas_type())) {
throw new FoxPayException(CodeEnum.PARAM_ERROR, "gas_type");
}
if (StrUtil.isBlank(dto.getAmount()) || !NumberUtil.isNumber(dto.getAmount())) {
throw new FoxPayException(CodeEnum.PARAM_ERROR, "amount");
}
BigDecimal amount = NumberUtil.toBigDecimal(dto.getAmount());
if (amount.scale() > 2) {
throw new FoxPayException(CodeEnum.PARAM_ERROR, "amount");
}
if (amount.compareTo(BigDecimal.ZERO) < 0) {
throw new FoxPayException(CodeEnum.PARAM_ERROR, "amount");
}
FoxPayResult foxPay = FoxPayRequestUtil.orderRequest(FoxPayUrlEnum.TRANS_PREPARE, dto, foxPayConfigProperties);
TransPrepareVO result = new TransPrepareVO();
if (StrUtil.isNotBlank(foxPay.getData())) {
result = JSON.parseObject(foxPay.getData(), TransPrepareVO.class);
}
result.setCode(foxPay.getCode());
result.setMessage(foxPay.getMessage());
return result;
}
/**
* 确认提现
*/
@Override
public TransVO trans(TransDTO dto) {
if (dto == null) {
throw new FoxPayException(CodeEnum.PARAM_NOT_NULL);
}
if (StrUtil.isBlank(dto.getTrans_token())) {
throw new FoxPayException(CodeEnum.PARAM_ERROR, "trans_token");
}
FoxPayResult foxPay = FoxPayRequestUtil.orderRequest(FoxPayUrlEnum.TRANS, dto, foxPayConfigProperties);
TransVO result = new TransVO();
if (StrUtil.isNotBlank(foxPay.getData())) {
result = JSON.parseObject(foxPay.getData(), TransVO.class);
}
result.setCode(foxPay.getCode());
result.setMessage(foxPay.getMessage());
return result;
}
/**
* 查询提现记录
*/
@Override
public TransQueryVO getTrans(TransQueryDTO dto) {
if (dto == null) {
throw new FoxPayException(CodeEnum.PARAM_NOT_NULL);
}
if (StrUtil.isBlank(dto.getOrder_no()) && StrUtil.isBlank(dto.getTrade_no())) {
throw new FoxPayException(CodeEnum.PARAM_NOT_NULL);
}
FoxPayResult foxPay = FoxPayRequestUtil.orderRequest(FoxPayUrlEnum.GET_TRANS, dto, foxPayConfigProperties);
TransQueryVO result = new TransQueryVO();
if (StrUtil.isNotBlank(foxPay.getData())) {
result = JSON.parseObject(foxPay.getData(), TransQueryVO.class);
}
result.setCode(foxPay.getCode());
result.setMessage(foxPay.getMessage());
return result;
}
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/util/FoxPayRequestUtil.java
|
package foxpay.api.util;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import foxpay.api.config.properties.FoxPayConfigProperties;
import foxpay.api.constants.FoxPayHeaderConstant;
import foxpay.api.enums.CodeEnum;
import foxpay.api.enums.FoxPayUrlEnum;
import foxpay.api.exception.FoxPayException;
import foxpay.api.result.FoxPayResult;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class FoxPayRequestUtil {
public static FoxPayResult orderRequest(FoxPayUrlEnum urlEnum, Object param, FoxPayConfigProperties config) {
if (StrUtil.isBlank(config.getAppId())) {
throw new FoxPayException(CodeEnum.CONFIG_ERROR, "appId");
}
if (StrUtil.isBlank(config.getUrl())) {
throw new FoxPayException(CodeEnum.CONFIG_ERROR, "url");
}
String privateKey = null;
String publicKey = null;
if (StrUtil.isNotBlank(config.getPublicKeyFile()) && StrUtil.isNotBlank(config.getPrivateKeyFile())) {
if (!config.getPublicKeyFile().endsWith(".pem") || !config.getPrivateKeyFile().endsWith(".pem")) {
throw new FoxPayException(CodeEnum.FILE_ERROR);
}
try {
FileReader publicFile = new FileReader(config.getPublicKeyFile());
publicKey = RSAExample.extractFromPem(publicFile.readString());
FileReader privateFile = new FileReader(config.getPrivateKeyFile());
privateKey = RSAExample.extractFromPem(privateFile.readString());
} catch (Exception e) {
throw new FoxPayException(CodeEnum.FILE_ERROR);
}
} else {
privateKey = config.getPrivateKey();
publicKey = config.getPublicKey();
}
if (StrUtil.isBlank(privateKey)) {
throw new FoxPayException(CodeEnum.CONFIG_ERROR, "privateKey");
}
if (StrUtil.isBlank(publicKey)) {
throw new FoxPayException(CodeEnum.CONFIG_ERROR, "publicKey");
}
return orderRequest(urlEnum, param, publicKey, privateKey, config);
}
public static FoxPayResult orderRequest(FoxPayUrlEnum urlEnum, Object param, String publicKey, String privateKey, FoxPayConfigProperties config) {
//请求头参数
Map<String, String> headerMap = new HashMap<String, String>();
headerMap.put(FoxPayHeaderConstant.appId, config.getAppId());
if (param != null) {
//加密请求参数
String requestParam = SecretSignUtil.sortParam(param);
try {
String sign = RSAExample.sign(requestParam.getBytes(), privateKey);
log.warn("request sign:{}", sign);
headerMap.put(FoxPayHeaderConstant.sign, sign);
} catch (Exception e) {
throw new FoxPayException(CodeEnum.REQUEST_SIGN_ERROR);
}
}
String url = config.getUrl() + urlEnum.getUrl();
url = URLUtil.normalize(url); //格式化url
HttpResponse result = null;
if (urlEnum.getMethod() == Method.GET) {
//构建请求参数
result = HttpRequest.get(url).headerMap(headerMap, true)
.form(BeanUtil.beanToMap(param, false, true))//body内容
.timeout(3000)//超时(毫秒)
.execute();
}
if (urlEnum.getMethod() == Method.POST) {
//构建请求参数
result = HttpRequest.post(url).headerMap(headerMap, true)
.body(JSON.toJSONString(param))//body内容
.timeout(3000)//超时(毫秒)
.execute();
}
log.warn("request URL:{}", url);
String body = result.body();
log.warn("response body:{}", body);
JSONObject object = JSON.parseObject(body);
String msg = object.getString("message");
Integer code = object.getInteger("code");
String data = object.getString("data");
if (code == CodeEnum.SUCCESS.getCode()) { //操作成功
if (ObjectUtil.isNotEmpty(data)) {
String responseSig = result.header(FoxPayHeaderConstant.sign); //响应签名
log.warn("response sig:{}", responseSig);
//校验响应签名
Map<String, Object> params = JSONObject.parseObject(data, new TypeReference<Map<String, Object>>() {
});
try {
boolean is = RSAExample.verify(SecretSignUtil.sortParam(params).getBytes(), responseSig.getBytes(), publicKey);
log.warn("verify response sig:{}", is);
if (!is) {
throw new FoxPayException(CodeEnum.RESPONSE_SIGN_ERROR);
}
} catch (Exception e) {
throw new FoxPayException(CodeEnum.RESPONSE_SIGN_ERROR);
}
}
}
FoxPayResult foxPay = new FoxPayResult();
foxPay.setMessage(msg);
foxPay.setCode(code);
foxPay.setData(data);
return foxPay;
}
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/util/HttpRequestUtil.java
|
package foxpay.api.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
public class HttpRequestUtil {
public static String post(String uri, Map<String, String> heard, String postData) throws Exception {
// 目标URL
URL url = new URL(uri);
// 创建连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置HTTP方法为POST
connection.setRequestMethod("POST");
// 设置请求头
connection.setRequestProperty("Content-Type", "application/json");
//添加请求头
for (String s : heard.keySet()) {
connection.setRequestProperty(s, heard.get(s));
}
// 开启输出流,用于发送POST请求的数据
connection.setDoOutput(true);
// 发送请求数据
try (OutputStream outputStream = connection.getOutputStream()) {
outputStream.write(postData.getBytes(StandardCharsets.UTF_8));
outputStream.flush();
}
// 发起请求并获取响应
int responseCode = connection.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuffer response = new StringBuffer();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 输出响应结果
System.out.println("Response Body: " + response.toString());
// 关闭连接
connection.disconnect();
return response.toString();
}
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/util/RSAExample.java
|
package foxpay.api.util;
import cn.hutool.core.io.file.FileReader;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class RSAExample {
// 签名
public static byte[] sign(byte[] data, PrivateKey privateKey) throws Exception {
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initSign(privateKey);
signature.update(data);
return signature.sign();
}
// 签名
public static String sign(byte[] data, String privateKeyStr) throws Exception {
byte[] byteKey = Base64.getDecoder().decode(privateKeyStr);
PKCS8EncodedKeySpec x509EncodedKeySpec = new PKCS8EncodedKeySpec(byteKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(x509EncodedKeySpec);
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initSign(privateKey);
signature.update(data);
return Base64.getEncoder().encodeToString(signature.sign());
}
// 验证签名
public static boolean verify(byte[] data, byte[] signature, PublicKey publicKey) throws Exception {
Signature verifier = Signature.getInstance("SHA1withRSA");
verifier.initVerify(publicKey);
verifier.update(data);
return verifier.verify(signature);
}
// 验证签名
public static boolean verify(byte[] data, byte[] signature, String publicKeyStr) throws Exception {
// Base64解码签名
byte[] signatureBytes = Base64.getDecoder().decode(signature);
// 创建公钥对象
byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyStr);
// 创建公钥对象
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
Signature verifier = Signature.getInstance("SHA1withRSA");
verifier.initVerify(publicKey);
verifier.update(data);
return verifier.verify(signatureBytes);
}
public static String extractFromPem(String privateKey) {
String pkcs1_begin = "-----BEGIN RSA PRIVATE KEY-----";
String pkcs1_end = "-----END RSA PRIVATE KEY-----";
String pkcs8_begin = "-----BEGIN PRIVATE KEY-----";
String pkcs8_end = "-----END PRIVATE KEY-----";
String pkcs1_pub_begin = "-----BEGIN RSA PUBLIC KEY-----";
String pkcs1_pub_end = "-----END RSA PUBLIC KEY-----";
String pkcs8_pub_begin = "-----BEGIN PUBLIC KEY-----";
String pkcs8_pub_end = "-----END PUBLIC KEY-----";
privateKey = privateKey.replace(pkcs1_begin, "");
privateKey = privateKey.replace(pkcs1_end, "");
privateKey = privateKey.replace(pkcs8_begin, "");
privateKey = privateKey.replace(pkcs8_end, "");
privateKey = privateKey.replace(pkcs1_pub_begin, "");
privateKey = privateKey.replace(pkcs1_pub_end, "");
privateKey = privateKey.replace(pkcs8_pub_begin, "");
privateKey = privateKey.replace(pkcs8_pub_end, "");
//去换行符空格
privateKey = privateKey.replaceAll("\\s+", "");
return privateKey;
}
public static void a() throws Exception {
// 生成RSA密钥对
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// 获取公钥和私钥
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// 要签名的数据
byte[] data = "Hello, World!".getBytes();
// 签名
byte[] signature = sign(data, privateKey);
// 验证签名
boolean isValid = verify(data, signature, publicKey);
System.out.println("Signature is valid? " + isValid);
}
public static void b() throws Exception {
FileReader publicFile = new FileReader("E:\\public.pem");
}
public static void main(String[] args) throws Exception{
b();
}
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/util/SecretSignUtil.java
|
package foxpay.api.util;
import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@Slf4j
public class SecretSignUtil {
/**
* 排序参数
*/
public static String sortParam(Map<String, Object> paramValues) {
StringBuilder stringBuilder = new StringBuilder();
List<String> keys = new ArrayList<String>(paramValues.keySet());
Collections.sort(keys);
int i = 0;
for (String key : keys) {
stringBuilder.append(key).append("=").append(paramValues.get(key).toString());
if (i != keys.size() - 1) {
stringBuilder.append("&");
}
i++;
}
log.warn("sort:{}", stringBuilder);
return stringBuilder.toString();
}
/**
* 排序参数
*/
public static String sortParam(Object obj) {
Map<String, Object> paramValues = BeanUtil.beanToMap(obj, false, true);
return sortParam(paramValues);
}
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/vo/BalanceQueryVO.java
|
package foxpay.api.vo;
import foxpay.api.result.FoxPayVO;
import lombok.Data;
/**
* sdk订单信息
*/
@Data
public class BalanceQueryVO extends FoxPayVO {
/**
* erc20地址
*/
private String erc20_address;
/**
* trc20地址
*/
private String trc20_address;
/**
* 可用资产
*/
private String money;
/**
* 交易冻结资产
*/
private String trans_freeze_money;
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/vo/OrderCreateVO.java
|
package foxpay.api.vo;
import foxpay.api.result.FoxPayVO;
import lombok.Data;
@Data
public class OrderCreateVO extends FoxPayVO {
/**
* 流水号
*/
private String trade_no;
/**
* 订单状态:1等待支付 2支付成功 3交易失败 4交易超时
*/
private Integer status;
/**
* eth收款地址
*/
private String eth_address;
/**
* tron收款地址
*/
private String tron_address;
/**
* 商户订单标题
*/
private String subject;
/**
* 商户订单号
*/
private String order_no;
/**
* 订单回调地址
*/
private String notify_url;
/**
* 支付地址
*/
private String pay_url;
/**
* 订单支付成功重定向地址
*/
private String redirect_url;
/**
* 超时时间(秒)
*/
private Long time_out;
/**
* 数量
*/
private String amount;
/**
* 备注
*/
private String remark;
/**
* 国际化:中文简体(zh-CN),中文繁体(zh-TW),英文(en-US),日文(ja-JP)
*/
private String locale;
/**
* 过期时间
*/
private Long expire_time;
/**
* 创建时间
*/
private Long create_time;
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/vo/OrderQueryVO.java
|
package foxpay.api.vo;
import foxpay.api.result.FoxPayVO;
import lombok.Data;
@Data
public class OrderQueryVO extends FoxPayVO {
/**
* 流水号
*/
private String trade_no;
/**
* 订单状态:1等待支付 2支付成功 3交易失败 4交易超时
*/
private Integer status;
/**
* eth收款地址
*/
private String eth_address;
/**
* tron收款地址
*/
private String tron_address;
/**
* 商户订单标题
*/
private String subject;
/**
* 商户订单号
*/
private String order_no;
/**
* 订单回调地址
*/
private String notify_url;
/**
* 支付地址
*/
private String pay_url;
/**
* 订单支付成功重定向地址
*/
private String redirect_url;
/**
* 超时时间(秒)
*/
private Long time_out;
/**
* 数量
*/
private String amount;
/**
* 手续费
*/
private String fee;
/**
* 余额
*/
private String balance;
/**
* 支付时间
*/
private Long pay_time;
/**
* 支付地址
*/
private String pay_address;
/**
* 交易hash
*/
private String tx_hash;
/**
* 备注
*/
private String remark;
/**
* 国际化:中文简体(zh-CN),中文繁体(zh-TW),英文(en-US),日文(ja-JP)
*/
private String locale;
/**
* 过期时间
*/
private Long expire_time;
/**
* 创建时间
*/
private Long create_time;
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/vo/TransPrepareVO.java
|
package foxpay.api.vo;
import foxpay.api.result.FoxPayVO;
import lombok.Data;
@Data
public class TransPrepareVO extends FoxPayVO {
/**
* 交易凭证
*/
private String trans_token;
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/vo/TransQueryVO.java
|
package foxpay.api.vo;
import foxpay.api.result.FoxPayVO;
import lombok.Data;
@Data
public class TransQueryVO extends FoxPayVO {
/**
* 流水号
*/
private String trade_no;
/**
* 商户订单号
*/
private String order_no;
/**
* 手续费方式:2 交易金额 3 账户余额
*/
private String gas_type;
/**
* 交易凭证
*/
private String trans_token;
/**
* 提现状态:1待提现,2处理中, 3提现成功, 4提现失败
*/
private Integer status;
/**
* 提现地址
*/
private String to_address;
/**
* 回调地址
*/
private String notify_url;
/**
* 数量
*/
private String amount;
/**
* 手续费
*/
private String fee;
/**
* 余额
*/
private String balance;
/**
* 支付时间
*/
private Long pay_time;
/**
* 交易hash
*/
private String tx_hash;
/**
* 备注
*/
private String remark;
/**
* 创建时间
*/
private Long create_time;
}
|
0
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api
|
java-sources/ai/foxpay/api/foxpay-sdk/1.1/foxpay/api/vo/TransVO.java
|
package foxpay.api.vo;
import foxpay.api.result.FoxPayVO;
import lombok.Data;
@Data
public class TransVO extends FoxPayVO {
/**
* 流水号
*/
private String trade_no;
/**
* 商户订单号
*/
private String order_no;
/**
* 手续费方式:2 交易金额 3 账户余额
*/
private String gas_type;
/**
* 交易凭证
*/
private String trans_token;
/**
* 提现状态:1待提现,2处理中, 3提现成功, 4提现失败
*/
private Integer status;
/**
* 提现地址
*/
private String to_address;
/**
* 回调地址
*/
private String notify_url;
/**
* 数量
*/
private String amount;
/**
* 备注
*/
private String remark;
/**
* 创建时间
*/
private Long create_time;
}
|
0
|
java-sources/ai/fusionbrain/fusionbrain-spring-boot-starter/1.0.0/ai/fusionbrain
|
java-sources/ai/fusionbrain/fusionbrain-spring-boot-starter/1.0.0/ai/fusionbrain/autoconfigure/FusionBrainAutoConfiguration.java
|
package ai.fusionbrain.autoconfigure;
import ai.fusionbrain.client.FusionBrainClient;
import ai.fusionbrain.client.FusionBrainClientImpl;
import ai.fusionbrain.client.FusionBrainFeignClient;
import ai.fusionbrain.config.FeignConfig;
import ai.fusionbrain.config.FusionBrainProperties;
import ai.fusionbrain.config.FusionBrainSslProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
@EnableConfigurationProperties({FusionBrainProperties.class, FusionBrainSslProperties.class})
@ConditionalOnProperty(prefix = "fusionbrain", name = "enabled")
@EnableFeignClients(basePackageClasses = FusionBrainFeignClient.class)
@Import({FeignConfig.class, FusionBrainSslConfig.class})
@AutoConfigureAfter(name = {
"org.springframework.cloud.openfeign.FeignAutoConfiguration",
"org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration"
})
public class FusionBrainAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public FusionBrainClient fusionBrainClient(
FusionBrainFeignClient feignClient,
ObjectMapper objectMapper,
FusionBrainProperties fusionBrainProperties,
Executor fusionBrainAsyncExecutor
) {
return new FusionBrainClientImpl(feignClient, objectMapper, fusionBrainProperties, fusionBrainAsyncExecutor);
}
@Bean(name = "fusionBrainAsyncExecutor")
@ConditionalOnMissingBean(name = "fusionBrainAsyncExecutor")
public Executor fusionBrainAsyncExecutor(FusionBrainProperties properties) {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(properties.getAsyncCorePoolSize());
executor.setThreadNamePrefix("FusionBrainAsync-");
executor.initialize();
return executor;
}
}
|
0
|
java-sources/ai/fusionbrain/fusionbrain-spring-boot-starter/1.0.0/ai/fusionbrain
|
java-sources/ai/fusionbrain/fusionbrain-spring-boot-starter/1.0.0/ai/fusionbrain/autoconfigure/FusionBrainSslConfig.java
|
package ai.fusionbrain.autoconfigure;
import ai.fusionbrain.config.FusionBrainSslProperties;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.InputStream;
import java.security.KeyStore;
@Configuration
@ConditionalOnClass(name = "feign.httpclient.ApacheHttpClient")
@ConditionalOnProperty(prefix = "fusionbrain", name = "enabled", havingValue = "true")
public class FusionBrainSslConfig {
@Bean
public CloseableHttpClient fusionBrainHttpClient(FusionBrainSslProperties properties)
throws Exception {
SSLContext sslContext = createSslContext(properties);
return HttpClients.custom()
.setSSLSocketFactory(
new SSLConnectionSocketFactory(
sslContext,
getHostnameVerifier(properties)
)
)
.build();
}
public SSLContext createSslContext(FusionBrainSslProperties properties) throws Exception {
SSLContextBuilder builder = SSLContexts.custom();
if (!properties.isEnabled()) {
builder.loadTrustMaterial((chain, authType) -> true);
} else if (StringUtils.hasText(properties.getTruststore())) {
Resource resource = new DefaultResourceLoader().getResource(properties.getTruststore());
try (InputStream is = resource.getInputStream()) {
KeyStore trustStore = KeyStore.getInstance(properties.getTruststoreType());
trustStore.load(is, properties.getTruststorePassword().toCharArray());
builder.loadTrustMaterial(trustStore, null);
}
}
return builder.build();
}
public HostnameVerifier getHostnameVerifier(FusionBrainSslProperties properties) {
return properties.isEnabled()
? SSLConnectionSocketFactory.getDefaultHostnameVerifier()
: NoopHostnameVerifier.INSTANCE;
}
}
|
0
|
java-sources/ai/fusionbrain/fusionbrain-spring-boot-starter/1.0.0/ai/fusionbrain
|
java-sources/ai/fusionbrain/fusionbrain-spring-boot-starter/1.0.0/ai/fusionbrain/client/FusionBrainClient.java
|
package ai.fusionbrain.client;
import ai.fusionbrain.dto.*;
import ai.fusionbrain.dto.request.PipelineParams;
import ai.fusionbrain.exception.FusionBrainException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
/**
* Interface defining methods for interacting with FusionBrain API.
*/
public interface FusionBrainClient {
/**
* Retrieves a list of all available pipelines.
*
* @return List of {@link PipelineDTO} objects representing the pipelines.
* @throws FusionBrainException if an error occurs during the request.
*/
List<PipelineDTO> getPipelines() throws FusionBrainException;
/**
* Retrieves a list of pipelines based on the specified type.
*
* @param type The type of pipelines to retrieve.
* @return List of {@link PipelineDTO} objects representing the pipelines of the specified type.
* @throws FusionBrainException if an error occurs during the request.
*/
List<PipelineDTO> getPipelines(EPipelineType type) throws FusionBrainException;
/**
* Retrieves the availability status of a specific pipeline.
*
* @param pipelineId The unique identifier of the pipeline.
* @return {@link AvailabilityStatus} indicating whether the pipeline is available.
* @throws FusionBrainException if an error occurs during the request.
*/
AvailabilityStatus getPipelineAvailability(UUID pipelineId) throws FusionBrainException;
/**
* Runs a specified pipeline with given parameters and files.
*
* @param pipelineId The unique identifier of the pipeline to run.
* @param params The parameters for the pipeline execution.
* @param files List of byte arrays representing the input files for the pipeline.
* @return {@link RunResponse} containing information about the initiated pipeline run.
* @throws FusionBrainException if an error occurs during the request.
*/
RunResponse runPipeline(UUID pipelineId, PipelineParams params, List<byte[]> files) throws FusionBrainException;
/**
* Runs a specified pipeline with given parameters (without files).
*
* @param pipelineId The unique identifier of the pipeline to run.
* @param params The parameters for the pipeline execution.
* @return {@link RunResponse} containing information about the initiated pipeline run.
* @throws FusionBrainException if an error occurs during the request.
*/
default RunResponse runPipeline(UUID pipelineId, PipelineParams params) throws FusionBrainException {
return runPipeline(pipelineId, params, null);
}
/**
* Retrieves the current status of a running task.
*
* @param taskId The unique identifier of the task.
* @return {@link StatusResponse} object containing the status information.
* @throws FusionBrainException if an error occurs during the request.
*/
StatusResponse getStatus(UUID taskId) throws FusionBrainException;
/**
* Asynchronously waits for a specified task to complete, polling at regular intervals.
*
* @param taskId The unique identifier of the task.
* @param initialDelay The time in seconds to wait before starting to poll.
* @return {@link StatusResponse} object containing the final status after completion.
* @throws FusionBrainException if an error occurs during the request.
*/
CompletableFuture<StatusResponse> waitForCompletion(UUID taskId, long initialDelay) throws FusionBrainException;
/**
* Synchronously waits for a specified task to complete, polling at regular intervals.
* This method blocks until the task is completed or an error occurs.
*
* @param taskId The unique identifier of the task.
* @param initialDelay The time in seconds to wait before starting to poll.
* @return {@link StatusResponse} object containing the final status after completion.
* @throws FusionBrainException if an error occurs during the request.
*/
default StatusResponse waitForCompletionSync(UUID taskId, long initialDelay) {
try {
return waitForCompletion(taskId, initialDelay).get();
} catch (InterruptedException | ExecutionException e) {
Thread.currentThread().interrupt();
throw new FusionBrainException("Failed to execute synchronous operation", e);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.