<commit_before>/*
 * Copyright © 2015 <NAME>, Inc.
 *
 * 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 co.cask.cdap.test;

import co.cask.cdap.api.app.Application;
import co.cask.cdap.cli.util.InstanceURIParser;
import co.cask.cdap.client.ApplicationClient;
import co.cask.cdap.client.DatasetClient;
import co.cask.cdap.client.MetaClient;
import co.cask.cdap.client.MetricsClient;
import co.cask.cdap.client.MonitorClient;
import co.cask.cdap.client.NamespaceClient;
import co.cask.cdap.client.ProgramClient;
import co.cask.cdap.client.StreamClient;
import co.cask.cdap.client.config.ClientConfig;
import co.cask.cdap.client.config.ConnectionConfig;
import co.cask.cdap.client.util.RESTClient;
import co.cask.cdap.common.UnauthorizedException;
import co.cask.cdap.common.conf.CConfiguration;
import co.cask.cdap.common.conf.Constants;
import co.cask.cdap.data2.datafabric.DefaultDatasetNamespace;
import co.cask.cdap.proto.ApplicationRecord;
import co.cask.cdap.proto.ConfigEntry;
import co.cask.cdap.proto.DatasetSpecificationSummary;
import co.cask.cdap.proto.Id;
import co.cask.cdap.proto.NamespaceMeta;
import co.cask.cdap.proto.StreamDetail;
import co.cask.cdap.security.authentication.client.AccessToken;
import co.cask.cdap.security.authentication.client.AuthenticationClient;
import co.cask.cdap.security.authentication.client.basic.BasicAuthenticationClient;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Abstract class for writing Integration tests for CDAP. Provides utility methods to use in Integration tests.
 * Users should extend this class in their test classes.
 */
public abstract class IntegrationTestBase {
  private static final Logger LOG = LoggerFactory.getLogger(IntegrationTestBase.class);
  private static final long SERVICE_CHECK_TIMEOUT = TimeUnit.MINUTES.toSeconds(10);

  @ClassRule
  public static final TemporaryFolder TEMP_FOLDER = new TemporaryFolder();

  private AccessToken accessToken;

  @Before
  public void setUp() throws Exception {
    checkSystemServices();
    assertUnrecoverableResetEnabled();
    assertIsClear();
  }

  protected void checkSystemServices() throws TimeoutException {
    Callable<Boolean> cdapAvailable = new Callable<Boolean>() {
      @Override
      public Boolean call() throws Exception {
        // first wait for all system services to be 'OK'
        if (!getMonitorClient().allSystemServicesOk()) {
          return false;
        }
        // Check that the dataset service is up, and also that the default namespace exists
        // Using list and checking that the only namespace to exist is default, as opposed to using get()
        // so we don't have to unnecessarily add a try-catch for NamespaceNotFoundException, since that exception is
        // not handled in checkServicesWithRetry.
        List<NamespaceMeta> namespaces = getNamespaceClient().list();
        return namespaces.size() == 1 && NamespaceMeta.DEFAULT.equals(namespaces.get(0));
      }
    };

    try {
      checkServicesWithRetry(cdapAvailable, "CDAP Services are not available");
    } catch (Throwable e) {
      Throwable rootCause = Throwables.getRootCause(e);
      if (rootCause instanceof UnauthorizedException) {
        // security is enabled, we need to get access token before checking system services
        try {
          accessToken = fetchAccessToken();
        } catch (IOException ex) {
          throw Throwables.propagate(ex);
        }
        checkServicesWithRetry(cdapAvailable, "CDAP Services are not available");
      } else {
        throw Throwables.propagate(rootCause);
      }
    }
    LOG.info("CDAP Services are up and running!");
  }

  /**
   * Uses BasicAuthenticationClient to fetch {@link AccessToken} - this implementation can be overridden if desired.
   *
   * @return {@link AccessToken}
   * @throws IOException
   * @throws TimeoutException if a timeout occurs while getting an access token
   */
  protected AccessToken fetchAccessToken() throws IOException, TimeoutException {
    Properties properties = new Properties();
    properties.setProperty("security.auth.client.username", System.getProperty("cdap.username"));
    properties.setProperty("security.auth.client.password", System.getProperty("cdap.password"));
    final AuthenticationClient authClient = new BasicAuthenticationClient();
    authClient.configure(properties);
    ConnectionConfig connectionConfig = getClientConfig().getConnectionConfig();
    authClient.setConnectionInfo(connectionConfig.getHostname(), connectionConfig.getPort(), false);

    checkServicesWithRetry(new Callable<Boolean>() {
      @Override
      public Boolean call() throws Exception {
        return authClient.getAccessToken() != null;
      }
    }, "Unable to connect to Authentication service to obtain access token, Connection info : " + connectionConfig);

    return authClient.getAccessToken();
  }


  private void checkServicesWithRetry(Callable<Boolean> callable,
                                      String exceptionMessage) throws TimeoutException {
    int numSecs = 0;
    do {
      try {
        numSecs++;
        if (callable.call()) {
          return;
        }
        TimeUnit.SECONDS.sleep(1);
      } catch (InterruptedException | IOException e) {
        // We want to suppress and retry on InterruptedException or IOException
      } catch (Throwable e) {
        // Also suppress and retry if the root cause is InterruptedException or IOException
        Throwable rootCause = Throwables.getRootCause(e);
        if (!(rootCause instanceof InterruptedException || rootCause instanceof IOException)) {
          // Throw if root cause is any other exception e.g. UnauthorizedException
          throw Throwables.propagate(rootCause);
        }
      }
    } while (numSecs <= SERVICE_CHECK_TIMEOUT);

    // when we have passed the timeout and the check for services is not successful<commit_msg>Use StopWatch instead of a count of retries, to have a more accurate timeout. Only retry for namespaces if there are 0 namespaces. This handles the case of retrying until timeout, when more than one namespace exists.<commit_after>/*
 * Copyright © 2015-2016 <NAME>, Inc.
 *
 * 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 co.cask.cdap.test;

import co.cask.cdap.api.app.Application;
import co.cask.cdap.cli.util.InstanceURIParser;
import co.cask.cdap.client.ApplicationClient;
import co.cask.cdap.client.DatasetClient;
import co.cask.cdap.client.MetaClient;
import co.cask.cdap.client.MetricsClient;
import co.cask.cdap.client.MonitorClient;
import co.cask.cdap.client.NamespaceClient;
import co.cask.cdap.client.ProgramClient;
import co.cask.cdap.client.StreamClient;
import co.cask.cdap.client.config.ClientConfig;
import co.cask.cdap.client.config.ConnectionConfig;
import co.cask.cdap.client.util.RESTClient;
import co.cask.cdap.common.UnauthorizedException;
import co.cask.cdap.common.conf.CConfiguration;
import co.cask.cdap.common.conf.Constants;
import co.cask.cdap.data2.datafabric.DefaultDatasetNamespace;
import co.cask.cdap.proto.ApplicationRecord;
import co.cask.cdap.proto.ConfigEntry;
import co.cask.cdap.proto.DatasetSpecificationSummary;
import co.cask.cdap.proto.Id;
import co.cask.cdap.proto.NamespaceMeta;
import co.cask.cdap.proto.StreamDetail;
import co.cask.cdap.security.authentication.client.AccessToken;
import co.cask.cdap.security.authentication.client.AuthenticationClient;
import co.cask.cdap.security.authentication.client.basic.BasicAuthenticationClient;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Stopwatch;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Abstract class for writing Integration tests for CDAP. Provides utility methods to use in Integration tests.
 * Users should extend this class in their test classes.
 */
public abstract class IntegrationTestBase {
  private static final Logger LOG = LoggerFactory.getLogger(IntegrationTestBase.class);
  private static final long SERVICE_CHECK_TIMEOUT_SECONDS = TimeUnit.MINUTES.toSeconds(10);

  @ClassRule
  public static final TemporaryFolder TEMP_FOLDER = new TemporaryFolder();

  private AccessToken accessToken;

  @Before
  public void setUp() throws Exception {
    checkSystemServices();
    assertUnrecoverableResetEnabled();
    assertIsClear();
  }

  protected void checkSystemServices() throws TimeoutException, InterruptedException {
    Callable<Boolean> cdapAvailable = new Callable<Boolean>() {
      @Override
      public Boolean call() throws Exception {
        // first wait for all system services to be 'OK'
        if (!getMonitorClient().allSystemServicesOk()) {
          return false;
        }
        // Check that the dataset service is up, and also that the default namespace exists
        // Using list and checking that the only namespace to exist is default, as opposed to using get()
        // so we don't have to unnecessarily add a try-catch for NamespaceNotFoundException, since that exception is
        // not handled in checkServicesWithRetry.
        List<NamespaceMeta> namespaces = getNamespaceClient().list();

        if (namespaces.size() == 0) {
          return false;
        }
        if (namespaces.size() == 1 && NamespaceMeta.DEFAULT.equals(namespaces.get(0))) {
          return true;
        }
        throw new IllegalStateException("Unexpected namespaces: " + namespaces);
      }
    };

    String errorMessage = String.format("CDAP Services are not available. Retried for %s seconds.",
                                        SERVICE_CHECK_TIMEOUT_SECONDS);
    try {
      checkServicesWithRetry(cdapAvailable, errorMessage);
    } catch (Throwable e) {
      Throwable rootCause = Throwables.getRootCause(e);
      if (rootCause instanceof UnauthorizedException) {
        // security is enabled, we need to get access token before checking system services
        try {
          accessToken = fetchAccessToken();
        } catch (IOException ex) {
          throw Throwables.propagate(ex);
        }
        checkServicesWithRetry(cdapAvailable, errorMessage);
      } else {
        throw Throwables.propagate(rootCause);
      }
    }
    LOG.info("CDAP Services are up and running!");
  }

  /**
   * Uses BasicAuthenticationClient to fetch {@link AccessToken} - this implementation can be overridden if desired.
   *
   * @return {@link AccessToken}
   * @throws IOException
   * @throws TimeoutException if a timeout occurs while getting an access token
   */
  protected AccessToken fetchAccessToken() throws IOException, TimeoutException, InterruptedException {
    Properties properties = new Properties();
    properties.setProperty("security.auth.client.username", System.getProperty("cdap.username"));
    properties.setProperty("security.auth.client.password", System.getProperty("cdap.password"));
    final AuthenticationClient authClient = new BasicAuthenticationClient();
    authClient.configure(properties);
    ConnectionConfig connectionConfig = getClientConfig().getConnectionConfig();
    authClient.setConnectionInfo(connectionConfig.getHostname(), connectionConfig.getPort(), false);

    checkServicesWithRetry(new Callable<Boolean>() {
      @Override
      public Boolean call() throws Exception {
        return authClient.getAccessToken() != null;
      }
    }, "Unable to connect to Authentication service to obtain access token, Connection info : " + connectionConfig);

    return authClient.getAccessToken();
  }


  private void checkServicesWithRetry(Callable<Boolean> callable,
                                      String exceptionMessage) throws TimeoutException, InterruptedException {
    Stopwatch sw = new Stopwatch().start();
    do {
      try {
        if (callable.call()) {
          return;
        }
      } catch (IOException e) {
        // We want to suppress and retry on IOException
      } catch (Throwable e) {
        // Also suppress and retry if the root cause is IOException
        Throwable rootCause = Throwables.getRootCause(e);
        if (!(rootCause instanceof IOException)) {
          // Throw if root cause is any other exception e.g. UnauthorizedException
          throw Throwables.propagate(rootCause);
        }
      }
      TimeUnit.SECONDS.sleep(1);
    } while (sw.elapsedTime(TimeUnit.SECONDS) <= SERVICE_CHECK_TIMEOUT_SECONDS);

    // when we have passed the timeout and the check for services is not successful
{'fraction_non_alphanumeric': 0.09056987788331072, 'fraction_numerical': 0.0026458616010854815, 'mean_word_length': 3.7459755312298775, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7252697', 'n_tokens_mistral': 4007, 'n_tokens_neox': 3942, 'n_words': 1144}