<commit_before>/*
 * Copyright (c) 2016 Open Baton (http://www.openbaton.org)
 *
 * 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 org.openbaton.nfvo.core.api;

import java.io.IOException;
import java.net.InetAddress;
import java.net.URL;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.PostConstruct;
import org.openbaton.catalogue.mano.common.DeploymentFlavour;
import org.openbaton.catalogue.mano.descriptor.VirtualDeploymentUnit;
import org.openbaton.catalogue.mano.descriptor.VirtualNetworkFunctionDescriptor;
import org.openbaton.catalogue.mano.record.VirtualNetworkFunctionRecord;
import org.openbaton.catalogue.nfvo.ImageStatus;
import org.openbaton.catalogue.nfvo.NFVImage;
import org.openbaton.catalogue.nfvo.Network;
import org.openbaton.catalogue.nfvo.Subnet;
import org.openbaton.catalogue.nfvo.VimInstance;
import org.openbaton.exceptions.AlreadyExistingException;
import org.openbaton.exceptions.BadRequestException;
import org.openbaton.exceptions.EntityUnreachableException;
import org.openbaton.exceptions.NotFoundException;
import org.openbaton.exceptions.PluginException;
import org.openbaton.exceptions.VimException;
import org.openbaton.nfvo.repositories.ImageRepository;
import org.openbaton.nfvo.repositories.VNFDRepository;
import org.openbaton.nfvo.repositories.VNFRRepository;
import org.openbaton.nfvo.repositories.VimRepository;
import org.openbaton.nfvo.vim_interfaces.vim.VimBroker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/** Created by lto on 13/05/15. */
@Service
@Scope
@ConfigurationProperties
public class VimManagement implements org.openbaton.nfvo.core.interfaces.VimManagement {

  @Autowired private VimRepository vimRepository;

  @Autowired private VimBroker vimBroker;

  @Autowired private ImageRepository imageRepository;

  @Autowired private VNFDRepository vnfdRepository;

  @Autowired private VNFRRepository vnfrRepository;

  @Autowired private AsyncVimManagement asyncVimManagement;

  private static Map<String, Long> lastUpdateVim;

  private final Logger log = LoggerFactory.getLogger(this.getClass());

  // if set to true there will be a check if the stored Vims are still reachable every minute

  @Value("${nfvo.vim.active.check:false}")
  private boolean vimCheck;

  @Value("${nfvo.vim.delete.check.vnfr:true}")
  private boolean checkForVimInVnfr;

  //TODO change Scope to prototype
  @Value("${nfvo.vim.refresh.timout:120}")
  private int refreshTimeout;

  @Value("${nfvo.vim.cache.timout:10000}")
  private long refreshCacheTimeout;

  public boolean isCheckForVimInVnfr() {
    return checkForVimInVnfr;
  }

  public int getRefreshTimeout() {
    return refreshTimeout;
  }

  public void setRefreshTimeout(int refreshTimeout) {
    this.refreshTimeout = refreshTimeout;
  }

  @PostConstruct
  private void init() {
    lastUpdateVim = new ConcurrentHashMap<>();
  }

  @Override
  public VimInstance add(VimInstance vimInstance, String projectId)
      throws VimException, PluginException, IOException, BadRequestException,
          AlreadyExistingException {
    validateVimInstance(vimInstance);
    vimInstance.setProjectId(projectId);
    log.trace("Persisting VimInstance: " + vimInstance);
    return this.refresh(vimInstance, true);
  }

  @Override
  public void delete(String id, String projectId) throws NotFoundException, BadRequestException {

    VimInstance vimInstance = vimRepository.findFirstByIdAndProjectId(id, projectId);
    if (vimInstance == null) {
      throw new NotFoundException("Vim Instance with id " + id + " was not found");
    }
    if (checkForVimInVnfr) {
      for (VirtualNetworkFunctionRecord vnfr : vnfrRepository.findByProjectId(projectId)) {
        for (VirtualDeploymentUnit vdu : vnfr.getVdu()) {
          if (vdu.getVimInstanceName().contains(vimInstance.getName())) {
            throw new BadRequestException(
                "Cannot delete VIM Instance " + vimInstance.getName() + " while it is in use.");
          }
        }
      }
    }
    //    for (VirtualNetworkFunctionDescriptor vnfd : vnfdRepository.findByProjectId(projectId)) {
    //      for (VirtualDeploymentUnit vdu : vnfd.getVdu()) {
    //        if (vdu.getVimInstanceName().contains(vimInstance.getName())) {
    //          vdu.getVimInstanceName().remove(vimInstance.getName());
    //        }
    //      }
    //    }
    vimRepository.delete(vimInstance);
  }

  @Override
  public VimInstance update(VimInstance vimInstance, String id, String projectId)
      throws VimException, PluginException, IOException, BadRequestException,
          AlreadyExistingException, NotFoundException {
    validateVimInstance(vimInstance);
    //    vimInstance = vimRepository.save(vimInstance);
    VimInstance vimInstanceOld = vimRepository.findFirstByIdAndProjectId(id, projectId);
    if (vimInstanceOld == null)
      throw new NotFoundException("VIM Instance with ID " + id + " not found.");
    if (!vimInstanceOld.getName().equals(vimInstance.getName())) {
      for (VirtualNetworkFunctionDescriptor vnfd : vnfdRepository.findByProjectId(projectId)) {
        for (VirtualDeploymentUnit vdu : vnfd.getVdu()) {
          if (vdu.getVimInstanceName().contains(vimInstanceOld.getName())) {
            vdu.getVimInstanceName().remove(vimInstanceOld.getName());
            vdu.getVimInstanceName().add(vimInstance.getName());
          }
        }
      }
      for (VirtualNetworkFunctionRecord vnfr : vnfrRepository.findByProjectId(projectId)) {
        for (VirtualDeploymentUnit vdu : vnfr.getVdu()) {
          if (vdu.getVimInstanceName().contains(vimInstanceOld.getName())) {
            vdu.getVimInstanceName().remove(vimInstanceOld.getName());
            vdu.getVimInstanceName().add(vimInstance.getName());
          }
        }
      }
    }
    vimInstance.setProjectId(vimInstanceOld.getProjectId());
    vimInstance.setId(vimInstanceOld.getId());
    if (vimInstance.getPassword().equals("**********")) {
      vimInstance.setPassword(vimInstanceOld.getPassword());
    }
    return refresh(vimInstance, true);
    //    return vimInstance;
  }

  @Override
  public VimInstance query(String id, String projectId) {
    return vimRepository.findFirstByIdAndProjectId(id, projectId);
  }

  @Override
  public synchronized VimInstance refresh(VimInstance vimInstance, boolean force)
      throws VimException, PluginException, IOException, BadRequestException,
          AlreadyExistingException {

    if (!force) {
      long lastUpdated = 0;
      try {
        lastUpdated = lastUpdateVim.get(vimInstance.getId());
      } catch (NullPointerException ignored) {

      }
      if (lastUpdated != 0 && lastUpdated > (new Date().getTime() + refreshCacheTimeout)) {
        return vimInstance;
      }
    }

    if (vimCheck) {
      this.checkVimInstances();
    } else {
      vimInstance.setActive(true);
    }

    if (!vimInstance.isActive() && vimInstance.getId() != null) {
      return vimInstance;
    }

    if (vimInstanceWithSameNameExists(vimInstance)) {
      throw new AlreadyExistingException(
          "VimInstance with name \""
              + vimInstance.getName()
              + "\" already exists in project with id: "
              + vimInstance.getProjectId());
    }

    log.info("Updating images");
    Future<Set<NFVImage>> futureImages = asyncVimManagement.updateImages(vimInstance);
    log.info("Updating networks");
    Future<Set<Network>> futureNetworks = asyncVimManagement.updateNetworks(vimInstance);
    log.info("Updating flavors");
    Future<Set<DeploymentFlavour>> futureFlavors = asyncVimManagement.updateFlavors(vimInstance);

    try {

      futureImages.get(refreshTimeout, TimeUnit.SECONDS);
      futureFlavors.get(refreshTimeout, TimeUnit.SECONDS);
      futureNetworks.get(refreshTimeout, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
      throw new VimException("Refreshing VIM went in timout: " + e.getLocalizedMessage());
    } catch (Exception e) {
      e.printStackTrace();
      throw new VimException("Refreshing VIM caused following error: " + e.getMessage());
    }
    lastUpdateVim.put(vimInstance.getId(), new Date().getTime());
    return vimRepository.save(vimInstance);
  }

  private boolean vimInstanceWithSameNameExists(VimInstance vimInstance) {
    if (vimInstance.getId() == null) {
      for (VimInstance vimInstance1 : vimRepository.findByProjectId(vimInstance.getProjectId())) {
        if (vimInstance1.getName().equals(vimInstance.getName())) {
          return true;
        }
      }
    }
    return false;
  }

  /**
   * Adds a new NFVImage to the VimInstance with id
   *
   * @param id of VimInstance
   * @param image the new NFVImage
   * @return NFVImage
   */
  @Override
  public NFVImage addImage(String id, NFVImage image, String projectId)
      throws VimException, PluginException, EntityUnreachableException, IOException,
          BadRequestException, AlreadyExistingException, NotFoundException {
    VimInstance vimInstance = vimRepository.findFirstByIdAndProjectId(id, projectId);
    if (vimInstance == null) throw new NotFoundException("No VIMInstance found with ID " + id);<commit_msg>fix vim instance upload<commit_after>/*
 * Copyright (c) 2016 Open Baton (http://www.openbaton.org)
 *
 * 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 org.openbaton.nfvo.core.api;

import java.io.IOException;
import java.net.InetAddress;
import java.net.URL;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.PostConstruct;
import org.openbaton.catalogue.mano.common.DeploymentFlavour;
import org.openbaton.catalogue.mano.descriptor.VirtualDeploymentUnit;
import org.openbaton.catalogue.mano.descriptor.VirtualNetworkFunctionDescriptor;
import org.openbaton.catalogue.mano.record.VirtualNetworkFunctionRecord;
import org.openbaton.catalogue.nfvo.ImageStatus;
import org.openbaton.catalogue.nfvo.NFVImage;
import org.openbaton.catalogue.nfvo.Network;
import org.openbaton.catalogue.nfvo.Subnet;
import org.openbaton.catalogue.nfvo.VimInstance;
import org.openbaton.exceptions.AlreadyExistingException;
import org.openbaton.exceptions.BadRequestException;
import org.openbaton.exceptions.EntityUnreachableException;
import org.openbaton.exceptions.NotFoundException;
import org.openbaton.exceptions.PluginException;
import org.openbaton.exceptions.VimException;
import org.openbaton.nfvo.repositories.ImageRepository;
import org.openbaton.nfvo.repositories.VNFDRepository;
import org.openbaton.nfvo.repositories.VNFRRepository;
import org.openbaton.nfvo.repositories.VimRepository;
import org.openbaton.nfvo.vim_interfaces.vim.VimBroker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/** Created by lto on 13/05/15. */
@Service
@Scope
@ConfigurationProperties
public class VimManagement implements org.openbaton.nfvo.core.interfaces.VimManagement {

  @Autowired private VimRepository vimRepository;

  @Autowired private VimBroker vimBroker;

  @Autowired private ImageRepository imageRepository;

  @Autowired private VNFDRepository vnfdRepository;

  @Autowired private VNFRRepository vnfrRepository;

  @Autowired private AsyncVimManagement asyncVimManagement;

  private static Map<String, Long> lastUpdateVim;

  private final Logger log = LoggerFactory.getLogger(this.getClass());

  // if set to true there will be a check if the stored Vims are still reachable every minute

  @Value("${nfvo.vim.active.check:false}")
  private boolean vimCheck;

  @Value("${nfvo.vim.delete.check.vnfr:true}")
  private boolean checkForVimInVnfr;

  //TODO change Scope to prototype
  @Value("${nfvo.vim.refresh.timout:120}")
  private int refreshTimeout;

  @Value("${nfvo.vim.cache.timout:10000}")
  private long refreshCacheTimeout;

  public boolean isCheckForVimInVnfr() {
    return checkForVimInVnfr;
  }

  public int getRefreshTimeout() {
    return refreshTimeout;
  }

  public void setRefreshTimeout(int refreshTimeout) {
    this.refreshTimeout = refreshTimeout;
  }

  @PostConstruct
  private void init() {
    lastUpdateVim = new ConcurrentHashMap<>();
  }

  @Override
  public VimInstance add(VimInstance vimInstance, String projectId)
      throws VimException, PluginException, IOException, BadRequestException,
          AlreadyExistingException {
    validateVimInstance(vimInstance);
    vimInstance.setProjectId(projectId);
    log.trace("Persisting VimInstance: " + vimInstance);
    return this.refresh(vimInstance, true);
  }

  @Override
  public void delete(String id, String projectId) throws NotFoundException, BadRequestException {

    VimInstance vimInstance = vimRepository.findFirstByIdAndProjectId(id, projectId);
    if (vimInstance == null) {
      throw new NotFoundException("Vim Instance with id " + id + " was not found");
    }
    if (checkForVimInVnfr) {
      for (VirtualNetworkFunctionRecord vnfr : vnfrRepository.findByProjectId(projectId)) {
        for (VirtualDeploymentUnit vdu : vnfr.getVdu()) {
          if (vdu.getVimInstanceName().contains(vimInstance.getName())) {
            throw new BadRequestException(
                "Cannot delete VIM Instance " + vimInstance.getName() + " while it is in use.");
          }
        }
      }
    }
    //    for (VirtualNetworkFunctionDescriptor vnfd : vnfdRepository.findByProjectId(projectId)) {
    //      for (VirtualDeploymentUnit vdu : vnfd.getVdu()) {
    //        if (vdu.getVimInstanceName().contains(vimInstance.getName())) {
    //          vdu.getVimInstanceName().remove(vimInstance.getName());
    //        }
    //      }
    //    }
    vimRepository.delete(vimInstance);
  }

  @Override
  public VimInstance update(VimInstance vimInstance, String id, String projectId)
      throws VimException, PluginException, IOException, BadRequestException,
          AlreadyExistingException, NotFoundException {
    validateVimInstance(vimInstance);
    //    vimInstance = vimRepository.save(vimInstance);
    VimInstance vimInstanceOld = vimRepository.findFirstByIdAndProjectId(id, projectId);
    if (vimInstanceOld == null)
      throw new NotFoundException("VIM Instance with ID " + id + " not found.");
    if (!vimInstanceOld.getName().equals(vimInstance.getName())) {
      for (VirtualNetworkFunctionDescriptor vnfd : vnfdRepository.findByProjectId(projectId)) {
        for (VirtualDeploymentUnit vdu : vnfd.getVdu()) {
          if (vdu.getVimInstanceName().contains(vimInstanceOld.getName())) {
            vdu.getVimInstanceName().remove(vimInstanceOld.getName());
            vdu.getVimInstanceName().add(vimInstance.getName());
          }
        }
      }
      for (VirtualNetworkFunctionRecord vnfr : vnfrRepository.findByProjectId(projectId)) {
        for (VirtualDeploymentUnit vdu : vnfr.getVdu()) {
          if (vdu.getVimInstanceName().contains(vimInstanceOld.getName())) {
            vdu.getVimInstanceName().remove(vimInstanceOld.getName());
            vdu.getVimInstanceName().add(vimInstance.getName());
          }
        }
      }
    }
    vimInstance.setProjectId(vimInstanceOld.getProjectId());
    vimInstance.setId(vimInstanceOld.getId());
    if (vimInstance.getPassword().equals("**********")) {
      vimInstance.setPassword(vimInstanceOld.getPassword());
    }
    return refresh(vimInstance, true);
    //    return vimInstance;
  }

  @Override
  public VimInstance query(String id, String projectId) {
    return vimRepository.findFirstByIdAndProjectId(id, projectId);
  }

  @Override
  public synchronized VimInstance refresh(VimInstance vimInstance, boolean force)
      throws VimException, PluginException, IOException, BadRequestException,
          AlreadyExistingException {

    if (!force) {
      long lastUpdated = 0;
      try {
        lastUpdated = lastUpdateVim.get(vimInstance.getId());
      } catch (NullPointerException ignored) {

      }
      if (lastUpdated != 0 && lastUpdated > (new Date().getTime() + refreshCacheTimeout)) {
        return vimInstance;
      }
    }

    if (vimCheck) {
      this.checkVimInstances();
    } else {
      vimInstance.setActive(true);
    }

    if (!vimInstance.isActive() && vimInstance.getId() != null) {
      return vimInstance;
    }

    if (vimInstanceWithSameNameExists(vimInstance)) {
      throw new AlreadyExistingException(
          "VimInstance with name \""
              + vimInstance.getName()
              + "\" already exists in project with id: "
              + vimInstance.getProjectId());
    }

    log.info("Updating images");
    Future<Set<NFVImage>> futureImages = asyncVimManagement.updateImages(vimInstance);
    log.info("Updating networks");
    Future<Set<Network>> futureNetworks = asyncVimManagement.updateNetworks(vimInstance);
    log.info("Updating flavors");
    Future<Set<DeploymentFlavour>> futureFlavors = asyncVimManagement.updateFlavors(vimInstance);

    try {

      futureImages.get(refreshTimeout, TimeUnit.SECONDS);
      futureFlavors.get(refreshTimeout, TimeUnit.SECONDS);
      futureNetworks.get(refreshTimeout, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
      throw new VimException("Refreshing VIM went in timout: " + e.getLocalizedMessage());
    } catch (Exception e) {
      e.printStackTrace();
      throw new VimException("Refreshing VIM caused following error: " + e.getMessage());
    }
    vimInstance = vimRepository.save(vimInstance);
    lastUpdateVim.put(vimInstance.getId(), new Date().getTime());
    return vimInstance;
  }

  private boolean vimInstanceWithSameNameExists(VimInstance vimInstance) {
    if (vimInstance.getId() == null) {
      for (VimInstance vimInstance1 : vimRepository.findByProjectId(vimInstance.getProjectId())) {
        if (vimInstance1.getName().equals(vimInstance.getName())) {
          return true;
        }
      }
    }
    return false;
  }

  /**
   * Adds a new NFVImage to the VimInstance with id
   *
   * @param id of VimInstance
   * @param image the new NFVImage
   * @return NFVImage
   */
  @Override
  public NFVImage addImage(String id, NFVImage image, String projectId)
      throws VimException, PluginException, EntityUnreachableException, IOException,
          BadRequestException, AlreadyExistingException, NotFoundException {
    VimInstance vimInstance = vimRepository.findFirstByIdAndProjectId(id, projectId);
    if (vimInstance == null) throw new NotFoundException("No VIMInstance found with ID " + id);
{'fraction_non_alphanumeric': 0.10098015778149654, 'fraction_numerical': 0.0026775041836002867, 'mean_word_length': 4.026676279740447, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1091253', 'n_tokens_mistral': 6209, 'n_tokens_neox': 6011, 'n_words': 1266}