<commit_before>package de.uks.beast.server.environment;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.openstack4j.api.Builders;
import org.openstack4j.api.OSClient;
import org.openstack4j.model.compute.Flavor;
import org.openstack4j.model.identity.Tenant;
import org.openstack4j.model.network.AttachInterfaceType;
import org.openstack4j.model.network.IPVersionType;
import org.openstack4j.model.network.Network;
import org.openstack4j.model.network.Router;
import org.openstack4j.model.network.Subnet;
import org.openstack4j.openstack.OSFactory;

import de.uks.beast.model.Hardware;
import de.uks.beast.server.BeastService;
import de.uks.beast.server.environment.model.Configuration;
import de.uks.beast.server.environment.model.ConnectionInfo;
import de.uks.beast.server.environment.model.OpenstackConfiguration;
import de.uks.beast.server.environment.model.OpenstackConnectionInfo;
import de.uks.beast.server.vm.OpenstackConnection;

public class OpenstackEnvironment extends CloudEnvironment {

	private static final Logger logger = LogManager.getLogger(OpenstackEnvironment.class);
	
	private OSClient os;
	private final BeastService service;

	public OpenstackEnvironment(BeastService service) {
		this.service = service;
	}


	/**
	 * Authenticate
	 * Authorized OSClient allows you to invoke Compute, Identity, Neutron operations.
	 * Version 2 Authentication.
	 * @return
	 */
	@Override
	public boolean authenticate() {
		logger.info("Authentication against keystone ...");
		try {
			this.os = OSFactory.builder()
					.endpoint(service.get("keystone"))
					.credentials(service.get("user"), service.get("password"))
					.tenantName(service.get("tenantName"))
					.authenticate();
		} catch (Exception e) {
			if (e.getMessage().equals("java.net.ConnectException: Connection refused")) {
				logger.error("Could not connect to keystone", e);
			}
			return false;
		}
		
		logger.info("Authenthication successfull");
		return true;
	}


	/**
	 * Setup the virtual networks and servers
	 * @param hwconf
	 * @return
	 */
	public List<? extends Configuration> createHardwareDefiniton(Hardware hwconf) {
		List<OpenstackConfiguration> configs = new ArrayList<OpenstackConfiguration>();

		for (de.uks.beast.model.Network network : hwconf.getNetworks()) {
			
			Network openstacknetwork = getOrCreateNetwork(network);
			
			for (de.uks.beast.model.Server server : network.getServers()) {
				String flavorID = "";
				boolean flavorExists = false;

				for (Flavor flavor : os.compute().flavors().list()) {
					if (flavor.getName().equals(server.buildFlavor())) {
						flavorExists = true;
						flavorID = flavor.getId();
						logger.info("Using flavor with name " + server.buildFlavor() + " (" + flavorID + ")");
					}
				}
				
				if (!flavorExists) {
					Flavor f = Builders.flavor()
							.name(server.buildFlavor())
							.ram(server.getRam())
							.vcpus(server.getCpu())
							.disk(server.getDiskSpace())
							.rxtxFactor(1.0f)
							.build();
					os.compute().flavors().create(f);
					
					for (Flavor flavor : os.compute().flavors().list()) {
						if (flavor.getName().equals(server.buildFlavor())) {
							flavorID = flavor.getId();
						}
					}
					
					logger.info("Created new Flavor with name " + server.buildFlavor()
							+ " (" + flavorID + ")");
				}
				configs.add(new OpenstackConfiguration(openstacknetwork.getId(), flavorID, server));
			}
			
		}
		
		return configs;
	}
	
	@Override
	public ArrayList<? extends ConnectionInfo> startVirtualMachine(List<? extends Configuration> configs) {
		ArrayList<OpenstackConnectionInfo> cons = new ArrayList<OpenstackConnectionInfo>();

		for (Configuration config : configs) {
			OpenstackConfiguration оc = (OpenstackConfiguration) config;
			
			// TODO: alle openstack vms holen und merken
			// Find all running Servers
//			List<? extends Server> serversBefore = os.compute().servers().list();
			
			//int nrOfMachine = (juju deploy ubuntu) - returns machine number
			
			//alle openstack vms holen
			// Find all running Servers
//			List<? extends Server> serversAfter = os.compute().servers().list();
			
		}
		
		return cons;
	}

	/*@Override
	public ArrayList<? extends ConnectionInfo> startVirtualMachine(List<? extends Configuration> configs) {
		ArrayList<OpenstackConnectionInfo> cons = new ArrayList<OpenstackConnectionInfo>();
		
		logger.info("Creating keypair for VM(s) ...");
		
		os.compute().keypairs().delete("beast-keypair");
		Keypair kp = os.compute().keypairs().create("beast-keypair", null);
		
		for (Configuration configuration : configs) {
			OpenstackConfiguration cf = (OpenstackConfiguration) configuration;
			ServerCreate sc = Builders.server()
					.name(cf.getHost())
					.flavor(cf.getId())
					.image(service.get("ubuntu-image"))
					.keypairName("beast-keypair")<commit_msg>refactoring<commit_after>package de.uks.beast.server.environment;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.openstack4j.api.Builders;
import org.openstack4j.api.OSClient;
import org.openstack4j.model.compute.Flavor;
import org.openstack4j.model.identity.Tenant;
import org.openstack4j.model.network.AttachInterfaceType;
import org.openstack4j.model.network.IPVersionType;
import org.openstack4j.model.network.Network;
import org.openstack4j.model.network.Router;
import org.openstack4j.model.network.Subnet;
import org.openstack4j.openstack.OSFactory;

import de.uks.beast.model.Hardware;
import de.uks.beast.server.BeastService;
import de.uks.beast.server.environment.model.Configuration;
import de.uks.beast.server.environment.model.ConnectionInfo;
import de.uks.beast.server.environment.model.OpenstackConfiguration;
import de.uks.beast.server.environment.model.OpenstackConnectionInfo;
import de.uks.beast.server.juju.Juju;
import de.uks.beast.server.vm.OpenstackConnection;

public class OpenstackEnvironment extends CloudEnvironment {

	private static final Logger logger = LogManager.getLogger(OpenstackEnvironment.class);
	
	private OSClient os;
	private final BeastService service;

	public OpenstackEnvironment(BeastService service) {
		this.service = service;
	}


	/**
	 * Authenticate
	 * Authorized OSClient allows you to invoke Compute, Identity, Neutron operations.
	 * Version 2 Authentication.
	 * @return
	 */
	@Override
	public boolean authenticate() {
		logger.info("Authentication against keystone ...");
		try {
			this.os = OSFactory.builder()
					.endpoint(service.get("keystone"))
					.credentials(service.get("user"), service.get("password"))
					.tenantName(service.get("tenantName"))
					.authenticate();
		} catch (Exception e) {
			if (e.getMessage().equals("java.net.ConnectException: Connection refused")) {
				logger.error("Could not connect to keystone", e);
			}
			return false;
		}
		
		logger.info("Authenthication successfull");
		return true;
	}


	/**
	 * Setup the virtual networks and servers
	 * @param hwconf
	 * @return
	 */
	public List<? extends Configuration> createHardwareDefiniton(Hardware hwconf) {
		List<OpenstackConfiguration> configs = new ArrayList<OpenstackConfiguration>();

		for (de.uks.beast.model.Network network : hwconf.getNetworks()) {
			
			Network openstacknetwork = getOrCreateNetwork(network);
			
			for (de.uks.beast.model.Server server : network.getServers()) {
				String flavorID = "";
				boolean flavorExists = false;

				for (Flavor flavor : os.compute().flavors().list()) {
					if (flavor.getName().equals(server.buildFlavor())) {
						flavorExists = true;
						flavorID = flavor.getId();
						logger.info("Using flavor with name " + server.buildFlavor() + " (" + flavorID + ")");
					}
				}
				
				if (!flavorExists) {
					Flavor f = Builders.flavor()
							.name(server.buildFlavor())
							.ram(server.getRam())
							.vcpus(server.getCpu())
							.disk(server.getDiskSpace())
							.rxtxFactor(1.0f)
							.build();
					os.compute().flavors().create(f);
					
					for (Flavor flavor : os.compute().flavors().list()) {
						if (flavor.getName().equals(server.buildFlavor())) {
							flavorID = flavor.getId();
						}
					}
					
					logger.info("Created new Flavor with name " + server.buildFlavor()
							+ " (" + flavorID + ")");
				}
				configs.add(new OpenstackConfiguration(openstacknetwork.getId(), flavorID, server));
			}
			
		}
		
		return configs;
	}
	
	@Override
	public ArrayList<? extends ConnectionInfo> startVirtualMachine(List<? extends Configuration> configs) {
		ArrayList<OpenstackConnectionInfo> cons = new ArrayList<OpenstackConnectionInfo>();

		for (Configuration config : configs) {
			OpenstackConfiguration оc = (OpenstackConfiguration) config;
			
			// TODO: 
			/*
			alle openstack vms holen und merken
			Find all running Servers
			int nrOfMachine = (juju deploy ubuntu) - returns machine number
			alle openstack vms holen
			Find all running Servers
			 */
			
			// add a blank machine, and returns its number in juju environment
			try {
				int machineNumber = Juju.addMachine();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		return cons;
	}

	/*@Override
	public ArrayList<? extends ConnectionInfo> startVirtualMachine(List<? extends Configuration> configs) {
		ArrayList<OpenstackConnectionInfo> cons = new ArrayList<OpenstackConnectionInfo>();
		
		logger.info("Creating keypair for VM(s) ...");
		
		os.compute().keypairs().delete("beast-keypair");
		Keypair kp = os.compute().keypairs().create("beast-keypair", null);
		
		for (Configuration configuration : configs) {
			OpenstackConfiguration cf = (OpenstackConfiguration) configuration;
			ServerCreate sc = Builders.server()
					.name(cf.getHost())
					.flavor(cf.getId())
					.image(service.get("ubuntu-image"))
					.keypairName("beast-keypair")
{'fraction_non_alphanumeric': 0.12589214908802537, 'fraction_numerical': 0.002973830293417922, 'mean_word_length': 3.9166666666666665, 'pattern_counts': {'":': 0, '<': 27, '<?xml version=': 0, '>': 27, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '2279857', 'n_tokens_mistral': 3631, 'n_tokens_neox': 2987, 'n_words': 618}