/**
 * Copyright (C) 2015 The Gravitee team (http://gravitee.io)
 *
 * 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
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.gravitee.gateway.services.monitoring;

import io.gravitee.common.event.Event;
import io.gravitee.common.event.EventListener;
import io.gravitee.common.event.EventManager;
import io.gravitee.common.service.AbstractService;
import io.gravitee.definition.model.Api;
import io.gravitee.gateway.core.event.ApiEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author David BRASSELY (brasseld at gmail.com)
 */
public class MonitoringService extends AbstractService implements EventListener<ApiEvent, Api> {

    private final static Logger LOGGER = LoggerFactory.getLogger(MonitoringService.class);

    @Autowired
    private EventManager eventManager;

    private final Map<Api, ExecutorService> monitors = new HashMap<>();

    @Override
    protected void doStart() throws Exception {
        super.doStart();

        eventManager.subscribeForEvents(this, ApiEvent.class);
    }

    @Override
    protected void doStop() throws Exception {
        super.doStop();

        monitors.forEach((api, executorService) -> {
            ExecutorService executor = monitors.remove(api);
            if (! executor.isShutdown()) {
                LOGGER.info("Stop monitor for {}", api);
                executor.shutdownNow();
            }
        });
    }

    @Override
    protected String name() {
        return "Endpoint Monitoring Service";
    }

    @Override
    public void onEvent(Event<ApiEvent, Api> event) {
        final Api api = event.content();

        LOGGER.info("Create an executor to monitor {}", api);

        EndpointMonitor monitor = new EndpointMonitor(api);

        ExecutorService executor = Executors.newSingleThreadScheduledExecutor(
                r -> new Thread(r, "monitor-" + api.getName()));

        monitors.put(api, executor);

        LOGGER.info("Start monitor for {}", api);
        ((ScheduledExecutorService) executor).scheduleWithFixedDelay(monitor, 0, 5, TimeUnit.SECONDS);
    }
}

@@ -898,16 +898,64 @@
 el.Api;%0A
+import io.gravitee.definition.model.Monitoring;%0A
 import i
@@ -2015,451 +2015,779 @@
  -%3E 
-%7B
+stopMonitor(api));
 %0A    
+%7D%0A%0A
     
-    ExecutorService executor = monitors.remove(api);%0A            if (! executor.isShutdown()) %7B%0A                LOGGER.info(%22Stop monitor for %7B%7D%22, api);%0A                executor.shutdownNow();%0A            %7D%0A        %7D);%0A
+@Override%0A    protected String name() %7B%0A        return %22Endpoint Monitoring Service%22;%0A    %7D%0A%0A    @Override%0A    public void onEvent(Event%3CApiEvent, Api%3E event) %7B%0A        final Api api = event.content();%0A%0A        switch (event.type()) %7B%0A            case DEPLOY:%0A                startMonitor(api);%0A                break;%0A            case UNDEPLOY:%0A                stopMonitor(api);%0A                break;%0A            case UPDATE:%0A   
     
+ 
 %7D%0A
-%0A
+   
     
-@Override%0A    protected String name() %7B%0A        return %22Endpoint Monitoring Service%22
+ if (api.getMonitoring() != null && api.getMonitoring().isEnabled()) %7B%0A            startMonitor(api)
 ;%0A    
+ 
+   
 %7D
-%0A
 %0A    
-@Override%0A    public void onEvent(Event%3CApiEvent, Api%3E event) %7B%0A        final Api api = event.content();%0A%0A
+%7D%0A%0A    private void startMonitor(Api api) %7B%0A        Monitoring monitoring = api.getMonitoring();%0A        if (monitoring != null) %7B%0A            if (monitoring.isEnabled()) %7B%0A        
     
@@ -2853,16 +2853,24 @@
         
+ 
+       
 Endpoint
@@ -2922,16 +2922,24 @@
         
+  
+      
 Executor
@@ -3017,16 +3017,24 @@
         
+        
 r -%3E new
@@ -3075,32 +3075,40 @@
 e()));%0A%0A        
+      
+  
 monitors.put(api
@@ -3117,24 +3117,32 @@
 executor);%0A%0A
+        
         LOGG
@@ -3175,24 +3175,32 @@
  %7B%7D%22, api);%0A
+        
         ((Sc
@@ -3290,16 +3290,518 @@
 CONDS);%0A
+            %7D else %7B%0A                LOGGER.info(%22Monitoring is disabled for %7B%7D%22, api);%0A            %7D%0A        %7D%0A    %7D%0A%0A    private void stopMonitor(Api api) %7B%0A        ExecutorService executor = monitors.remove(api);%0A        if (executor != null) %7B%0A            if (! executor.isShutdown()) %7B%0A                LOGGER.info(%22Stop monitor for %7B%7D%22, api);%0A                executor.shutdownNow();%0A            %7D else %7B%0A                LOGGER.info(%22Monitor already shutdown for %7B%7D%22, api);%0A            %7D%0A        %7D%0A
     %7D%0A%7D%0A

Monitor API