summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openecomp/sparky/dal/aai/ActiveInventoryAdapter.java
blob: 0f1ed36e76ace89462b45aa6109c19e5dcd5ab20 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
/**
 * ============LICENSE_START=======================================================
 * org.onap.aai
 * ================================================================================
 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
 * Copyright © 2017 Amdocs
 * ================================================================================
 * 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.
 * ============LICENSE_END=========================================================
 *
 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 */
package org.openecomp.sparky.dal.aai;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.NoSuchElementException;

import org.apache.http.client.utils.URIBuilder;
import org.openecomp.cl.api.Logger;
import org.openecomp.cl.eelf.LoggerFactory;
import org.openecomp.sparky.config.oxm.OxmEntityDescriptor;
import org.openecomp.sparky.config.oxm.OxmModelLoader;
import org.openecomp.sparky.dal.aai.config.ActiveInventoryConfig;
import org.openecomp.sparky.dal.aai.config.ActiveInventoryRestConfig;
import org.openecomp.sparky.dal.aai.enums.RestAuthenticationMode;
import org.openecomp.sparky.dal.exception.ElasticSearchOperationException;
import org.openecomp.sparky.dal.rest.OperationResult;
import org.openecomp.sparky.dal.rest.RestClientBuilder;
import org.openecomp.sparky.dal.rest.RestfulDataAccessor;
import org.openecomp.sparky.logging.AaiUiMsgs;
import org.openecomp.sparky.security.SecurityContextFactory;
import org.openecomp.sparky.util.NodeUtils;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource.Builder;


/**
 * The Class ActiveInventoryAdapter.
 */

/**
 * @author davea
 *
 */
public class ActiveInventoryAdapter extends RestfulDataAccessor
    implements ActiveInventoryDataProvider {

  private static final Logger LOG =
      LoggerFactory.getInstance().getLogger(ActiveInventoryAdapter.class);
  
  private static final String HEADER_TRANS_ID = "X-TransactionId";
  private static final String HEADER_FROM_APP_ID = "X-FromAppId";
  private static final String HEADER_AUTHORIZATION = "Authorization";

  private static final String TRANSACTION_ID_PREFIX = "txnId-";
  private static final String UI_APP_NAME = "AAI-UI";
  
  
  private ActiveInventoryConfig config;

  /**
   * Instantiates a new active inventory adapter.
   *
   * @param restClientBuilder the rest client builder
   * @throws ElasticSearchOperationException the elastic search operation exception
   * @throws IOException Signals that an I/O exception has occurred.
   */
  public ActiveInventoryAdapter(RestClientBuilder restClientBuilder)
      throws ElasticSearchOperationException, IOException {
    super(restClientBuilder);

    try {
      this.config = ActiveInventoryConfig.getConfig();
    } catch (Exception exc) {
      throw new ElasticSearchOperationException("Error getting active inventory configuration",
          exc);
    }

    clientBuilder.setUseHttps(true);

    clientBuilder.setValidateServerHostname(config.getAaiSslConfig().isValidateServerHostName());

    SecurityContextFactory sslContextFactory = clientBuilder.getSslContextFactory();

    sslContextFactory.setServerCertificationChainValidationEnabled(
        config.getAaiSslConfig().isValidateServerCertificateChain());
    
    if (config.getAaiRestConfig().getAuthenticationMode() == RestAuthenticationMode.SSL_CERT) {
      sslContextFactory.setClientCertFileName(config.getAaiSslConfig().getKeystoreFilename());
      sslContextFactory.setClientCertPassword(config.getAaiSslConfig().getKeystorePassword());
      sslContextFactory.setTrustStoreFileName(config.getAaiSslConfig().getTruststoreFilename());
    }

    clientBuilder.setConnectTimeoutInMs(config.getAaiRestConfig().getConnectTimeoutInMs());
    clientBuilder.setReadTimeoutInMs(config.getAaiRestConfig().getReadTimeoutInMs());

  }

  /* (non-Javadoc)
   * @see org.openecomp.sparky.dal.rest.RestfulDataAccessor#setClientDefaults(com.sun.jersey.api.client.Client, java.lang.String, java.lang.String, java.lang.String)
   */
  @Override
  protected Builder setClientDefaults(Client client, String url, String payloadContentType,
      String acceptContentType) {
    Builder builder = super.setClientDefaults(client, url, payloadContentType, acceptContentType);

    builder = builder.header(HEADER_FROM_APP_ID, UI_APP_NAME);
    byte bytes[] = new byte[6];
    txnIdGenerator.nextBytes(bytes);
    builder =
        builder.header(HEADER_TRANS_ID, TRANSACTION_ID_PREFIX + ByteBuffer.wrap(bytes).getInt());

    if (config.getAaiRestConfig().getAuthenticationMode() == RestAuthenticationMode.SSL_BASIC) {
      builder = builder.header(HEADER_AUTHORIZATION,
          config.getAaiSslConfig().getBasicAuthenticationCredentials());
    }

    return builder;
  }

  /**
   * The main method.
   *
   * @param args the arguments
   */
  public static void main(String[] args) {

    // TODO Auto-generated method stub
    RestClientBuilder builder = new RestClientBuilder();
    RestfulDataAccessor accessor;
    try {
      accessor = new ActiveInventoryAdapter(builder);
      OperationResult or =
          accessor.doGet("/cloud-infrastructure/pservers/pserver/SQLTEST006", "application/json");
      String jsonPatch = "{ \"hostname\" : \"SQLTEST006\", \"prov-status\" : \"PREPROV\","
          + " \"in-maint\" : \"false\", \"is-closed-loop\" : \"false\" }";
      or = accessor.doPatch("/cloud-infrastructure/pservers/pserver/SQLTEST006", jsonPatch,
          "application/json");
      // System.out.println("PATCH or = " + or.getResultCode() + " : " + or.toString());
    } catch (ElasticSearchOperationException | IOException exc) {
      // TODO Auto-generated catch block
      exc.printStackTrace();
    }

  }

  /**
   * Gets the full url.
   *
   * @param resourceUrl the resource url
   * @return the full url
   * @throws Exception the exception
   */
  private String getFullUrl(String resourceUrl) throws Exception {
    ActiveInventoryRestConfig aaiRestConfig = ActiveInventoryConfig.getConfig().getAaiRestConfig();
    final String host = aaiRestConfig.getHost();
    final String port = aaiRestConfig.getPort();
    final String basePath = aaiRestConfig.getResourceBasePath();
    return String.format("https://%s:%s%s%s", host, port, basePath, resourceUrl);
  }
  
  public String getGenericQueryForSelfLink(String startNodeType, List<String> queryParams) throws Exception {
    
    URIBuilder urlBuilder = new URIBuilder(getFullUrl("/search/generic-query"));
    
    for( String queryParam : queryParams) {
      urlBuilder.addParameter("key", queryParam);
    }
    
    urlBuilder.addParameter("start-node-type", startNodeType);
    urlBuilder.addParameter("include", startNodeType);
    
    final String constructedLink = urlBuilder.toString();
    
    // TODO: debug log for constructed link

    return constructedLink;

}


  /* (non-Javadoc)
   * @see org.openecomp.sparky.dal.aai.ActiveInventoryDataProvider#getSelfLinksByEntityType(java.lang.String)
   */
  @Override
  public OperationResult getSelfLinksByEntityType(String entityType) throws Exception {

    /*
     * For this one, I want to dynamically construct the nodes-query for self-link discovery as a
     * utility method that will use the OXM model entity data to drive the query as well.
     */
    
    if (entityType == null) {
      throw new NullPointerException(
          "Failed to getSelfLinksByEntityType() because entityType is null");
    }

    OxmEntityDescriptor entityDescriptor =
        OxmModelLoader.getInstance().getEntityDescriptor(entityType);

    if (entityDescriptor == null) {
      throw new NoSuchElementException("Failed to getSelfLinksByEntityType() because could"
          + " not find entity descriptor from OXM with type = " + entityType);
    }

    String link = null;
    final String primaryKeyStr =
        NodeUtils.concatArray(entityDescriptor.getPrimaryKeyAttributeName(), "/");

    link = getFullUrl("/search/nodes-query?search-node-type=" + entityType + "&filter="
        + primaryKeyStr + ":EXISTS");



    return doGet(link, "application/json");

  }

  /* (non-Javadoc)
   * @see org.openecomp.sparky.dal.aai.ActiveInventoryDataProvider#getSelfLinkForEntity(java.lang.String, java.lang.String, java.lang.String)
   */
  @Override
  public OperationResult getSelfLinkForEntity(String entityType, String primaryKeyName,
      String primaryKeyValue) throws Exception {

    if (entityType == null) {
      throw new NullPointerException("Failed to getSelfLinkForEntity() because entityType is null");
    }

    if (primaryKeyName == null) {
      throw new NullPointerException(
          "Failed to getSelfLinkForEntity() because primaryKeyName is null");
    }

    if (primaryKeyValue == null) {
      throw new NullPointerException(
          "Failed to getSelfLinkForEntity() because primaryKeyValue is null");
    }


    /*
     * Try to protect ourselves from illegal URI formatting exceptions caused by characters that
     * aren't natively supported in a URI, but can be escaped to make them legal.
     */

    String encodedEntityType = URLEncoder.encode(entityType, "UTF-8");
    String encodedPrimaryKeyName = URLEncoder.encode(primaryKeyName, "UTF-8");
    String encodedPrimaryKeyValue = URLEncoder.encode(primaryKeyValue, "UTF-8");

    String link = null;

    if ("service-instance".equals(entityType)) {

      link = getFullUrl("/search/generic-query?key=" + encodedEntityType + "."
          + encodedPrimaryKeyName + ":" + encodedPrimaryKeyValue + "&start-node-type="
          + encodedEntityType + "&include=customer&depth=2");

    } else {

      link =
          getFullUrl("/search/generic-query?key=" + encodedEntityType + "." + encodedPrimaryKeyName
              + ":" + encodedPrimaryKeyValue + "&start-node-type=" + encodedEntityType);

    }

    return queryActiveInventoryWithRetries(link, "application/json",
        this.config.getAaiRestConfig().getNumRequestRetries());

  }


  /**
   * Our retry conditions should be very specific.
   *
   * @param r the r
   * @return true, if successful
   */
  private boolean shouldRetryRequest(OperationResult r) {

    if (r == null) {
      return true;
    }

    int rc = r.getResultCode();

    if (rc == 200) {
      return false;
    }

    if (rc == 404) {
      return false;
    }

    return true;

  }

  /**
   * Query active inventory.
   *
   * @param url the url
   * @param acceptContentType the accept content type
   * @return the operation result
   */
  // package protected for test classes instead of private
  OperationResult queryActiveInventory(String url, String acceptContentType) {
    return doGet(url, acceptContentType);
  }

  /* (non-Javadoc)
   * @see org.openecomp.sparky.dal.aai.ActiveInventoryDataProvider#queryActiveInventoryWithRetries(java.lang.String, java.lang.String, int)
   */
  @Override
  public OperationResult queryActiveInventoryWithRetries(String url, String responseType,
      int numRetries) {

    OperationResult result = null;

    for (int x = 0; x < numRetries; x++) {

      LOG.debug(AaiUiMsgs.QUERY_AAI_RETRY_SEQ, url, String.valueOf(x + 1));

      result = queryActiveInventory(url, responseType);

      /**
       * Record number of times we have attempted the request to later summarize how many times we
       * are generally retrying over thousands of messages in a sync.
       * 
       * If the number of retries is surprisingly high, then we need to understand why that is as
       * the number of retries is also causing a heavier load on AAI beyond the throttling controls
       * we already have in place in term of the transaction rate controller and number of
       * parallelized threads per task processor.
       */

      result.setNumRequestRetries(x);

      if (!shouldRetryRequest(result)) {

        /*
         * if (myConfig.getAaiRestConfig().isCacheEnabled()) {
         * 
         * CachedHttpRequest cachedRequest = new CachedHttpRequest();
         * cachedRequest.setHttpRequestMethod("GET"); cachedRequest.setPayload("");
         * cachedRequest.setPayloadMimeType(""); cachedRequest.setUrl(url);
         * cachedRequest.setOperationType( TransactionStorageType.ACTIVE_INVENTORY_QUERY.getIndex()
         * );
         * 
         * CachedHttpResponse cachedResponse = new CachedHttpResponse();
         * cachedResponse.setPayload(result.getResult());
         * cachedResponse.setPayloadMimeType("application/json");
         * cachedResponse.setStatusCode(result.getResultCode());
         * 
         * CachedHttpTransaction txn = new CachedHttpTransaction(cachedRequest, cachedResponse);
         * storageProvider.persistTransaction(txn);
         * 
         * }
         */


        result.setResolvedLinkFromServer(true);
        LOG.debug(AaiUiMsgs.QUERY_AAI_RETRY_DONE_SEQ, url, String.valueOf(x + 1));

        return result;
      }

      try {
        /*
         * Sleep between re-tries to be nice to the target system.
         */
        Thread.sleep(50);
      } catch (InterruptedException exc) {
        LOG.error(AaiUiMsgs.QUERY_AAI_WAIT_INTERRUPTION, exc.getLocalizedMessage());
        break;
      }
      LOG.error(AaiUiMsgs.QUERY_AAI_RETRY_FAILURE_WITH_SEQ, url, String.valueOf(x + 1));
    }


    result.setResolvedLinkFailure(true);
    LOG.info(AaiUiMsgs.QUERY_AAI_RETRY_MAXED_OUT, url);

    return result;

  }

  /* (non-Javadoc)
   * @see org.openecomp.sparky.dal.rest.RestfulDataAccessor#shutdown()
   */
  @Override
  public void shutdown() {
    // TODO Auto-generated method stub

    if (entityCache != null) {
      entityCache.shutdown();
    }

  }


}