Search in sources :

Example 1 with Event

use of io.gravitee.repository.management.model.Event in project gravitee-management-rest-api by gravitee-io.

the class EventServiceImpl method convert.

private Event convert(NewEventEntity newEventEntity) {
    Event event = new Event();
    event.setType(io.gravitee.repository.management.model.EventType.valueOf(newEventEntity.getType().toString()));
    event.setPayload(newEventEntity.getPayload());
    event.setParentId(newEventEntity.getParentId());
    event.setProperties(newEventEntity.getProperties());
    return event;
}
Also used : Event(io.gravitee.repository.management.model.Event)

Example 2 with Event

use of io.gravitee.repository.management.model.Event in project gravitee-gateway by gravitee-io.

the class SyncManager method getLastEvent.

private Event getLastEvent(final String api, long nextLastRefreshAt) {
    final EventCriteria.Builder eventCriteriaBuilder;
    if (lastRefreshAt == -1) {
        eventCriteriaBuilder = new EventCriteria.Builder().property(Event.EventProperties.API_ID.getValue(), api);
    } else {
        eventCriteriaBuilder = new EventCriteria.Builder().property(Event.EventProperties.API_ID.getValue(), api).from(lastRefreshAt - TIMEFRAME_BEFORE_DELAY).to(nextLastRefreshAt + TIMEFRAME_AFTER_DELAY);
    }
    List<Event> events = eventRepository.search(eventCriteriaBuilder.types(EventType.PUBLISH_API, EventType.UNPUBLISH_API, EventType.START_API, EventType.STOP_API).build(), new PageableBuilder().pageNumber(0).pageSize(1).build()).getContent();
    return (!events.isEmpty()) ? events.get(0) : null;
}
Also used : PageableBuilder(io.gravitee.repository.management.api.search.builder.PageableBuilder) Event(io.gravitee.repository.management.model.Event) EventCriteria(io.gravitee.repository.management.api.search.EventCriteria) PageableBuilder(io.gravitee.repository.management.api.search.builder.PageableBuilder)

Example 3 with Event

use of io.gravitee.repository.management.model.Event 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());
}
Also used : java.util(java.util) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) EventCriteria(io.gravitee.repository.management.api.search.EventCriteria) Plan(io.gravitee.gateway.handlers.api.definition.Plan) EventType(io.gravitee.repository.management.model.EventType) ApiRepository(io.gravitee.repository.management.api.ApiRepository) PageableBuilder(io.gravitee.repository.management.api.search.builder.PageableBuilder) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Collator(java.text.Collator) EventRepository(io.gravitee.repository.management.api.EventRepository) Logger(org.slf4j.Logger) Event(io.gravitee.repository.management.model.Event) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ApiManager(io.gravitee.gateway.handlers.api.manager.ApiManager) IOException(java.io.IOException) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) PlanRepository(io.gravitee.repository.management.api.PlanRepository) LifecycleState(io.gravitee.repository.management.model.LifecycleState) AtomicLong(java.util.concurrent.atomic.AtomicLong) Api(io.gravitee.gateway.handlers.api.definition.Api) Path(io.gravitee.definition.model.Path) GatewayConfiguration(io.gravitee.gateway.env.GatewayConfiguration) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) IOException(java.io.IOException) Event(io.gravitee.repository.management.model.Event) Api(io.gravitee.gateway.handlers.api.definition.Api)

Example 4 with Event

use of io.gravitee.repository.management.model.Event in project gravitee-gateway by gravitee-io.

the class SyncManagerTest method test_shouldUndeployIfLastEventIsUnpublishAPI.

@Test
public void test_shouldUndeployIfLastEventIsUnpublishAPI() throws Exception {
    io.gravitee.repository.management.model.Api api = new RepositoryApiBuilder().id("api-test").updatedAt(new Date()).definition("test").build();
    final Api mockApi = mockApi(api);
    final Event mockEvent = mockEvent(api, EventType.PUBLISH_API);
    final Event mockEvent2 = mockEvent(api, EventType.UNPUBLISH_API);
    when(eventRepository.search(any(EventCriteria.class), any(Pageable.class))).thenReturn(new Page<>(Collections.singletonList(mockEvent), 0, 0, 1), new Page<>(Collections.singletonList(mockEvent2), 0, 0, 1));
    when(apiRepository.findAll()).thenReturn(Collections.singleton(api));
    syncManager.refresh();
    when(apiManager.apis()).thenReturn(Collections.singleton(mockApi));
    when(apiRepository.findAll()).thenReturn(Collections.singleton(api));
    syncManager.refresh();
    verify(apiManager).deploy(mockApi);
    verify(apiManager, never()).update(any(Api.class));
    verify(apiManager).undeploy(mockApi.getId());
}
Also used : Pageable(io.gravitee.repository.management.api.search.Pageable) Event(io.gravitee.repository.management.model.Event) RepositoryApiBuilder(io.gravitee.gateway.services.sync.builder.RepositoryApiBuilder) Api(io.gravitee.gateway.handlers.api.definition.Api) EventCriteria(io.gravitee.repository.management.api.search.EventCriteria) Test(org.junit.Test)

Example 5 with Event

use of io.gravitee.repository.management.model.Event in project gravitee-gateway by gravitee-io.

the class SyncManagerTest method test_shouldUpdateIfLastEventIsStopAPI.

@Test
public void test_shouldUpdateIfLastEventIsStopAPI() throws Exception {
    io.gravitee.repository.management.model.Api api = new RepositoryApiBuilder().id("api-test").updatedAt(new Date()).definition("test").lifecycleState(LifecycleState.STARTED).build();
    Instant updateDateInst = api.getUpdatedAt().toInstant().plus(Duration.ofHours(1));
    io.gravitee.repository.management.model.Api api2 = new RepositoryApiBuilder().id("api-test").updatedAt(Date.from(updateDateInst)).definition("test").lifecycleState(LifecycleState.STOPPED).build();
    final Api mockApi = mockApi(api);
    mockApi(api2);
    final Event mockEvent = mockEvent(api, EventType.PUBLISH_API);
    final Event mockEvent2 = mockEvent(api2, EventType.STOP_API);
    List<Event> events = new ArrayList<Event>();
    events.add(mockEvent);
    events.add(mockEvent2);
    when(eventRepository.search(any(EventCriteria.class), any(Pageable.class))).thenReturn(new Page<>(Collections.singletonList(mockEvent), 0, 0, 1));
    when(apiRepository.findAll()).thenReturn(Collections.singleton(api));
    when(apiManager.apis()).thenReturn(Collections.singleton(mockApi));
    syncManager.refresh();
    when(eventRepository.search(any(EventCriteria.class), any(Pageable.class))).thenReturn(new Page<>(events, 0, 0, 2));
    when(apiRepository.findAll()).thenReturn(Collections.singleton(api2));
    when(apiManager.get(api.getId())).thenReturn(mockApi);
    syncManager.refresh();
    verify(apiManager).deploy(mockApi);
    verify(apiManager).update(mockApi);
    verify(apiManager, never()).undeploy(any(String.class));
}
Also used : Instant(java.time.Instant) RepositoryApiBuilder(io.gravitee.gateway.services.sync.builder.RepositoryApiBuilder) EventCriteria(io.gravitee.repository.management.api.search.EventCriteria) Pageable(io.gravitee.repository.management.api.search.Pageable) Event(io.gravitee.repository.management.model.Event) Api(io.gravitee.gateway.handlers.api.definition.Api) Test(org.junit.Test)

Aggregations

Event (io.gravitee.repository.management.model.Event)25 EventCriteria (io.gravitee.repository.management.api.search.EventCriteria)19 Api (io.gravitee.gateway.handlers.api.definition.Api)16 RepositoryApiBuilder (io.gravitee.gateway.services.sync.builder.RepositoryApiBuilder)15 Pageable (io.gravitee.repository.management.api.search.Pageable)14 Test (org.junit.Test)14 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)4 PageableBuilder (io.gravitee.repository.management.api.search.builder.PageableBuilder)4 Instant (java.time.Instant)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 EventRepository (io.gravitee.repository.management.api.EventRepository)3 EventType (io.gravitee.repository.management.model.EventType)3 Collectors (java.util.stream.Collectors)3 ArgumentMatcher (org.mockito.ArgumentMatcher)3 Logger (org.slf4j.Logger)3 LoggerFactory (org.slf4j.LoggerFactory)3 Autowired (org.springframework.beans.factory.annotation.Autowired)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 GatewayConfiguration (io.gravitee.gateway.env.GatewayConfiguration)2 InstanceEventPayload (io.gravitee.gateway.services.monitoring.event.InstanceEventPayload)2