Search in sources :

Example 1 with AzureDockerException

use of com.microsoft.azure.docker.model.AzureDockerException in project azure-tools-for-java by Microsoft.

the class AzureDockerSSHOps method download.

public static void download(Session session, String fileName, String fromPath, String toPath) {
    try {
        ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
        channel.connect();
        File toFile = new File(toPath, fileName);
        OutputStream outputStream = new FileOutputStream(toFile);
        BufferedOutputStream buff = new BufferedOutputStream(outputStream);
        channel.cd(fromPath);
        channel.get(fileName, buff);
        channel.disconnect();
    } catch (Exception e) {
        throw new AzureDockerException(e.getMessage(), e);
    }
}
Also used : AzureDockerException(com.microsoft.azure.docker.model.AzureDockerException) AzureDockerException(com.microsoft.azure.docker.model.AzureDockerException)

Example 2 with AzureDockerException

use of com.microsoft.azure.docker.model.AzureDockerException in project azure-tools-for-java by Microsoft.

the class AzureDockerSSHOps method createLoginInstance.

public static Session createLoginInstance(DockerHost dockerHost) {
    if (dockerHost != null && dockerHost.certVault != null && dockerHost.certVault.vmUsername != null && !dockerHost.certVault.vmUsername.isEmpty() && ((dockerHost.certVault.vmPwd != null && !dockerHost.certVault.vmPwd.isEmpty()) || (dockerHost.certVault.sshPubKey != null && !dockerHost.certVault.sshPubKey.isEmpty()))) {
        try {
            JSch jsch = new JSch();
            jsch.setKnownHosts(System.getProperty("user.home") + "/.ssh/known_hosts");
            if (dockerHost.certVault.sshKey != null && !dockerHost.certVault.sshKey.isEmpty()) {
                jsch.addIdentity(dockerHost.certVault.hostName, dockerHost.certVault.sshKey.getBytes(), dockerHost.certVault.sshPubKey.getBytes(), (byte[]) null);
            }
            Session session = jsch.getSession(dockerHost.certVault.vmUsername, dockerHost.hostVM.dnsName);
            if (dockerHost.certVault.vmPwd != null && !dockerHost.certVault.vmPwd.isEmpty()) {
                session.setPassword(dockerHost.certVault.vmPwd);
            }
            session.setConfig("StrictHostKeyChecking", "no");
            session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
            session.connect();
            return session;
        } catch (Exception e) {
            throw new AzureDockerException("Create Log In Instance: " + e.getMessage(), e);
        }
    } else {
        throw new AzureDockerException("Unexpected param values; dockerHost cannot be null");
    }
}
Also used : AzureDockerException(com.microsoft.azure.docker.model.AzureDockerException) AzureDockerException(com.microsoft.azure.docker.model.AzureDockerException)

Example 3 with AzureDockerException

use of com.microsoft.azure.docker.model.AzureDockerException in project azure-tools-for-java by Microsoft.

the class AzureDockerSSHOps method executeCommand.

public static String executeCommand(String command, Session session, Boolean getExitStatus, Boolean withErr) {
    String result = "";
    String resultErr = "";
    try {
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        InputStream commandOutput = channel.getInputStream();
        InputStream commandErr = ((ChannelExec) channel).getErrStream();
        channel.connect();
        byte[] tmp = new byte[4096];
        while (true) {
            while (commandOutput.available() > 0) {
                int i = commandOutput.read(tmp, 0, 4096);
                if (i < 0)
                    break;
                result += new String(tmp, 0, i);
            }
            while (commandErr.available() > 0) {
                int i = commandErr.read(tmp, 0, 4096);
                if (i < 0)
                    break;
                resultErr += new String(tmp, 0, i);
            }
            if (channel.isClosed()) {
                if (commandOutput.available() > 0)
                    continue;
                if (getExitStatus) {
                    result += "exit-status: " + channel.getExitStatus();
                    if (withErr) {
                        result += "\n With error:\n" + resultErr;
                    }
                }
                break;
            }
            try {
                Thread.sleep(100);
            } catch (Exception ee) {
            }
        }
        channel.disconnect();
        return result;
    } catch (Exception e) {
        throw new AzureDockerException(e.getMessage(), e);
    }
}
Also used : AzureDockerException(com.microsoft.azure.docker.model.AzureDockerException) AzureDockerException(com.microsoft.azure.docker.model.AzureDockerException)

Example 4 with AzureDockerException

use of com.microsoft.azure.docker.model.AzureDockerException in project azure-tools-for-java by Microsoft.

the class AzureDockerCertVaultOps method createOrUpdateVault.

public static void createOrUpdateVault(Azure azureClient, AzureDockerCertVault certVault, KeyVaultClient keyVaultClient) throws AzureDockerException {
    if (azureClient == null || keyVaultClient == null || certVault == null || certVault.name == null || certVault.hostName == null || certVault.resourceGroupName == null || certVault.region == null || (certVault.servicePrincipalId == null && certVault.userId == null)) {
        throw new AzureDockerException("Unexpected argument values; azureClient, vault name, hostName, resourceGroupName, region and userName/servicePrincipalId cannot be null");
    }
    try {
        Vault vault = null;
        try {
            if (certVault.id != null) {
                vault = azureClient.vaults().getById(certVault.id);
            } else {
                for (ResourceGroup group : azureClient.resourceGroups().list()) {
                    for (Vault vaultItem : azureClient.vaults().listByResourceGroup(group.name())) {
                        if (vaultItem.name().equals(certVault.name)) {
                            vault = vaultItem;
                            break;
                        }
                    }
                    if (vault != null)
                        break;
                }
            }
        } catch (CloudException e) {
            if (e.body().code().equals("ResourceNotFound") || e.body().code().equals("ResourceGroupNotFound")) {
                // Vault does no exist
                vault = null;
            } else {
                throw e;
            }
        }
        if (vault == null) {
            // Vault does not exist so this is the create op
            Vault.DefinitionStages.WithGroup withGroup = azureClient.vaults().define(certVault.name).withRegion(certVault.region);
            Vault.DefinitionStages.WithAccessPolicy withAccessPolicy;
            if (certVault.resourceGroupName.contains("@")) {
                // use existing resource group as selected by the user
                withAccessPolicy = withGroup.withExistingResourceGroup(certVault.resourceGroupName.split("@")[0]);
                certVault.resourceGroupName = certVault.resourceGroupName.split("@")[0];
            } else {
                withAccessPolicy = withGroup.withNewResourceGroup(certVault.resourceGroupName);
            }
            Vault.DefinitionStages.WithCreate withCreate = certVault.servicePrincipalId != null ? withAccessPolicy.defineAccessPolicy().forServicePrincipal(certVault.servicePrincipalId).allowSecretAllPermissions().attach() : withAccessPolicy.defineAccessPolicy().forUser(certVault.userId).allowSecretAllPermissions().attach();
            withCreate.withTag("dockerhost", "true").create();
        } else {
            // If original owner is an AD user, we might fail to set vault permissions
            try {
                setVaultPermissionsAll(azureClient, certVault);
            } catch (Exception e) {
                DefaultLoader.getUIHelper().logError(String.format("WARN: Can't set permissions to %s: %s\n", vault.vaultUri(), e.getMessage()), e);
            }
        }
        vault = azureClient.vaults().getByResourceGroup(certVault.resourceGroupName, certVault.name);
        String vaultUri = vault.vaultUri();
        // add a retry policy to make sure it got created and it is readable
        for (int sleepMs = 5000; sleepMs <= 2000000; sleepMs += 5000) {
            try {
                keyVaultClient.listSecrets(vaultUri);
                break;
            } catch (Exception e) {
                try {
                    if (DEBUG)
                        System.out.format("WARN: can't find %s (sleepMs: %d)\n", vaultUri, sleepMs);
                    if (DEBUG)
                        System.out.println(e.getMessage());
                    //            DefaultLoader.getUIHelper().logError(String.format("WARN: Can't connect to %s: %s (sleepMs: %d)\n", vaultUri, e.getMessage(), sleepMs), e);
                    try {
                        // Windows only - flush local DNS to reflect the new Key Vault URI
                        if (System.getProperty("os.name").toLowerCase().contains("win")) {
                            Process p = Runtime.getRuntime().exec("cmd /c ipconfig /flushdns");
                        }
                    } catch (Exception ignored) {
                    }
                    Thread.sleep(5000);
                } catch (Exception ignored) {
                }
            }
        }
        Map<String, String> secretsMap = getSecretsMap(certVault);
        // TODO: remove this after enabling parallel secrets write from above
        for (Map.Entry<String, String> entry : secretsMap.entrySet()) {
            try {
                if (entry.getValue() != null && !entry.getValue().isEmpty()) {
                    keyVaultClient.setSecret(new SetSecretRequest.Builder(vaultUri, entry.getKey(), entry.getValue()).build());
                }
            } catch (Exception e) {
                DefaultLoader.getUIHelper().logError(String.format("WARN: Unexpected error writing to %s: %s\n", vaultUri, e.getMessage()), e);
                System.out.format("ERROR: can't write %s secret %s: %s\n", vaultUri, entry.getKey(), entry.getValue());
                System.out.println(e.getMessage());
            }
        }
        if (keyVaultClient.listSecrets(vaultUri).size() > 0 && certVault.hostName != null && !certVault.hostName.isEmpty()) {
            keyVaultClient.setSecret(new SetSecretRequest.Builder(vaultUri, SECRETENTRY_DOCKERHOSTNAMES, certVault.hostName).build());
        } else {
            // something unexpected went wrong... delete the vault
            if (DEBUG)
                System.out.println("ERROR: something went wrong");
            throw new RuntimeException("Key vault has no secrets");
        }
    } catch (Exception e) {
        DefaultLoader.getUIHelper().logError(String.format("WARN: Unexpected error creating Azure Key Vault %s - %s\n", certVault.name, e.getMessage()), e);
        throw new AzureDockerException(e.getMessage());
    }
}
Also used : CloudException(com.microsoft.azure.CloudException) AzureDockerException(com.microsoft.azure.docker.model.AzureDockerException) CloudException(com.microsoft.azure.CloudException) AzureDockerException(com.microsoft.azure.docker.model.AzureDockerException) Vault(com.microsoft.azure.management.keyvault.Vault) AzureDockerCertVault(com.microsoft.azure.docker.model.AzureDockerCertVault) HashMap(java.util.HashMap) Map(java.util.Map) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup)

Example 5 with AzureDockerException

use of com.microsoft.azure.docker.model.AzureDockerException in project azure-tools-for-java by Microsoft.

the class AzureDockerCertVaultOps method getTLSCertsFromLocalFile.

public static AzureDockerCertVault getTLSCertsFromLocalFile(String localPath) throws AzureDockerException {
    AzureDockerCertVault certVault = new AzureDockerCertVault();
    try {
        certVault.tlsCACert = new String(Files.readAllBytes(Paths.get(localPath, "ca.pem")));
        certVault.tlsCAKey = new String(Files.readAllBytes(Paths.get(localPath, "ca-key.pem")));
        certVault.tlsClientCert = new String(Files.readAllBytes(Paths.get(localPath, "cert.pem")));
        certVault.tlsClientKey = new String(Files.readAllBytes(Paths.get(localPath, "key.pem")));
        certVault.tlsServerCert = new String(Files.readAllBytes(Paths.get(localPath, "server.pem")));
        certVault.tlsServerKey = new String(Files.readAllBytes(Paths.get(localPath, "server-key.pem")));
    } catch (Exception e) {
        throw new AzureDockerException(e.getMessage());
    }
    return certVault;
}
Also used : AzureDockerException(com.microsoft.azure.docker.model.AzureDockerException) AzureDockerCertVault(com.microsoft.azure.docker.model.AzureDockerCertVault) AzureDockerException(com.microsoft.azure.docker.model.AzureDockerException) CloudException(com.microsoft.azure.CloudException)

Aggregations

AzureDockerException (com.microsoft.azure.docker.model.AzureDockerException)16 CloudException (com.microsoft.azure.CloudException)9 AzureDockerCertVault (com.microsoft.azure.docker.model.AzureDockerCertVault)8 Vault (com.microsoft.azure.management.keyvault.Vault)3 FileWriter (java.io.FileWriter)3 JSch (com.jcraft.jsch.JSch)2 KeyPair (com.jcraft.jsch.KeyPair)2 ResourceGroup (com.microsoft.azure.management.resources.ResourceGroup)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 AzureDockerUtils (com.microsoft.azure.docker.ops.utils.AzureDockerUtils)1 DEBUG (com.microsoft.azure.docker.ops.utils.AzureDockerUtils.DEBUG)1 KeyVaultClient (com.microsoft.azure.keyvault.KeyVaultClient)1 SecretBundle (com.microsoft.azure.keyvault.models.SecretBundle)1 SetSecretRequest (com.microsoft.azure.keyvault.requests.SetSecretRequest)1 Azure (com.microsoft.azure.management.Azure)1 SecretPermissions (com.microsoft.azure.management.keyvault.SecretPermissions)1 Pair (com.microsoft.azuretools.utils.Pair)1 ServiceCallback (com.microsoft.rest.ServiceCallback)1