BUG-6650: ep-ip/sgt, implement and wire template provider
[groupbasedpolicy.git] / sxp-integration / sxp-ise-adapter / src / main / java / org / opendaylight / groupbasedpolicy / sxp_ise_adapter / impl / GbpIseConfigListenerImpl.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.groupbasedpolicy.sxp_ise_adapter.impl;
10
11 import com.google.common.util.concurrent.CheckedFuture;
12 import com.google.common.util.concurrent.FutureCallback;
13 import com.google.common.util.concurrent.Futures;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import com.google.common.util.concurrent.ThreadFactoryBuilder;
16 import java.text.SimpleDateFormat;
17 import java.util.Collection;
18 import java.util.Date;
19 import java.util.concurrent.ExecutionException;
20 import java.util.concurrent.LinkedBlockingQueue;
21 import java.util.concurrent.ThreadPoolExecutor;
22 import java.util.concurrent.TimeUnit;
23 import java.util.concurrent.TimeoutException;
24 import javax.annotation.Nonnull;
25 import javax.annotation.Nullable;
26 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
27 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
28 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
29 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
30 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.groupbasedpolicy.gbp.sxp.ise.adapter.model.rev160630.GbpSxpIseAdapter;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.groupbasedpolicy.gbp.sxp.ise.adapter.model.rev160630.gbp.sxp.ise.adapter.IseSourceConfig;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.groupbasedpolicy.gbp.sxp.ise.adapter.model.rev160630.gbp.sxp.ise.adapter.IseHarvestStatus;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.groupbasedpolicy.gbp.sxp.ise.adapter.model.rev160630.gbp.sxp.ise.adapter.IseHarvestStatusBuilder;
36 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 /**
41  * Purpose: listen for harvest configuration and trigger harvesting
42  */
43 public class GbpIseConfigListenerImpl implements GbpIseConfigListener {
44
45     private static final Logger LOG = LoggerFactory.getLogger(GbpIseConfigListenerImpl.class);
46
47     private static final String DATE_AND_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
48
49     private final DataBroker dataBroker;
50     private final GbpIseSgtHarvester gbpIseSgtHarvester;
51     @Nonnull private final EPPolicyTemplateProviderFacade templateProviderFacade;
52     private final ThreadPoolExecutor pool;
53
54     public GbpIseConfigListenerImpl(@Nonnull final DataBroker dataBroker, @Nonnull final GbpIseSgtHarvester gbpIseSgtHarvester,
55                                     @Nonnull final EPPolicyTemplateProviderFacade templateProviderFacade) {
56         this.dataBroker = dataBroker;
57         this.gbpIseSgtHarvester = gbpIseSgtHarvester;
58         this.templateProviderFacade = templateProviderFacade;
59         pool = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(10),
60                 new ThreadFactoryBuilder().setNameFormat("ise-sgt-harverster-%d").build()) {
61             @Override
62             protected void afterExecute(final Runnable r, final Throwable t) {
63                 super.afterExecute(r, t);
64                 if (t != null) {
65                     LOG.warn("ise harvest task failed", t);
66                 }
67             }
68         };
69     }
70
71     @Override
72     public void onDataTreeChanged(@Nonnull final Collection<DataTreeModification<IseSourceConfig>> collection) {
73         for (DataTreeModification<IseSourceConfig> modification : collection) {
74             final IseSourceConfig iseSourceConfig = modification.getRootNode().getDataAfter();
75             //TODO: separate template provider from harvesting
76             templateProviderFacade.assignIseSourceConfig(iseSourceConfig);
77             if (iseSourceConfig != null) {
78                 pool.submit(() -> {
79                     final ListenableFuture<Integer> harvestResult = gbpIseSgtHarvester.harvest(iseSourceConfig);
80                     Futures.addCallback(harvestResult, new FutureCallback<Integer>() {
81                         @Override
82                         public void onSuccess(@Nullable final Integer result) {
83                             LOG.debug("ise harvest finished, outcome: {}", result);
84                             storeOutcome(true, result.intValue(), null);
85                         }
86
87                         @Override
88                         public void onFailure(final Throwable t) {
89                             LOG.debug("ise harvest failed", t);
90                             storeOutcome(false, 0, t.getMessage());
91                         }
92                     });
93
94                     try {
95                         harvestResult.get(30, TimeUnit.SECONDS);
96                     } catch (InterruptedException | ExecutionException | TimeoutException e) {
97                         LOG.debug("failed to finish ise-sgt-harvest task properly on time", e);
98                     }
99                 });
100             }
101         }
102     }
103
104     private CheckedFuture<Void, TransactionCommitFailedException> storeOutcome(final boolean succeeded, final int counter, final String reason) {
105         final WriteTransaction wTx = dataBroker.newWriteOnlyTransaction();
106         final InstanceIdentifier<IseHarvestStatus> harvestStatusPath = InstanceIdentifier.create(GbpSxpIseAdapter.class)
107                 .child(IseHarvestStatus.class);
108         final IseHarvestStatus harvestStatus = new IseHarvestStatusBuilder()
109                 .setReason(reason)
110                 .setSuccess(succeeded)
111                 .setTemplatesWritten(counter)
112                 .setTimestamp(createDateTime(new Date()))
113                 .build();
114         wTx.put(LogicalDatastoreType.OPERATIONAL, harvestStatusPath, harvestStatus, true);
115         return wTx.submit();
116     }
117
118     private static DateAndTime createDateTime(Date when) {
119         final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_AND_TIME_FORMAT);
120         return new DateAndTime(simpleDateFormat.format(when));
121     }
122
123     @Override
124     public void close() throws Exception {
125         if (!pool.isTerminated()) {
126             pool.shutdown();
127             final boolean terminated = pool.awaitTermination(10, TimeUnit.SECONDS);
128             if (! terminated) {
129                 pool.shutdownNow();
130             }
131         }
132     }
133 }