http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/75178c77/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachBridgedAdapterToMachine.java ---------------------------------------------------------------------- diff --git a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachBridgedAdapterToMachine.java b/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachBridgedAdapterToMachine.java deleted file mode 100644 index 676f5b6..0000000 --- a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachBridgedAdapterToMachine.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.virtualbox.functions; - -import static org.virtualbox_4_2.NetworkAttachmentType.Bridged; - -import org.jclouds.virtualbox.domain.NetworkInterfaceCard; -import org.virtualbox_4_2.IMachine; -import org.virtualbox_4_2.INetworkAdapter; - -import com.google.common.base.Function; - -public class AttachBridgedAdapterToMachine implements Function<IMachine, Void> { - - private NetworkInterfaceCard networkInterfaceCard; - - - public AttachBridgedAdapterToMachine(NetworkInterfaceCard networkInterfaceCard) { - this.networkInterfaceCard = networkInterfaceCard; - } - - @Override - public Void apply(IMachine machine) { - INetworkAdapter iNetworkAdapter = machine.getNetworkAdapter(networkInterfaceCard.getSlot()); - iNetworkAdapter.setAttachmentType(Bridged); - iNetworkAdapter.setMACAddress(networkInterfaceCard.getNetworkAdapter().getMacAddress()); - iNetworkAdapter.setBridgedInterface(networkInterfaceCard.getHostInterfaceName()); - iNetworkAdapter.setEnabled(networkInterfaceCard.isEnabled()); - machine.saveSettings(); - return null; - } -}
http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/75178c77/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachHostOnlyAdapter.java ---------------------------------------------------------------------- diff --git a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachHostOnlyAdapter.java b/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachHostOnlyAdapter.java deleted file mode 100644 index b283681..0000000 --- a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachHostOnlyAdapter.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.virtualbox.functions; - -import org.jclouds.virtualbox.domain.NetworkInterfaceCard; -import org.virtualbox_4_2.IMachine; -import org.virtualbox_4_2.INetworkAdapter; -import org.virtualbox_4_2.NetworkAttachmentType; - -import com.google.common.base.Function; - -public class AttachHostOnlyAdapter implements Function<IMachine, Void> { - - private NetworkInterfaceCard networkInterfaceCard; - - public AttachHostOnlyAdapter(NetworkInterfaceCard networkInterfaceCard) { - this.networkInterfaceCard = networkInterfaceCard; - } - - @Override - public Void apply(IMachine machine) { - INetworkAdapter iNetworkAdapter = machine.getNetworkAdapter(networkInterfaceCard.getSlot()); - iNetworkAdapter.setAttachmentType(NetworkAttachmentType.HostOnly); - iNetworkAdapter.setMACAddress(networkInterfaceCard.getNetworkAdapter().getMacAddress()); - iNetworkAdapter.setHostOnlyInterface(networkInterfaceCard.getHostInterfaceName()); - iNetworkAdapter.setEnabled(networkInterfaceCard.isEnabled()); - machine.saveSettings(); - return null; - } - -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/75178c77/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachMediumToMachineIfNotAlreadyAttached.java ---------------------------------------------------------------------- diff --git a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachMediumToMachineIfNotAlreadyAttached.java b/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachMediumToMachineIfNotAlreadyAttached.java deleted file mode 100644 index a8b6af9..0000000 --- a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachMediumToMachineIfNotAlreadyAttached.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.virtualbox.functions; - -import org.jclouds.virtualbox.domain.DeviceDetails; -import org.virtualbox_4_2.IMachine; -import org.virtualbox_4_2.IMedium; -import org.virtualbox_4_2.VBoxException; - -import com.google.common.base.Function; - -public class AttachMediumToMachineIfNotAlreadyAttached implements Function<IMachine, Void> { - - private final DeviceDetails device; - private final IMedium medium; - private final String controllerName; - - public AttachMediumToMachineIfNotAlreadyAttached(DeviceDetails device, IMedium medium, String controllerName) { - this.device = device; - this.medium = medium; - this.controllerName = controllerName; - } - - @Override - public Void apply(IMachine machine) { - try { - machine.attachDevice(controllerName, device.getPort(), device.getDeviceSlot(), device.getDeviceType(), medium); - machine.saveSettings(); - } catch (VBoxException e) { - if (!alreadyAttached(e)) - throw e; - } - return null; - } - - private boolean alreadyAttached(VBoxException e) { - System.out.println(medium.getName() + " " + e.getMessage()); - return e.getMessage().contains("is already attached to port"); - } - -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/75178c77/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachNATAdapterToMachineIfNotAlreadyExists.java ---------------------------------------------------------------------- diff --git a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachNATAdapterToMachineIfNotAlreadyExists.java b/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachNATAdapterToMachineIfNotAlreadyExists.java deleted file mode 100644 index ec5210c..0000000 --- a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachNATAdapterToMachineIfNotAlreadyExists.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.virtualbox.functions; - -import static org.virtualbox_4_2.NetworkAttachmentType.NAT; - -import org.jclouds.virtualbox.domain.NetworkInterfaceCard; -import org.jclouds.virtualbox.domain.RedirectRule; -import org.virtualbox_4_2.IMachine; -import org.virtualbox_4_2.INetworkAdapter; -import org.virtualbox_4_2.VBoxException; - -import com.google.common.base.Function; -import com.google.common.base.Splitter; -import com.google.common.collect.Iterables; - -public class AttachNATAdapterToMachineIfNotAlreadyExists implements Function<IMachine, Void> { - - private NetworkInterfaceCard networkInterfaceCard; - - public AttachNATAdapterToMachineIfNotAlreadyExists(NetworkInterfaceCard networkInterfaceCard) { - this.networkInterfaceCard = networkInterfaceCard; - } - - @Override - public Void apply(IMachine machine) { - INetworkAdapter iNetworkAdapter = machine.getNetworkAdapter(networkInterfaceCard.getSlot()); - // clean up previously set rules - for (String redirectRule : iNetworkAdapter.getNATEngine().getRedirects()) { - String redirectRuleName = Iterables.getFirst(Splitter.on(",").split(redirectRule), null); - if (redirectRuleName != null) { - iNetworkAdapter.getNATEngine().removeRedirect(redirectRuleName); - } - } - iNetworkAdapter.setAttachmentType(NAT); - for (RedirectRule rule : networkInterfaceCard.getNetworkAdapter().getRedirectRules()) { - try { - String ruleName = String.format("%s@%s:%s->%s:%s", rule.getProtocol(), rule.getHost(), rule.getHostPort(), - rule.getGuest(), rule.getGuestPort()); - iNetworkAdapter.getNATEngine().addRedirect(ruleName, rule.getProtocol(), rule.getHost(), rule.getHostPort(), - rule.getGuest(), rule.getGuestPort()); - } catch (VBoxException e) { - if (!e.getMessage().contains("already exists")) - throw e; - } - } - iNetworkAdapter.setEnabled(networkInterfaceCard.isEnabled()); - machine.saveSettings(); - return null; - } -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/75178c77/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachNicToMachine.java ---------------------------------------------------------------------- diff --git a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachNicToMachine.java b/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachNicToMachine.java deleted file mode 100644 index 04f2a87..0000000 --- a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachNicToMachine.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.virtualbox.functions; - -import static com.google.common.base.Preconditions.checkNotNull; - -import org.jclouds.virtualbox.domain.NetworkInterfaceCard; -import org.jclouds.virtualbox.util.MachineUtils; -import org.virtualbox_4_2.NetworkAttachmentType; - -import com.google.common.base.Function; - -public class AttachNicToMachine implements Function<NetworkInterfaceCard, Void> { - - private final String vmName; - private final MachineUtils machineUtils; - - public AttachNicToMachine(String vmName, MachineUtils machineUtils) { - this.vmName = checkNotNull(vmName, "vmName can't be null"); - this.machineUtils = checkNotNull(machineUtils, "machineUtils can't be null"); - } - - @Override - public Void apply(NetworkInterfaceCard nic) { - if (hasNatAdapter(nic)) { - return machineUtils.writeLockMachineAndApply(vmName, new AttachNATAdapterToMachineIfNotAlreadyExists(nic)); - } else if (hasBridgedAdapter(nic)) { - return machineUtils.writeLockMachineAndApply(vmName, new AttachBridgedAdapterToMachine(nic)); - } else if (hasHostOnlyAdapter(nic)) { - return machineUtils.writeLockMachineAndApply(vmName, new AttachHostOnlyAdapter(nic)); - } else - return null; - } - - private boolean hasNatAdapter(NetworkInterfaceCard nic) { - return nic.getNetworkAdapter().getNetworkAttachmentType().equals(NetworkAttachmentType.NAT); - } - - private boolean hasBridgedAdapter(NetworkInterfaceCard nic) { - return nic.getNetworkAdapter().getNetworkAttachmentType().equals(NetworkAttachmentType.Bridged); - } - - private boolean hasHostOnlyAdapter(NetworkInterfaceCard nic) { - return nic.getNetworkAdapter().getNetworkAttachmentType().equals(NetworkAttachmentType.HostOnly); - } -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/75178c77/virtualbox/src/main/java/org/jclouds/virtualbox/functions/BridgedIfStringToBridgedIf.java ---------------------------------------------------------------------- diff --git a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/BridgedIfStringToBridgedIf.java b/virtualbox/src/main/java/org/jclouds/virtualbox/functions/BridgedIfStringToBridgedIf.java deleted file mode 100644 index 0934797..0000000 --- a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/BridgedIfStringToBridgedIf.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.virtualbox.functions; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.util.Map; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.virtualbox.domain.BridgedIf; - -import com.google.common.base.Function; -import com.google.common.base.Splitter; -import com.google.common.collect.Iterables; - -@Singleton -public class BridgedIfStringToBridgedIf implements Function<String, BridgedIf> { - - private static final String BRIDGED_IF_STATUS = "Status"; - private static final String BRIDGED_IF_MEDIUM_TYPE = "MediumType"; - private static final String BRIDGED_IF_NETWORK_MASK = "NetworkMask"; - private static final String BRIDGED_IF_IP_ADDRESS = "IPAddress"; - private static final String BRIDGED_IF_GUID = "GUID"; - private static final String BRIDGED_IF_NAME = "Name"; - - @Inject - public BridgedIfStringToBridgedIf() { - } - - @Override - public BridgedIf apply(String rawBridgedIf) { - checkNotNull(rawBridgedIf, "bridged interface can't be null"); - - String transformedBridgedIf = transformRawBridgedIf(rawBridgedIf); - Map<String, String> bridgedIfMap = Splitter.on("\n") - .omitEmptyStrings().withKeyValueSeparator("=") - .split(transformedBridgedIf); - - return BridgedIf - .builder() - .name(getValueFromMap(bridgedIfMap, BRIDGED_IF_NAME)) - .guid(getValueFromMap(bridgedIfMap, BRIDGED_IF_GUID)) - .ip(getValueFromMap(bridgedIfMap, BRIDGED_IF_IP_ADDRESS)) - .networkMask(getValueFromMap(bridgedIfMap, BRIDGED_IF_NETWORK_MASK)) - .mediumType(getValueFromMap(bridgedIfMap, BRIDGED_IF_MEDIUM_TYPE)) - .status(getValueFromMap(bridgedIfMap, BRIDGED_IF_STATUS)) - .build(); - } - - private String getValueFromMap(Map<String, String> map, String key) { - return map.get(key).trim(); - } - - /** - * This is an helper to simplify the split step of the raw bridgedIf - * Substitute first ':' with '=' - * - * @param rawBridgedIf - * @return - */ - private String transformRawBridgedIf(String rawBridgedIf) { - Iterable<String> transformedLines = Iterables.transform( - Splitter.on("\n").split(rawBridgedIf), - new Function<String, String>() { - - @Override - public String apply(String line) { - return line.replaceFirst(":", "="); - } - - }); - - StringBuilder stringBuilder = new StringBuilder(); - - for (String line : transformedLines) { - stringBuilder.append(line + "\n"); - } - return stringBuilder.toString(); - } - -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/75178c77/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CloneAndRegisterMachineFromIMachineIfNotAlreadyExists.java ---------------------------------------------------------------------- diff --git a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CloneAndRegisterMachineFromIMachineIfNotAlreadyExists.java b/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CloneAndRegisterMachineFromIMachineIfNotAlreadyExists.java deleted file mode 100644 index 1168382..0000000 --- a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CloneAndRegisterMachineFromIMachineIfNotAlreadyExists.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.virtualbox.functions; - -import static org.jclouds.virtualbox.config.VirtualBoxConstants.GUEST_OS_PASSWORD; -import static org.jclouds.virtualbox.config.VirtualBoxConstants.GUEST_OS_USER; - -import java.util.List; - -import javax.annotation.Resource; -import javax.inject.Named; - -import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.logging.Logger; -import org.jclouds.virtualbox.config.VirtualBoxConstants; -import org.jclouds.virtualbox.domain.CloneSpec; -import org.jclouds.virtualbox.domain.NetworkInterfaceCard; -import org.jclouds.virtualbox.domain.NetworkSpec; -import org.jclouds.virtualbox.domain.VmSpec; -import org.jclouds.virtualbox.util.MachineUtils; -import org.virtualbox_4_2.CloneMode; -import org.virtualbox_4_2.CloneOptions; -import org.virtualbox_4_2.IMachine; -import org.virtualbox_4_2.IProgress; -import org.virtualbox_4_2.ISnapshot; -import org.virtualbox_4_2.VBoxException; -import org.virtualbox_4_2.VirtualBoxManager; - -import com.google.common.base.Function; -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.inject.Inject; - -/** - * CloneAndRegisterMachineFromIMachineIfNotAlreadyExists will take care of the followings: - cloning - * the master - register the clone machine. - */ -public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements Function<CloneSpec, IMachine> { - - @Resource - @Named(ComputeServiceConstants.COMPUTE_LOGGER) - protected Logger logger = Logger.NULL; - - private final Supplier<VirtualBoxManager> manager; - private final String workingDir; - private final MachineUtils machineUtils; - - @Inject - public CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(Supplier<VirtualBoxManager> manager, - @Named(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR) String workingDir, MachineUtils machineUtils) { - this.manager = manager; - this.workingDir = workingDir; - this.machineUtils = machineUtils; - } - - @Override - public IMachine apply(CloneSpec cloneSpec) { - VmSpec vmSpec = cloneSpec.getVmSpec(); - try { - manager.get().getVBox().findMachine(vmSpec.getVmName()); - throw new IllegalStateException("Machine " + vmSpec.getVmName() + " is already registered."); - } catch (VBoxException e) { - if (machineNotFoundException(e)) - return cloneMachine(cloneSpec); - else - throw e; - } - } - - private boolean machineNotFoundException(VBoxException e) { - return e.getMessage().contains("VirtualBox error: Could not find a registered machine named ") - || e.getMessage().contains("Could not find a registered machine with UUID {"); - } - - private IMachine cloneMachine(CloneSpec cloneSpec) { - VmSpec vmSpec = cloneSpec.getVmSpec(); - NetworkSpec networkSpec = cloneSpec.getNetworkSpec(); - boolean isLinkedClone = cloneSpec.isLinked(); - IMachine master = cloneSpec.getMaster(); - String flags = ""; - List<String> groups = ImmutableList.of(); - String group = ""; - String settingsFile = manager.get().getVBox().composeMachineFilename(vmSpec.getVmName(), group , flags , workingDir); - IMachine clonedMachine = manager - .get() - .getVBox() - .createMachine(settingsFile, vmSpec.getVmName(), groups, vmSpec.getOsTypeId(), flags); - List<CloneOptions> options = Lists.newArrayList(); - if (isLinkedClone) - options.add(CloneOptions.Link); - - ISnapshot currentSnapshot = new TakeSnapshotIfNotAlreadyAttached(manager, - "snapshotName", "snapshotDesc", logger).apply(master); - IProgress progress = currentSnapshot.getMachine().cloneTo(clonedMachine, - CloneMode.MachineState, options); - progress.waitForCompletion(-1); - - // memory may not be the same as the master vm - clonedMachine.setMemorySize(cloneSpec.getVmSpec().getMemory()); - - // registering - manager.get().getVBox().registerMachine(clonedMachine); - - // Networking - for (NetworkInterfaceCard networkInterfaceCard : networkSpec.getNetworkInterfaceCards()) { - new AttachNicToMachine(vmSpec.getVmName(), machineUtils).apply(networkInterfaceCard); - } - - // set only once the creds for this machine, same coming from its master - logger.debug("<< storing guest credentials on vm(%s) as extra data", clonedMachine.getName()); - String masterUsername = master.getExtraData(GUEST_OS_USER); - String masterPassword = master.getExtraData(GUEST_OS_PASSWORD); - clonedMachine.setExtraData(GUEST_OS_USER, masterUsername); - clonedMachine.setExtraData(GUEST_OS_PASSWORD, masterPassword); - - return clonedMachine; - } -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/75178c77/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndInstallVm.java ---------------------------------------------------------------------- diff --git a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndInstallVm.java b/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndInstallVm.java deleted file mode 100644 index 2d1a03e..0000000 --- a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndInstallVm.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.virtualbox.functions; - -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.base.Splitter; -import com.google.common.base.Stopwatch; -import com.google.common.collect.Iterables; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.inject.Inject; -import org.jclouds.compute.domain.ExecResponse; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.options.RunScriptOptions; -import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.logging.Logger; -import org.jclouds.rest.annotations.BuildVersion; -import org.jclouds.ssh.SshClient; -import org.jclouds.virtualbox.domain.IsoSpec; -import org.jclouds.virtualbox.domain.MasterSpec; -import org.jclouds.virtualbox.domain.VmSpec; -import org.jclouds.virtualbox.statements.InstallGuestAdditions; -import org.jclouds.virtualbox.util.MachineController; -import org.jclouds.virtualbox.util.MachineUtils; -import org.virtualbox_4_2.DeviceType; -import org.virtualbox_4_2.IMachine; -import org.virtualbox_4_2.IMediumAttachment; - -import javax.annotation.Resource; -import javax.inject.Named; -import javax.inject.Singleton; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; -import static com.google.common.collect.Iterables.transform; -import static org.jclouds.scriptbuilder.domain.Statements.call; -import static org.jclouds.virtualbox.config.VirtualBoxConstants.GUEST_OS_PASSWORD; -import static org.jclouds.virtualbox.config.VirtualBoxConstants.GUEST_OS_USER; -import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_PRECONFIGURATION_URL; - -@Singleton -public class CreateAndInstallVm implements Function<MasterSpec, IMachine> { - - @Resource - @Named(ComputeServiceConstants.COMPUTE_LOGGER) - protected Logger logger = Logger.NULL; - - private final CreateAndRegisterMachineFromIsoIfNotAlreadyExists createAndRegisterMachineFromIsoIfNotAlreadyExists; - private final Predicate<SshClient> sshResponds; - private final Function<IMachine, SshClient> sshClientForIMachine; - private final MachineUtils machineUtils; - private final IMachineToNodeMetadata imachineToNodeMetadata; - private final MachineController machineController; - private final String version; - private final String preconfigurationUrl; - - @Inject - public CreateAndInstallVm( - CreateAndRegisterMachineFromIsoIfNotAlreadyExists CreateAndRegisterMachineFromIsoIfNotAlreadyExists, - IMachineToNodeMetadata imachineToNodeMetadata, Predicate<SshClient> sshResponds, - Function<IMachine, SshClient> sshClientForIMachine, MachineUtils machineUtils, - MachineController machineController, @BuildVersion String version, - @Named(VIRTUALBOX_PRECONFIGURATION_URL) String preconfigurationUrl) { - this.createAndRegisterMachineFromIsoIfNotAlreadyExists = CreateAndRegisterMachineFromIsoIfNotAlreadyExists; - this.sshResponds = sshResponds; - this.sshClientForIMachine = sshClientForIMachine; - this.machineUtils = machineUtils; - this.imachineToNodeMetadata = imachineToNodeMetadata; - this.machineController = machineController; - this.version = Iterables.get(Splitter.on('-').split(version), 0); - this.preconfigurationUrl = preconfigurationUrl; - } - - @Override - public IMachine apply(MasterSpec masterSpec) { - VmSpec vmSpec = masterSpec.getVmSpec(); - IsoSpec isoSpec = masterSpec.getIsoSpec(); - String masterName = vmSpec.getVmName(); - IMachine masterMachine = - checkNotNull(createAndRegisterMachineFromIsoIfNotAlreadyExists.apply(masterSpec), "master machine"); - // Launch machine and wait for it to come online - machineController.ensureMachineIsLaunched(masterName); - String installationKeySequence = isoSpec.getInstallationKeySequence().replace("PRECONFIGURATION_URL", - preconfigurationUrl); - configureOsInstallationWithKeyboardSequence(masterName, installationKeySequence); - - masterMachine.setExtraData(GUEST_OS_USER, masterSpec.getLoginCredentials().getUser()); - masterMachine.setExtraData(GUEST_OS_PASSWORD, masterSpec.getLoginCredentials().getPassword()); - - SshClient client = sshClientForIMachine.apply(masterMachine); - logger.debug(">> awaiting installation to finish node(%s)", masterName); - Stopwatch stopwatch = Stopwatch.createUnstarted(); - stopwatch.start(); - checkState(sshResponds.apply(client), "timed out waiting for guest %s to be accessible via ssh", masterName); - stopwatch.stop(); - logger.debug(String.format("Elapsed time for the OS installation: %d minutes", TimeUnit.SECONDS.convert(stopwatch.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS))); - NodeMetadata nodeMetadata = imachineToNodeMetadata.apply(masterMachine); - - logger.debug(">> awaiting post-installation actions on vm: %s", masterName); - ListenableFuture<ExecResponse> execCleanup = machineUtils.runScriptOnNode(nodeMetadata, - call("cleanupUdevIfNeeded"), RunScriptOptions.NONE); - ExecResponse cleanupResponse = Futures.getUnchecked(execCleanup); - checkState(cleanupResponse.getExitStatus() == 0, "post-installation actions on vm(%s) failed", masterName); - - logger.debug(">> awaiting installation of guest additions on vm: %s", masterName); - ListenableFuture<ExecResponse> execInstallGA = machineUtils.runScriptOnNode(nodeMetadata, - new InstallGuestAdditions(vmSpec, version), RunScriptOptions.NONE); - ExecResponse execInstallGAResponse = Futures.getUnchecked(execInstallGA); - checkState(execInstallGAResponse.getExitStatus() == 0, "exec installation of guest additions on vm(%s) " + - "failed", masterName); - - logger.debug(">> check installation of guest additions on vm: %s", masterName); - ListenableFuture<ExecResponse> checkGAinstallation = machineUtils.runScriptOnNode(nodeMetadata, - call("checkVBoxService"), RunScriptOptions.NONE); - ExecResponse checkGAinstallationResponse = Futures.getUnchecked(checkGAinstallation); - checkState(checkGAinstallationResponse.getExitStatus() == 0, "check installation of guest additions on vm(%s) " + - "failed", masterName); - - machineController.ensureMachineIsShutdown(masterName); - - // detach DVD and ISOs, if needed - Iterable<IMediumAttachment> mediumAttachments = Iterables.filter( - masterMachine.getMediumAttachmentsOfController("IDE Controller"), - new Predicate<IMediumAttachment>() { - public boolean apply(IMediumAttachment in) { - return in.getMedium() != null - && in.getMedium().getDeviceType() - .equals(DeviceType.DVD); - } - }); - for (IMediumAttachment iMediumAttachment : mediumAttachments) { - logger.debug("<< iMedium(%s) detached from (%s)", iMediumAttachment.getMedium() - .getName(), masterMachine.getName()); - machineUtils.sharedLockMachineAndApply( - masterMachine.getName(), - new DetachDistroMediumFromMachine(iMediumAttachment - .getController(), iMediumAttachment.getPort(), - iMediumAttachment.getDevice())); - } - return masterMachine; - } - - private void configureOsInstallationWithKeyboardSequence(String vmName, String installationKeySequence) { - Iterable<List<Integer>> scancodelist = transform(Splitter.on(" ").split(installationKeySequence), - new StringToKeyCode()); - for (List<Integer> scancodes : scancodelist) { - machineUtils.sharedLockMachineAndApplyToSession(vmName, new SendScancodes(scancodes)); - } - } - -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/75178c77/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExists.java ---------------------------------------------------------------------- diff --git a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExists.java b/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExists.java deleted file mode 100644 index 24ebeb2..0000000 --- a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExists.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.virtualbox.functions; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.virtualbox.util.MachineUtils.machineNotFoundException; - -import java.io.File; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import com.google.common.collect.ImmutableMap; -import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.logging.Logger; -import org.jclouds.virtualbox.config.VirtualBoxConstants; -import org.jclouds.virtualbox.domain.DeviceDetails; -import org.jclouds.virtualbox.domain.HardDisk; -import org.jclouds.virtualbox.domain.IsoImage; -import org.jclouds.virtualbox.domain.MasterSpec; -import org.jclouds.virtualbox.domain.NetworkInterfaceCard; -import org.jclouds.virtualbox.domain.NetworkSpec; -import org.jclouds.virtualbox.domain.StorageController; -import org.jclouds.virtualbox.domain.VmSpec; -import org.jclouds.virtualbox.util.MachineUtils; -import org.virtualbox_4_2.AccessMode; -import org.virtualbox_4_2.DeviceType; -import org.virtualbox_4_2.IMachine; -import org.virtualbox_4_2.IMedium; -import org.virtualbox_4_2.IVirtualBox; -import org.virtualbox_4_2.VBoxException; -import org.virtualbox_4_2.VirtualBoxManager; - -import com.google.common.base.Function; -import com.google.common.base.Supplier; -import com.google.common.collect.Lists; - -@Singleton -public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Function<MasterSpec, IMachine> { - - @Resource - @Named(ComputeServiceConstants.COMPUTE_LOGGER) - protected Logger logger = Logger.NULL; - - private final Supplier<VirtualBoxManager> manager; - private final MachineUtils machineUtils; - - private final String workingDir; - - @Inject - public CreateAndRegisterMachineFromIsoIfNotAlreadyExists(Supplier<VirtualBoxManager> manager, - MachineUtils machineUtils, @Named(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR) String workingDir) { - this.manager = manager; - this.machineUtils = machineUtils; - this.workingDir = workingDir; - } - - @Override - public IMachine apply(MasterSpec masterSpec) { - final IVirtualBox vBox = manager.get().getVBox(); - String vmName = masterSpec.getVmSpec().getVmName(); - String vmId = masterSpec.getVmSpec().getVmId(); - - try { - vBox.findMachine(vmId); - throw new IllegalStateException("Machine " + vmName + " is already registered."); - } catch (VBoxException e) { - if (machineNotFoundException(e)) - return createMachine(vBox, masterSpec); - else - throw e; - } - } - - private IMachine createMachine(IVirtualBox vBox, MasterSpec masterSpec) { - VmSpec vmSpec = masterSpec.getVmSpec(); - String flags = ""; - List<String> groups = Lists.newArrayList(); - String group = ""; - String settingsFile = manager.get().getVBox().composeMachineFilename(vmSpec.getVmName(), group , flags , workingDir); - - IMachine newMachine = vBox.createMachine(settingsFile, vmSpec.getVmName(), groups, vmSpec.getOsTypeId(), flags); - - manager.get().getVBox().registerMachine(newMachine); - ensureConfiguration(masterSpec); - return newMachine; - } - - private void ensureConfiguration(MasterSpec machineSpec) { - VmSpec vmSpec = machineSpec.getVmSpec(); - NetworkSpec networkSpec = machineSpec.getNetworkSpec(); - String vmName = vmSpec.getVmName(); - - // Change BootOrder - Map<Long, DeviceType> positionAndDeviceType = ImmutableMap.of(1l, DeviceType.HardDisk); - ensureMachineHasDesiredBootOrder(vmName, positionAndDeviceType); - - // Change RAM - ensureMachineHasMemory(vmName, vmSpec.getMemory()); - - Set<StorageController> controllers = vmSpec.getControllers(); - if (controllers.isEmpty()) { - throw new IllegalStateException(missingIDEControllersMessage(vmSpec)); - } - StorageController controller = controllers.iterator().next(); - ensureMachineHasStorageControllerNamed(vmName, controller); - setupHardDisksForController(vmName, controller); - setupDvdsForController(vmSpec, vmName, controller); - - // Networking - for (NetworkInterfaceCard networkInterfaceCard : networkSpec.getNetworkInterfaceCards()) { - new AttachNicToMachine(vmName, machineUtils).apply(networkInterfaceCard); - } - } - - private void setupDvdsForController(VmSpec vmSpecification, String vmName, StorageController controller) { - Set<IsoImage> dvds = controller.getIsoImages(); - for (IsoImage dvd : dvds) { - String dvdSource = dvd.getSourcePath(); - final IMedium dvdMedium = manager.get().getVBox() - .openMedium(dvdSource, DeviceType.DVD, AccessMode.ReadOnly, vmSpecification.isForceOverwrite()); - ensureMachineDevicesAttached(vmName, dvdMedium, dvd.getDeviceDetails(), controller.getName()); - } - } - - private void ensureMachineDevicesAttached(String vmName, IMedium medium, DeviceDetails deviceDetails, - String controllerName) { - machineUtils.writeLockMachineAndApply(vmName, new AttachMediumToMachineIfNotAlreadyAttached(deviceDetails, - medium, controllerName)); - } - - private String missingIDEControllersMessage(VmSpec vmSpecification) { - return String - .format("First controller is not an IDE controller. Please verify that the VM spec is a correct master node: %s", - vmSpecification); - } - - private void setupHardDisksForController(String vmName, StorageController controller) { - Set<HardDisk> hardDisks = controller.getHardDisks(); - for (HardDisk hardDisk : hardDisks) { - String sourcePath = hardDisk.getDiskPath(); - if (new File(sourcePath).exists()) { - boolean deleted = new File(sourcePath).delete(); - if (!deleted) { - logger.error(String.format("File %s could not be deleted.", sourcePath)); - } - } - IMedium medium = new CreateMediumIfNotAlreadyExists(manager, machineUtils, true).apply(hardDisk); - ensureMachineDevicesAttached(vmName, medium, hardDisk.getDeviceDetails(), controller.getName()); - } - } - - private void ensureMachineHasDesiredBootOrder(String vmName, Map<Long, DeviceType> positionAndDeviceType) { - machineUtils.writeLockMachineAndApply(vmName, new ApplyBootOrderToMachine(positionAndDeviceType)); - } - - private void ensureMachineHasMemory(String vmName, final long memorySize) { - machineUtils.writeLockMachineAndApply(vmName, new ApplyMemoryToMachine(memorySize)); - } - - public void ensureMachineHasStorageControllerNamed(String vmName, StorageController storageController) { - machineUtils.writeLockMachineAndApply(vmName, - new AddIDEControllerIfNotExists(checkNotNull(storageController, "storageController can't be null"))); - } -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/75178c77/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateMediumIfNotAlreadyExists.java ---------------------------------------------------------------------- diff --git a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateMediumIfNotAlreadyExists.java b/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateMediumIfNotAlreadyExists.java deleted file mode 100644 index ec0995a..0000000 --- a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateMediumIfNotAlreadyExists.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.virtualbox.functions; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.virtualbox.domain.HardDisk; -import org.jclouds.virtualbox.util.MachineUtils; -import org.virtualbox_4_2.AccessMode; -import org.virtualbox_4_2.DeviceType; -import org.virtualbox_4_2.IMachine; -import org.virtualbox_4_2.IMedium; -import org.virtualbox_4_2.IMediumAttachment; -import org.virtualbox_4_2.IProgress; -import org.virtualbox_4_2.IVirtualBox; -import org.virtualbox_4_2.VBoxException; -import org.virtualbox_4_2.VirtualBoxManager; - -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.base.Supplier; -import com.google.common.collect.Iterables; - -@Singleton -public class CreateMediumIfNotAlreadyExists implements Function<HardDisk, IMedium> { - - private final Supplier<VirtualBoxManager> manager; - private final MachineUtils machineUtils; - private final boolean overwriteIfExists; - - @Inject - public CreateMediumIfNotAlreadyExists(Supplier<VirtualBoxManager> manager, MachineUtils machineUtils, boolean overwriteIfExists) { - this.manager = manager; - this.machineUtils = machineUtils; - this.overwriteIfExists = overwriteIfExists; - } - - public static final Pattern ATTACHED_PATTERN = Pattern.compile(".*is still attached.*: ([-0-9a-f]+) .*"); - - @Override - public IMedium apply(HardDisk hardDisk) { - IVirtualBox vBox = manager.get().getVBox(); - try { - String diskPath = hardDisk.getDiskPath(); - final IMedium medium = vBox.openMedium(diskPath, DeviceType.HardDisk, AccessMode.ReadWrite, false); - if (overwriteIfExists) { - try { - deleteMediumAndBlockUntilComplete(medium); - } catch (VBoxException e) { - onAlreadyAttachedExceptionDetachOrPropagate(vBox, medium, e); - } - return createNewMedium(vBox, hardDisk); - } else { - throw new IllegalStateException("Medium for path " + diskPath + " already exists."); - } - } catch (VBoxException e) { - if (notFoundException(e)) - return createNewMedium(vBox, hardDisk); - throw e; - } - } - - private void onAlreadyAttachedExceptionDetachOrPropagate(IVirtualBox vBox, final IMedium medium, VBoxException e) { - Matcher matcher = ATTACHED_PATTERN.matcher(e.getMessage()); - if (matcher.find()) { - String machineId = matcher.group(1); - IMachine immutableMachine = vBox.findMachine(machineId); - IMediumAttachment mediumAttachment = Iterables.find(immutableMachine.getMediumAttachments(), - new Predicate<IMediumAttachment>() { - public boolean apply(IMediumAttachment in) { - return in.getMedium().getId().equals(medium.getId()); - } - }); - machineUtils.writeLockMachineAndApply(immutableMachine.getName(), new DetachDistroMediumFromMachine( - mediumAttachment.getController(), mediumAttachment.getPort(), mediumAttachment.getDevice())); - deleteMediumAndBlockUntilComplete(medium); - } else { - throw e; - } - } - - void deleteMediumAndBlockUntilComplete(IMedium medium) { - final IProgress progress = medium.deleteStorage(); - progress.waitForCompletion(-1); - } - - private IMedium createNewMedium(IVirtualBox vBox, HardDisk hardDisk) { - IMedium medium = vBox.createHardDisk(hardDisk.getDiskFormat(), hardDisk.getDiskPath()); - createBaseStorage(medium); - return medium; - } - - private boolean notFoundException(VBoxException e) { - return e.getMessage().contains("VirtualBox error: Could not find file for the medium "); - } - - private void createBaseStorage(IMedium hardDisk) { - try { - long size = 4L * 1024L * 1024L * 1024L - 4L; - IProgress storageCreation = hardDisk.createBaseStorage(size, - (long) org.virtualbox_4_2.jaxws.MediumVariant.STANDARD.ordinal()); - storageCreation.waitForCompletion(-1); - } catch (VBoxException e) { - if (fileNotFoundException(e)) { - // File for medium could not be found. Something wrong with - // creation. - hardDisk.deleteStorage(); - } - if (!storageAlreadyExists(e)) { - // Hard disk file was created but the storage had been created - // before that. - throw e; - } - } - } - - private boolean fileNotFoundException(VBoxException e) { - return e.getMessage().contains("VERR_FILE_NOT_FOUND"); - } - - private boolean storageAlreadyExists(VBoxException e) { - return e.getMessage().contains("VirtualBox error: Storage for the medium ") - && e.getMessage().contains("is already created"); - } - -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/75178c77/virtualbox/src/main/java/org/jclouds/virtualbox/functions/DetachDistroMediumFromMachine.java ---------------------------------------------------------------------- diff --git a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/DetachDistroMediumFromMachine.java b/virtualbox/src/main/java/org/jclouds/virtualbox/functions/DetachDistroMediumFromMachine.java deleted file mode 100644 index dbe7959..0000000 --- a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/DetachDistroMediumFromMachine.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.virtualbox.functions; - -import org.virtualbox_4_2.IMachine; -import org.virtualbox_4_2.VBoxException; - -import com.google.common.base.Function; - -public class DetachDistroMediumFromMachine implements Function<IMachine, Void> { - - private final String controller; - private int port; - private int deviceSlot; - - public DetachDistroMediumFromMachine(String controller, int port, int deviceSlot) { - this.controller = controller; - this.port = port; - this.deviceSlot = deviceSlot; - } - - //TODO: should this be a function on HardDisk? - @Override - public Void apply(IMachine machine) { - try { - machine.detachDevice(controller, port, deviceSlot); - machine.saveSettings(); - } catch (VBoxException e) { - if (!alreadyDetached(e)) - throw e; - } - return null; - } - - private boolean alreadyDetached(VBoxException e) { - return e.getMessage().contains("is already detached from port"); - } - -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/75178c77/virtualbox/src/main/java/org/jclouds/virtualbox/functions/HardcodedHostToHostNodeMetadata.java ---------------------------------------------------------------------- diff --git a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/HardcodedHostToHostNodeMetadata.java b/virtualbox/src/main/java/org/jclouds/virtualbox/functions/HardcodedHostToHostNodeMetadata.java deleted file mode 100644 index fdf1371..0000000 --- a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/HardcodedHostToHostNodeMetadata.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.virtualbox.functions; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.net.URI; - -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.domain.Credentials; -import org.jclouds.domain.LoginCredentials; -import org.jclouds.location.Provider; - -import com.google.common.base.Function; -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableList; -import com.google.inject.Inject; -import com.google.inject.Singleton; - -@Singleton -public class HardcodedHostToHostNodeMetadata implements Function<NodeMetadata, NodeMetadata> { - - private final Supplier<URI> providerSupplier; - private final Supplier<Credentials> creds; - - @Inject - public HardcodedHostToHostNodeMetadata(@Provider Supplier<URI> providerSupplier, - @Provider Supplier<Credentials> creds) { - this.providerSupplier = checkNotNull(providerSupplier, "endpoint to virtualbox websrvd is needed"); - this.creds = creds; - } - - @Override - public NodeMetadata apply(NodeMetadata host) { - Credentials currentCreds = checkNotNull(creds.get(), "credential supplier returned null"); - String username = currentCreds.identity; - String password = currentCreds.credential.equals("CHANGE_ME") ? "" : currentCreds.credential; - - LoginCredentials.Builder credentialsBuilder = LoginCredentials.builder(host.getCredentials()).user(username); - if (!password.isEmpty()) - credentialsBuilder.password(password); - - return NodeMetadataBuilder - .fromNodeMetadata(host) - .credentials(credentialsBuilder.build()) - .publicAddresses(ImmutableList.of(providerSupplier.get().getHost())) - .build(); - } - -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/75178c77/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToHardware.java ---------------------------------------------------------------------- diff --git a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToHardware.java b/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToHardware.java deleted file mode 100644 index e4e8a8e..0000000 --- a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToHardware.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.virtualbox.functions; - -import javax.inject.Inject; - -import org.jclouds.compute.domain.Hardware; -import org.jclouds.compute.domain.HardwareBuilder; -import org.jclouds.compute.predicates.ImagePredicates; -import org.jclouds.javax.annotation.Nullable; -import org.jclouds.virtualbox.config.VirtualBoxConstants; -import org.virtualbox_4_2.IGuestOSType; -import org.virtualbox_4_2.IMachine; -import org.virtualbox_4_2.VirtualBoxManager; - -import com.google.common.base.Function; -import com.google.common.base.Supplier; - -public class IMachineToHardware implements Function<IMachine, Hardware> { - - private Supplier<VirtualBoxManager> virtualBoxManager; - - @Inject - public IMachineToHardware(Supplier<VirtualBoxManager> virtualBoxManager) { - this.virtualBoxManager = virtualBoxManager; - } - - @Override - public Hardware apply(@Nullable IMachine vm) { - String osTypeId = vm.getOSTypeId(); - String vmNameWithoutPrefix = vm.getName().replace(VirtualBoxConstants.VIRTUALBOX_IMAGE_PREFIX, ""); - - IGuestOSType guestOSType = virtualBoxManager.get().getVBox().getGuestOSType(osTypeId); - Boolean is64Bit = guestOSType.getIs64Bit(); - HardwareBuilder hardwareBuilder = new HardwareBuilder(); - hardwareBuilder.ids(vmNameWithoutPrefix); - hardwareBuilder.is64Bit(is64Bit); - hardwareBuilder.supportsImage(ImagePredicates.idEquals(vmNameWithoutPrefix)); - hardwareBuilder.hypervisor("VirtualBox"); - return hardwareBuilder.build(); - } -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/75178c77/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToImage.java ---------------------------------------------------------------------- diff --git a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToImage.java b/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToImage.java deleted file mode 100644 index f1b672b..0000000 --- a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToImage.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.virtualbox.functions; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.compute.util.ComputeServiceUtils.parseOsFamilyOrUnrecognized; -import static org.jclouds.compute.util.ComputeServiceUtils.parseVersionOrReturnEmptyString; - -import java.util.Map; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.compute.domain.Image; -import org.jclouds.compute.domain.Image.Status; -import org.jclouds.compute.domain.ImageBuilder; -import org.jclouds.compute.domain.OperatingSystem; -import org.jclouds.compute.domain.OsFamily; -import org.jclouds.javax.annotation.Nullable; -import org.jclouds.virtualbox.config.VirtualBoxConstants; -import org.virtualbox_4_2.IGuestOSType; -import org.virtualbox_4_2.IMachine; -import org.virtualbox_4_2.MachineState; -import org.virtualbox_4_2.VirtualBoxManager; - -import com.google.common.base.Function; -import com.google.common.base.Supplier; - -@Singleton -public class IMachineToImage implements Function<IMachine, Image> { - - private final Map<MachineState, Status> toPortableImageStatus; - private final Supplier<VirtualBoxManager> virtualboxManager; - private final Map<OsFamily, Map<String, String>> osVersionMap; - - @Inject - public IMachineToImage(Map<MachineState, Image.Status> toPortableImageStatus, Supplier<VirtualBoxManager> virtualboxManager, Map<OsFamily, Map<String, String>> osVersionMap) { - this.toPortableImageStatus = checkNotNull(toPortableImageStatus, "toPortableImageStatus"); - this.virtualboxManager = checkNotNull(virtualboxManager, "virtualboxManager"); - this.osVersionMap = checkNotNull(osVersionMap, "osVersionMap"); - } - - @Override - public Image apply(@Nullable IMachine from) { - if (from == null) - return null; - - IGuestOSType guestOSType = virtualboxManager.get().getVBox().getGuestOSType(from.getOSTypeId()); - OsFamily family = parseOsFamilyOrUnrecognized(guestOSType.getDescription()); - String version = parseVersionOrReturnEmptyString(family, guestOSType.getDescription(), osVersionMap); - OperatingSystem os = OperatingSystem.builder().description(guestOSType.getDescription()).family(family) - .version(version).is64Bit(guestOSType.getIs64Bit()).build(); - - return new ImageBuilder() - .id(from.getName().substring(VirtualBoxConstants.VIRTUALBOX_IMAGE_PREFIX.length(), - from.getName().length())).name(from.getName()).description(from.getDescription()) - .operatingSystem(os).status(toPortableImageStatus.get(from.getState())).build(); - } - -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/75178c77/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToIpAddress.java ---------------------------------------------------------------------- diff --git a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToIpAddress.java b/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToIpAddress.java deleted file mode 100644 index 13b2216..0000000 --- a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToIpAddress.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.virtualbox.functions; - -import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot; - -import org.jclouds.compute.ComputeService; -import org.jclouds.compute.domain.ExecResponse; -import org.jclouds.compute.options.RunScriptOptions; -import org.jclouds.virtualbox.config.VirtualBoxConstants; -import org.virtualbox_4_2.IGuestOSType; -import org.virtualbox_4_2.IMachine; -import org.virtualbox_4_2.VirtualBoxManager; - -import com.google.common.base.Function; - -/** - * Get an IP address from an IMachine using arp of the host machine. - */ -public class IMachineToIpAddress implements Function<IMachine, String> { - - private VirtualBoxManager manager; - private ComputeService computeService; - - public IMachineToIpAddress(VirtualBoxManager manager, ComputeService computeService) { - this.manager = manager; - this.computeService = computeService; - } - - @Override - public String apply(IMachine machine) { - - String macAddress = machine.getNetworkAdapter(0l).getMACAddress(); - int offset = 0; - int step = 2; - for (int j = 1; j <= 5; j++) { - macAddress = new StringBuilder(macAddress).insert(j * step + offset, ":").toString().toLowerCase(); - offset++; - } - - String simplifiedMacAddressOfClonedVM = macAddress; - - final String hostId = System.getProperty(VirtualBoxConstants.VIRTUALBOX_HOST_ID); - IMachine hostMachine = manager.getVBox().findMachine(hostId); - if (isOSX(hostMachine)) { - if (simplifiedMacAddressOfClonedVM.contains("00")) - simplifiedMacAddressOfClonedVM = new StringBuilder(simplifiedMacAddressOfClonedVM).delete( - simplifiedMacAddressOfClonedVM.indexOf("00"), simplifiedMacAddressOfClonedVM.indexOf("00") + 1) - .toString(); - - if (simplifiedMacAddressOfClonedVM.contains("0")) - if (simplifiedMacAddressOfClonedVM.indexOf("0") + 1 != ':' - && simplifiedMacAddressOfClonedVM.indexOf("0") - 1 != ':') - simplifiedMacAddressOfClonedVM = new StringBuilder(simplifiedMacAddressOfClonedVM).delete( - simplifiedMacAddressOfClonedVM.indexOf("0"), simplifiedMacAddressOfClonedVM.indexOf("0") + 1) - .toString(); - } - - // TODO: This is both shell-dependent and hard-coded. Needs to be fixed. - ExecResponse execResponse = runScriptOnNode(hostId, "for i in {1..254} ; do ping -c 1 -t 1 192.168.2.$i & done", - runAsRoot(false).wrapInInitScript(false)); - System.out.println(execResponse); - - String arpLine = runScriptOnNode(hostId, "arp -an | grep " + simplifiedMacAddressOfClonedVM, - runAsRoot(false).wrapInInitScript(false)).getOutput(); - String ipAddress = arpLine.substring(arpLine.indexOf("(") + 1, arpLine.indexOf(")")); - System.out.println("IP address " + ipAddress); - return ipAddress; - } - - private ExecResponse runScriptOnNode(String nodeId, String command, RunScriptOptions options) { - return computeService.runScriptOnNode(nodeId, command, options); - } - - protected boolean isOSX(IMachine machine) { - String osTypeId = machine.getOSTypeId(); - IGuestOSType guestOSType = manager.getVBox().getGuestOSType(osTypeId); - return guestOSType.getFamilyDescription().equals("Other"); - } - -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/75178c77/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java ---------------------------------------------------------------------- diff --git a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java b/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java deleted file mode 100644 index 517494a..0000000 --- a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.virtualbox.functions; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.compute.util.ComputeServiceUtils.parseOsFamilyOrUnrecognized; -import static org.jclouds.compute.util.ComputeServiceUtils.parseVersionOrReturnEmptyString; -import static org.jclouds.virtualbox.config.VirtualBoxConstants.GUEST_OS_PASSWORD; -import static org.jclouds.virtualbox.config.VirtualBoxConstants.GUEST_OS_USER; -import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_NODE_NAME_SEPARATOR; -import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_NODE_PREFIX; - -import java.util.List; -import java.util.Map; - -import javax.annotation.Resource; -import javax.inject.Named; - -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.OperatingSystem; -import org.jclouds.compute.domain.OsFamily; -import org.jclouds.compute.domain.NodeMetadata.Status; -import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.domain.LocationBuilder; -import org.jclouds.domain.LocationScope; -import org.jclouds.domain.LoginCredentials; -import org.jclouds.javax.annotation.Nullable; -import org.jclouds.logging.Logger; -import org.jclouds.virtualbox.util.NetworkUtils; -import org.virtualbox_4_2.IGuestOSType; -import org.virtualbox_4_2.IMachine; -import org.virtualbox_4_2.INetworkAdapter; -import org.virtualbox_4_2.MachineState; -import org.virtualbox_4_2.NetworkAttachmentType; -import org.virtualbox_4_2.VirtualBoxManager; - -import com.google.common.base.Function; -import com.google.common.base.Splitter; -import com.google.common.base.Supplier; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.inject.Inject; -import com.google.inject.Singleton; - -@Singleton -public class IMachineToNodeMetadata implements Function<IMachine, NodeMetadata> { - - @Resource - @Named(ComputeServiceConstants.COMPUTE_LOGGER) - protected Logger logger = Logger.NULL; - - private final Supplier<VirtualBoxManager> virtualboxManager; - private final Map<MachineState, Status> toPortableNodeStatus; - private final NetworkUtils networkUtils; - private final Map<OsFamily, Map<String, String>> osVersionMap; - - @Inject - public IMachineToNodeMetadata(Supplier<VirtualBoxManager> virtualboxManager, Map<MachineState, NodeMetadata.Status> toPortableNodeStatus, - NetworkUtils networkUtils, Map<OsFamily, Map<String, String>> osVersionMap) { - this.virtualboxManager = checkNotNull(virtualboxManager, "virtualboxManager"); - this.toPortableNodeStatus = checkNotNull(toPortableNodeStatus, "toPortableNodeStatus"); - this.networkUtils = checkNotNull(networkUtils, "networkUtils"); - this.osVersionMap = checkNotNull(osVersionMap, "osVersionMap"); - } - - @Override - public NodeMetadata apply(@Nullable IMachine vm) { - - String group = ""; - String name = ""; - String[] encodedInVmName = vm.getName().split(VIRTUALBOX_NODE_NAME_SEPARATOR); - if (vm.getName().startsWith(VIRTUALBOX_NODE_PREFIX)){ - group = encodedInVmName[2]; - name = encodedInVmName[3]; - } else { - name = encodedInVmName[1]; - } - - NodeMetadataBuilder nodeMetadataBuilder = new NodeMetadataBuilder(); - nodeMetadataBuilder.name(name).ids(vm.getName()).group(group); - // TODO Set up location properly - LocationBuilder locationBuilder = new LocationBuilder(); - locationBuilder.description(""); - locationBuilder.id(""); - locationBuilder.scope(LocationScope.HOST); - nodeMetadataBuilder.location(locationBuilder.build()); - nodeMetadataBuilder.hostname(vm.getName()); - - MachineState vmState = vm.getState(); - NodeMetadata.Status nodeState = toPortableNodeStatus.get(vmState); - if (nodeState == null) - nodeState = Status.UNRECOGNIZED; - nodeMetadataBuilder.status(nodeState); - nodeMetadataBuilder = getIpAddresses(vm, nodeMetadataBuilder); - - IGuestOSType guestOSType = virtualboxManager.get().getVBox().getGuestOSType(vm.getOSTypeId()); - OsFamily family = parseOsFamilyOrUnrecognized(guestOSType.getDescription()); - String version = parseVersionOrReturnEmptyString(family, guestOSType.getDescription(), osVersionMap); - OperatingSystem os = OperatingSystem.builder().description(guestOSType.getDescription()).family(family) - .version(version).is64Bit(guestOSType.getIs64Bit()).build(); - nodeMetadataBuilder.operatingSystem(os); - - String guestOsUser = vm.getExtraData(GUEST_OS_USER); - String guestOsPassword = vm.getExtraData(GUEST_OS_PASSWORD); - nodeMetadataBuilder.credentials(LoginCredentials.builder() - .user(guestOsUser) - .password(guestOsPassword) - .authenticateSudo(true).build()); - return nodeMetadataBuilder.build(); - } - - private NodeMetadataBuilder getIpAddresses(IMachine vm, NodeMetadataBuilder nodeMetadataBuilder) { - List<String> publicIpAddresses = Lists.newArrayList(); - List<String> privateIpAddresses = Lists.newArrayList(); - for (long slot = 0; slot < 4; slot++) { - INetworkAdapter adapter = vm.getNetworkAdapter(slot); - if (adapter != null) { - if (adapter.getAttachmentType() == NetworkAttachmentType.NAT) { - String hostIP = adapter.getNATEngine().getHostIP(); - if (!hostIP.isEmpty()) - publicIpAddresses.add(hostIP); - for (String nameProtocolnumberAddressInboudportGuestTargetport : adapter.getNATEngine().getRedirects()) { - Iterable<String> stuff = Splitter.on(',').split(nameProtocolnumberAddressInboudportGuestTargetport); - String protocolNumber = Iterables.get(stuff, 1); - String hostAddress = Iterables.get(stuff, 2); - String inboundPort = Iterables.get(stuff, 3); - String targetPort = Iterables.get(stuff, 5); - if ("1".equals(protocolNumber) && "22".equals(targetPort)) { - int inPort = Integer.parseInt(inboundPort); - publicIpAddresses.add(hostAddress); - nodeMetadataBuilder.loginPort(inPort); - } - } - } else if (adapter.getAttachmentType() == NetworkAttachmentType.Bridged) { - String clientIpAddress = networkUtils.getIpAddressFromNicSlot(vm.getName(), adapter.getSlot()); - privateIpAddresses.add(clientIpAddress); - - } else if (adapter.getAttachmentType() == NetworkAttachmentType.HostOnly) { - String clientIpAddress = networkUtils.getValidHostOnlyIpFromVm(vm.getName()); - publicIpAddresses.add(clientIpAddress); - } - } - } - nodeMetadataBuilder.publicAddresses(publicIpAddresses); - nodeMetadataBuilder.privateAddresses(publicIpAddresses); - return nodeMetadataBuilder; - } - -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/75178c77/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToSshClient.java ---------------------------------------------------------------------- diff --git a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToSshClient.java b/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToSshClient.java deleted file mode 100644 index c515f5f..0000000 --- a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToSshClient.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.virtualbox.functions; - -import static org.jclouds.virtualbox.config.VirtualBoxConstants.GUEST_OS_PASSWORD; -import static org.jclouds.virtualbox.config.VirtualBoxConstants.GUEST_OS_USER; - -import javax.annotation.Resource; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.domain.LoginCredentials; -import org.jclouds.logging.Logger; -import org.jclouds.ssh.SshClient; -import org.jclouds.virtualbox.util.NetworkUtils; -import org.virtualbox_4_2.IMachine; -import org.virtualbox_4_2.INetworkAdapter; -import org.virtualbox_4_2.NetworkAttachmentType; - -import com.google.common.base.Function; -import com.google.common.base.Splitter; -import com.google.common.base.Strings; -import com.google.common.collect.Iterables; -import com.google.common.net.HostAndPort; -import com.google.inject.Inject; - -@Singleton -public class IMachineToSshClient implements Function<IMachine, SshClient> { - - @Resource - @Named(ComputeServiceConstants.COMPUTE_LOGGER) - protected Logger logger = Logger.NULL; - - private final SshClient.Factory sshClientFactory; - private final NetworkUtils networkUtils; - - @Inject - public IMachineToSshClient(SshClient.Factory sshClientFactory, NetworkUtils networkUtils) { - this.sshClientFactory = sshClientFactory; - this.networkUtils = networkUtils; - } - - @Override - public SshClient apply(final IMachine vm) { - String sshPort = "22"; - String guestIdentity = vm.getExtraData(GUEST_OS_USER); - String guestCredential = vm.getExtraData(GUEST_OS_PASSWORD); - LoginCredentials loginCredentials = LoginCredentials.builder().user(guestIdentity).password(guestCredential) - .authenticateSudo(true).build(); - - String clientIpAddress = null; - - long nicSlot = 0; - while (nicSlot < 4 && Strings.isNullOrEmpty(clientIpAddress)) { - INetworkAdapter networkAdapter = vm.getNetworkAdapter(nicSlot); - - if (networkAdapter.getAttachmentType().equals(NetworkAttachmentType.NAT)) { - for (String nameProtocolnumberAddressInboudportGuestTargetport : networkAdapter.getNATEngine() - .getRedirects()) { - Iterable<String> stuff = Splitter.on(',').split(nameProtocolnumberAddressInboudportGuestTargetport); - String protocolNumber = Iterables.get(stuff, 1); - String hostAddress = Iterables.get(stuff, 2); - String inboundPort = Iterables.get(stuff, 3); - String targetPort = Iterables.get(stuff, 5); - if ("1".equals(protocolNumber) && "22".equals(targetPort)) { - clientIpAddress = hostAddress; - sshPort = inboundPort; - } - } - } else if (networkAdapter.getAttachmentType().equals(NetworkAttachmentType.Bridged)) { - clientIpAddress = networkUtils.getIpAddressFromNicSlot(vm.getName(), networkAdapter.getSlot()); - } else if (networkAdapter.getAttachmentType().equals(NetworkAttachmentType.HostOnly)) { - clientIpAddress = networkUtils.getValidHostOnlyIpFromVm(vm.getName()); - } - nicSlot++; - } - return sshClientFactory.create(HostAndPort.fromParts(clientIpAddress, Integer.parseInt(sshPort)), - loginCredentials); - } - -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/75178c77/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToVmSpec.java ---------------------------------------------------------------------- diff --git a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToVmSpec.java b/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToVmSpec.java deleted file mode 100644 index 7601f74..0000000 --- a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToVmSpec.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.virtualbox.functions; - -import java.util.List; - -import javax.annotation.Resource; -import javax.inject.Named; - -import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.logging.Logger; -import org.jclouds.virtualbox.domain.HardDisk; -import org.jclouds.virtualbox.domain.StorageController; -import org.jclouds.virtualbox.domain.StorageController.Builder; -import org.jclouds.virtualbox.domain.VmSpec; -import org.virtualbox_4_2.CleanupMode; -import org.virtualbox_4_2.DeviceType; -import org.virtualbox_4_2.IMachine; -import org.virtualbox_4_2.IMedium; -import org.virtualbox_4_2.IMediumAttachment; -import org.virtualbox_4_2.IStorageController; - -import com.google.common.base.Function; -import com.google.common.collect.Lists; - -/** - * Get a VmSpec from an IMachine - */ -public class IMachineToVmSpec implements Function<IMachine, VmSpec> { - - @Resource - @Named(ComputeServiceConstants.COMPUTE_LOGGER) - protected Logger logger = Logger.NULL; - - @Override - public VmSpec apply(IMachine machine) { - List<StorageController> controllers = buildControllers(machine); - - // TODO some parameters are predefined cause the IMachine doesn't have the - // concept i.e.: cleanUpMode - org.jclouds.virtualbox.domain.VmSpec.Builder vmSpecBuilder = VmSpec.builder(); - - vmSpecBuilder.id(machine.getId()).name(machine.getName()).memoryMB(machine.getMemorySize().intValue()) - .osTypeId(machine.getOSTypeId()).forceOverwrite(true).cleanUpMode(CleanupMode.Full); - - for (StorageController storageController : controllers) { - vmSpecBuilder.controller(storageController); - } - - return vmSpecBuilder.build(); - } - - private List<StorageController> buildControllers(IMachine machine) { - - List<StorageController> controllers = Lists.newArrayList(); - for (IStorageController iStorageController : machine.getStorageControllers()) { - - Builder storageControllerBuilder = StorageController.builder(); - for (IMediumAttachment iMediumAttachment : machine.getMediumAttachmentsOfController(iStorageController - .getName())) { - IMedium iMedium = iMediumAttachment.getMedium(); - if (iMedium != null) { - if (iMedium.getDeviceType().equals(DeviceType.HardDisk)) { - storageControllerBuilder.attachHardDisk(HardDisk.builder().diskpath(iMedium.getLocation()) - .autoDelete(true).controllerPort(iMediumAttachment.getPort()) - .deviceSlot(iMediumAttachment.getDevice().intValue()).build()); - } else if (iMedium.getDeviceType().equals(DeviceType.DVD)) { - storageControllerBuilder.attachISO(iMediumAttachment.getPort(), iMediumAttachment.getDevice().intValue(), - iMedium.getLocation()); - } - } - } - controllers.add(storageControllerBuilder.name(iStorageController.getName()).bus(iStorageController.getBus()) - .build()); - } - return controllers; - } -} http://git-wip-us.apache.org/repos/asf/jclouds-labs/blob/75178c77/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IpAddressesLoadingCache.java ---------------------------------------------------------------------- diff --git a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IpAddressesLoadingCache.java b/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IpAddressesLoadingCache.java deleted file mode 100644 index b4097a4..0000000 --- a/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IpAddressesLoadingCache.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.jclouds.virtualbox.functions; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.logging.Logger; -import org.jclouds.virtualbox.util.MachineNameOrIdAndNicSlot; -import org.virtualbox_4_2.VirtualBoxManager; - -import com.google.common.base.Strings; -import com.google.common.base.Supplier; -import com.google.common.cache.AbstractLoadingCache; -import com.google.common.collect.Maps; - -/** - * A {@link LoadingCache} for ip addresses. If the requested ip address has been - * previously extracted this returns it, if not it calls vbox api. - */ -@Singleton -public class IpAddressesLoadingCache extends - AbstractLoadingCache<MachineNameOrIdAndNicSlot, String> { - - @Resource - @Named(ComputeServiceConstants.COMPUTE_LOGGER) - protected Logger logger = Logger.NULL; - - private final Map<MachineNameOrIdAndNicSlot, String> masters = Maps.newHashMap(); - private final Supplier<VirtualBoxManager> manager; - - @Inject - public IpAddressesLoadingCache(Supplier<VirtualBoxManager> manager) { - this.manager = checkNotNull(manager, "vboxmanager"); - } - - @Override - public synchronized String get(MachineNameOrIdAndNicSlot machineNameOrIdAndNicPort) throws ExecutionException { - if (masters.containsKey(machineNameOrIdAndNicPort)) { - return masters.get(machineNameOrIdAndNicPort); - } - String query = String.format("/VirtualBox/GuestInfo/Net/%s/V4/IP", machineNameOrIdAndNicPort.getSlotText()); - String ipAddress = Strings.nullToEmpty(manager.get().getVBox() - .findMachine(machineNameOrIdAndNicPort.getMachineNameOrId()).getGuestPropertyValue(query)); - if (!ipAddress.isEmpty()) { - logger.debug("<< vm(%s) has IP address(%s) at slot(%s)", machineNameOrIdAndNicPort.getMachineNameOrId(), - ipAddress, machineNameOrIdAndNicPort.getSlotText()); - } - masters.put(machineNameOrIdAndNicPort, ipAddress); - return ipAddress; - } - - @Override - public String getIfPresent(Object key) { - return masters.get((MachineNameOrIdAndNicSlot) key); - } - - @Override - public void invalidate(Object key) { - masters.remove(key); - } - -}
