use of io.gravitee.gateway.handlers.api.definition.Api in project gravitee-gateway by gravitee-io.
the class ProxyValidatorTest method validate_proxy_correctContextPathAndTarget.
/*
@Test(expected = ValidationException.class)
public void validate_proxy_badTarget() {
Proxy proxyDefinition = new Proxy();
proxyDefinition.setContextPath("/");
proxyDefinition.setEndpoint("toto");
Api definition = new Api();
definition.setProxy(proxyDefinition);
new ProxyValidator().validate(definition);
}
*/
@Test
public void validate_proxy_correctContextPathAndTarget() {
Proxy proxyDefinition = new Proxy();
proxyDefinition.setContextPath("/context-path");
proxyDefinition.setEndpoints(new LinkedHashSet<>());
proxyDefinition.getEndpoints().add(new HttpEndpoint("name", "http://localhost"));
Api definition = new Api();
definition.setProxy(proxyDefinition);
new ProxyValidator().validate(definition);
}
use of io.gravitee.gateway.handlers.api.definition.Api in project gravitee-gateway by gravitee-io.
the class PlanPolicyChainResolver method calculate.
@Override
protected List<Policy> calculate(StreamType streamType, Request request, Response response, ExecutionContext executionContext) {
if (streamType == StreamType.ON_REQUEST) {
String plan = (String) executionContext.getAttribute(ExecutionContext.ATTR_PLAN);
String application = (String) executionContext.getAttribute(ExecutionContext.ATTR_APPLICATION);
// String user = (String) executionContext.getAttribute(ExecutionContext.ATTR_USER_ID);
// request.metrics().setUserId(user);
request.metrics().setPlan(plan);
request.metrics().setApplication(application);
Plan apiPlan = api.getPlan(plan);
// The call is probably not relative to the same API.
if (plan != null && apiPlan != null) {
Map<String, Path> paths = api.getPlan(plan).getPaths();
if (paths != null && !paths.isEmpty()) {
// For 1.0.0, there is only a single root path defined
// Must be reconsidered when user will be able to manage policies at the plan level by himself
Path rootPath = paths.values().iterator().next();
return rootPath.getRules().stream().filter(rule -> rule.isEnabled() && rule.getMethods().contains(request.method())).map(rule -> create(streamType, rule.getPolicy().getName(), rule.getPolicy().getConfiguration())).filter(Objects::nonNull).collect(Collectors.toList());
}
} else {
logger.warn("No plan has been selected to process request {}. Returning an unauthorized HTTP status (401)", request.id());
return null;
}
}
return Collections.emptyList();
}
use of io.gravitee.gateway.handlers.api.definition.Api in project gravitee-gateway by gravitee-io.
the class ApiKeysCacheService method onEvent.
@Override
public void onEvent(Event<ReactorEvent, Reactable> event) {
final Api api = (Api) event.content().item();
switch(event.type()) {
case DEPLOY:
startRefresher(api);
break;
case UNDEPLOY:
stopRefresher(api);
break;
case UPDATE:
stopRefresher(api);
startRefresher(api);
break;
default:
// Nothing to do with unknown event type
break;
}
}
use of io.gravitee.gateway.handlers.api.definition.Api in project gravitee-gateway by gravitee-io.
the class SyncManager method refresh.
public void refresh() {
logger.debug("Synchronization #{} started at {}", counter.incrementAndGet(), Instant.now().toString());
logger.debug("Refreshing gateway state...");
try {
// Extract all registered APIs
Map<String, io.gravitee.repository.management.model.Api> apis = apiRepository.findAll().stream().collect(Collectors.toMap(io.gravitee.repository.management.model.Api::getId, api -> api));
long nextLastRefreshAt = System.currentTimeMillis();
// Get last event by API
Map<String, Event> events = new HashMap<>();
apis.forEach((id, api) -> {
Event event = getLastEvent(id, nextLastRefreshAt);
if (event != null) {
events.put(id, event);
}
});
// Extract definition for each event
Map<String, Api> definitions = new HashMap<>();
events.values().forEach(event -> {
try {
// Read API definition from event
io.gravitee.repository.management.model.Api eventPayload = objectMapper.readValue(event.getPayload(), io.gravitee.repository.management.model.Api.class);
Api definition = objectMapper.readValue(eventPayload.getDefinition(), Api.class);
io.gravitee.repository.management.model.Api api = apis.get(definition.getId());
// Update definition with required information for deployment phase
definition.setEnabled(api.getLifecycleState() == LifecycleState.STARTED);
definition.setDeployedAt(eventPayload.getDeployedAt());
definitions.put(definition.getId(), definition);
} catch (IOException ioe) {
logger.error("Error while determining deployed APIs store into events payload", ioe);
}
});
// Determine APIs to undeploy because of deployment tags
Set<String> apisToRemove = definitions.values().stream().filter(api -> !hasMatchingTags(api)).map(Api::getId).collect(Collectors.toSet());
// Undeploy APIs not relative to this gateway instance (different deployment tags)
apisToRemove.forEach(apiId -> {
apiManager.undeploy(apiId);
apis.remove(apiId);
events.remove(apiId);
definitions.remove(apiId);
});
// Determine API which must be stopped and stop them
events.entrySet().stream().filter(apiEvent -> {
Event event = apiEvent.getValue();
return event.getType() == EventType.STOP_API || event.getType() == EventType.UNPUBLISH_API;
}).forEach(apiEvent -> apiManager.undeploy(apiEvent.getKey()));
// Determine API which must be deployed
events.entrySet().stream().filter(apiEvent -> {
Event event = apiEvent.getValue();
return event.getType() == EventType.START_API || event.getType() == EventType.PUBLISH_API;
}).forEach(apiEvent -> {
// Read API definition from event
Api definition = definitions.get(apiEvent.getKey());
// API to deploy
enhanceWithData(definition);
if (definition != null) {
// Get deployed API
Api deployedApi = apiManager.get(definition.getId());
// API is not yet deployed, so let's do it !
if (deployedApi == null) {
apiManager.deploy(definition);
} else if (deployedApi.getDeployedAt().before(definition.getDeployedAt())) {
apiManager.update(definition);
}
}
});
lastRefreshAt = nextLastRefreshAt;
} catch (TechnicalException te) {
logger.error("Unable to sync instance", te);
}
logger.debug("Synchronization #{} ended at {}", counter.get(), Instant.now().toString());
}
use of io.gravitee.gateway.handlers.api.definition.Api in project gravitee-gateway by gravitee-io.
the class SyncManager method hasMatchingTags.
private boolean hasMatchingTags(Api api) {
final Optional<List<String>> optTagList = gatewayConfiguration.shardingTags();
if (optTagList.isPresent()) {
List<String> tagList = optTagList.get();
if (api.getTags() != null) {
final List<String> inclusionTags = tagList.stream().map(String::trim).filter(tag -> !tag.startsWith("!")).collect(Collectors.toList());
final List<String> exclusionTags = tagList.stream().map(String::trim).filter(tag -> tag.startsWith("!")).map(tag -> tag.substring(1)).collect(Collectors.toList());
if (inclusionTags.stream().filter(exclusionTags::contains).count() > 0) {
throw new IllegalArgumentException("You must not configure a tag to be included and excluded");
}
final boolean hasMatchingTags = inclusionTags.stream().anyMatch(tag -> api.getTags().stream().anyMatch(apiTag -> {
final Collator collator = Collator.getInstance();
collator.setStrength(Collator.NO_DECOMPOSITION);
return collator.compare(tag, apiTag) == 0;
})) || (!exclusionTags.isEmpty() && exclusionTags.stream().noneMatch(tag -> api.getTags().stream().anyMatch(apiTag -> {
final Collator collator = Collator.getInstance();
collator.setStrength(Collator.NO_DECOMPOSITION);
return collator.compare(tag, apiTag) == 0;
})));
if (!hasMatchingTags) {
logger.debug("The API {} has been ignored because not in configured tags {}", api.getName(), tagList);
}
return hasMatchingTags;
}
logger.debug("Tags {} are configured on gateway instance but not found on the API {}", tagList, api.getName());
return false;
}
// no tags configured on this gateway instance
return true;
}
Aggregations