BUG-6858: adapt to ise api, wire harvestAll to template-provider
[groupbasedpolicy.git] / sxp-integration / sxp-ise-adapter / src / main / java / org / opendaylight / groupbasedpolicy / sxp_ise_adapter / impl / GbpIseSgtHarvesterImpl.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.base.Function;
12 import com.google.common.util.concurrent.AsyncFunction;
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 com.sun.jersey.api.client.Client;
17 import com.sun.jersey.api.client.WebResource;
18 import java.net.URI;
19 import java.security.GeneralSecurityException;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Objects;
25 import java.util.concurrent.Callable;
26 import java.util.concurrent.ExecutorService;
27 import java.util.concurrent.Executors;
28 import java.util.concurrent.Future;
29 import java.util.concurrent.TimeUnit;
30 import java.util.stream.Collectors;
31 import javax.annotation.Nonnull;
32 import javax.annotation.Nullable;
33 import javax.xml.xpath.XPath;
34 import javax.xml.xpath.XPathExpressionException;
35 import org.opendaylight.groupbasedpolicy.sxp_ise_adapter.impl.util.IseReplyUtil;
36 import org.opendaylight.groupbasedpolicy.sxp_ise_adapter.impl.util.RestClientFactory;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.groupbasedpolicy.sxp.integration.sxp.ise.adapter.model.rev160630.gbp.sxp.ise.adapter.IseSourceConfig;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.groupbasedpolicy.sxp.integration.sxp.ise.adapter.model.rev160630.gbp.sxp.ise.adapter.ise.source.config.ConnectionConfig;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.groupbasedpolicy.sxp.integration.sxp.ise.adapter.model.rev160630.gbp.sxp.ise.adapter.ise.source.config.connection.config.Header;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.sxp.database.rev160308.Sgt;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.w3c.dom.Node;
44 import org.w3c.dom.NodeList;
45 import org.xml.sax.InputSource;
46
47 /**
48  * Purpose: harvest sgt + names available via ise-rest-api
49  */
50 public class GbpIseSgtHarvesterImpl implements GbpIseSgtHarvester {
51
52     private static final Logger LOG = LoggerFactory.getLogger(GbpIseSgtHarvesterImpl.class);
53
54     private final SgtInfoProcessor[] sgtInfoProcessors;
55
56     /**
57      * @param sgtInfoProcessors generator delegate
58      */
59     public GbpIseSgtHarvesterImpl(final SgtInfoProcessor... sgtInfoProcessors) {
60         this.sgtInfoProcessors = sgtInfoProcessors;
61     }
62
63     @Override
64     public ListenableFuture<Collection<SgtInfo>> harvestAll(@Nonnull final IseContext iseContext) {
65         ListenableFuture<Collection<SgtInfo>> result;
66         try {
67             final IseSourceConfig iseSourceConfig = iseContext.getIseSourceConfig();
68             final ConnectionConfig connectionConfig = iseSourceConfig.getConnectionConfig();
69             final WebResource baseWebResource = createWebResource(connectionConfig);
70
71             final WebResource.Builder requestBuilder = RestClientFactory.createRequestBuilder(baseWebResource,
72                     connectionConfig.getHeader(), RestClientFactory.PATH_ERS_CONFIG_SGT);
73             final String rawSgtSummary = IseReplyUtil.deliverResponse(requestBuilder);
74
75             final List<SgtInfo> sgtInfos = harvestDetails(rawSgtSummary, baseWebResource, connectionConfig, iseContext.getUuidToSgtMap());
76
77             ListenableFuture<Void> processingResult = Futures.immediateCheckedFuture(null);
78             for (SgtInfoProcessor processor : sgtInfoProcessors) {
79                 processingResult = Futures.transform(processingResult, new AsyncFunction<Void, Void>() {
80                     @Override
81                     public ListenableFuture<Void> apply(final Void input) throws Exception {
82                         LOG.debug("entering stg-info processor {}", processor.getClass().getSimpleName());
83                         return processor.processSgtInfo(iseSourceConfig.getTenant(), sgtInfos);
84                     }
85                 });
86             }
87             result = Futures.transform(processingResult, new Function<Void, Collection<SgtInfo>>() {
88                 @Nullable
89                 @Override
90                 public Collection<SgtInfo> apply(@Nullable final Void input) {
91                     // update uuid map
92                     for (SgtInfo sgtInfo : sgtInfos) {
93                         iseContext.getUuidToSgtMap().put(sgtInfo.getUuid(), sgtInfo.getSgt().getValue());
94                     }
95                     //TODO: store harvest stats to DS/operational
96                     // always success, otherwise there will be TransactionCommitFailedException thrown
97                     return sgtInfos;
98                 }
99             });
100         } catch (Exception e) {
101             LOG.debug("failed to harvest ise", e);
102             result = Futures.immediateFailedFuture(e);
103         }
104
105         return result;
106     }
107
108     private WebResource createWebResource(final ConnectionConfig connectionConfig) throws GeneralSecurityException {
109         final Client iseClient = RestClientFactory.createIseClient(connectionConfig);
110         return iseClient.resource(connectionConfig.getIseRestUrl().getValue());
111     }
112
113     private List<SgtInfo> harvestDetails(final String rawSgtSummary, final WebResource baseWebResource,
114                                          final ConnectionConfig connectionConfig, final Map<String, Integer> uuidToSgtMap) {
115         LOG.trace("rawSgtSummary: {}", rawSgtSummary);
116         final List<Future<SgtInfo>> sgtInfoFutureBag = new ArrayList<>();
117
118         // prepare worker pool
119         final ExecutorService pool = Executors.newFixedThreadPool(
120                 10, new ThreadFactoryBuilder().setNameFormat("ise-sgt-worker-%d").build());
121
122         // parse sgtSummary
123         final XPath xpath = IseReplyUtil.setupXpath();
124
125         final InputSource inputSource = IseReplyUtil.createInputSource(rawSgtSummary);
126         try {
127             final NodeList sgtResources = IseReplyUtil.findAllSgtResourceNodes(xpath, inputSource);
128             final Collection<Node> sgtLinkNodes = IseReplyUtil.filterNewResourcesByID(uuidToSgtMap, xpath, sgtResources);
129
130             int counter = 0;
131             for (Node sgtLinkNode : sgtLinkNodes) {
132                 final String sgtLinkHrefValue = sgtLinkNode.getNodeValue();
133                 LOG.debug("found sgt resource: {}", sgtLinkHrefValue);
134
135                 // submit all query tasks to pool
136                 final int idx = counter++;
137                 sgtInfoFutureBag.add(pool.submit(new Callable<SgtInfo>() {
138                     @Override
139                     public SgtInfo call() {
140                         SgtInfo sgtInfo = null;
141                         try {
142                             sgtInfo = querySgtDetail(baseWebResource, connectionConfig.getHeader(), xpath, idx, sgtLinkHrefValue);
143                         } catch (XPathExpressionException e) {
144                             LOG.info("failed to parse sgt response for {}: {}", sgtLinkHrefValue, e.getMessage());
145                         }
146                         return sgtInfo;
147                     }
148                 }));
149             }
150
151             // stop pool
152             pool.shutdown();
153             final boolean terminated = pool.awaitTermination(1, TimeUnit.MINUTES);
154             if (! terminated) {
155                 LOG.debug("NOT all sgt-detail queries succeeded - timed out");
156                 pool.shutdownNow();
157             }
158         } catch (InterruptedException | XPathExpressionException e) {
159             LOG.warn("failed to query all-sgt details", e);
160         }
161
162         // harvest available details
163         return sgtInfoFutureBag.stream()
164                 .map(this::gainSgtInfoSafely)
165                 .filter(Objects::nonNull)
166                 .collect(Collectors.toList());
167     }
168
169     private SgtInfo gainSgtInfoSafely(final Future<SgtInfo> response) {
170         SgtInfo result = null;
171         if (response.isDone() && ! response.isCancelled()) {
172             try {
173                 result = response.get();
174             } catch (Exception e) {
175                 LOG.debug("sgt-detail query failed even when future was DONE", e);
176             }
177         }
178         return result;
179     }
180
181     private SgtInfo querySgtDetail(final WebResource baseWebResource, final List<Header> headers, final XPath xpath,
182                                    final int idx, final String sgtLinkHrefValue) throws XPathExpressionException {
183         // query all sgt entries (serial-vise)
184         final URI hrefToSgtDetailUri = URI.create(sgtLinkHrefValue);
185         final WebResource.Builder requestBuilder = RestClientFactory.createRequestBuilder(baseWebResource, headers,
186                 hrefToSgtDetailUri.getPath());
187         // time consuming operation - wait for rest response
188         final String rawSgtDetail = IseReplyUtil.deliverResponse(requestBuilder);
189         LOG.trace("rawSgtDetail: {}", rawSgtDetail);
190
191         // process response xml
192         final Node sgtNode = IseReplyUtil.findSgtDetailNode(xpath, rawSgtDetail);
193         final Node sgtName = IseReplyUtil.gainSgtName(xpath, sgtNode);
194         final Node sgtUuid = IseReplyUtil.gainSgtUuid(xpath, sgtNode);
195         final Node sgtValue = IseReplyUtil.gainSgtValue(xpath, sgtNode);
196         LOG.debug("sgt value [{}]: {} -> {}", idx, sgtValue, sgtName);
197
198         // store replies into list of SgtInfo
199         final Sgt sgt = new Sgt(Integer.parseInt(sgtValue.getNodeValue(), 10));
200         return new SgtInfo(sgt, sgtName.getNodeValue(), sgtUuid.getNodeValue());
201     }
202
203 }