Search in sources :

Example 1 with Platform

use of com.aws.greengrass.util.platforms.Platform in project aws-greengrass-nucleus by aws-greengrass.

the class DefaultDockerClient method login.

/**
 * Login to given docker registry.
 *
 * @param registry Registry to log into, with credentials encapsulated
 * @throws DockerLoginException                error in authenticating with the registry
 * @throws UserNotAuthorizedForDockerException when current user is not authorized to use docker
 * @throws DockerServiceUnavailableException   an error that can be potentially fixed through retries
 * @throws IOException                         unexpected error
 */
public void login(Registry registry) throws DockerLoginException, UserNotAuthorizedForDockerException, DockerServiceUnavailableException, IOException {
    Map<String, String> credEnvMap = new HashMap<>();
    credEnvMap.put("dockerUsername", registry.getCredentials().getUsername());
    credEnvMap.put("dockerPassword", registry.getCredentials().getPassword());
    Platform platform = Platform.getInstance();
    String loginCommand = String.format("docker login %s -u %s -p %s", registry.getEndpoint(), platform.formatEnvironmentVariableCmd("dockerUsername"), platform.formatEnvironmentVariableCmd("dockerPassword"));
    CliResponse response = runDockerCmd(loginCommand, credEnvMap);
    Optional<UserNotAuthorizedForDockerException> userAuthorizationError = checkUserAuthorizationError(response);
    if (userAuthorizationError.isPresent()) {
        throw userAuthorizationError.get();
    }
    if (response.exit.isPresent()) {
        if (response.exit.get() == 0) {
            return;
        } else {
            if (response.getOut().contains("Service Unavailable")) {
                // engine has issues or proxy config is bad etc. Not entirely reliable to determine retry behavior
                throw new DockerServiceUnavailableException(String.format("Error logging into the registry using credentials - %s", response.err));
            }
            throw new DockerLoginException(String.format("Error logging into the registry using credentials - %s", response.err));
        }
    } else {
        throw new IOException("Unexpected error while trying to perform docker login", response.failureCause);
    }
}
Also used : DockerServiceUnavailableException(com.aws.greengrass.componentmanager.plugins.docker.exceptions.DockerServiceUnavailableException) Platform(com.aws.greengrass.util.platforms.Platform) HashMap(java.util.HashMap) IOException(java.io.IOException) DockerLoginException(com.aws.greengrass.componentmanager.plugins.docker.exceptions.DockerLoginException) UserNotAuthorizedForDockerException(com.aws.greengrass.componentmanager.plugins.docker.exceptions.UserNotAuthorizedForDockerException)

Example 2 with Platform

use of com.aws.greengrass.util.platforms.Platform in project aws-greengrass-nucleus by aws-greengrass.

the class UnixExec method close.

@Override
public synchronized void close() throws IOException {
    if (isClosed.get()) {
        return;
    }
    Process p = process;
    if (p == null || !p.isAlive()) {
        return;
    }
    Platform platformInstance = Platform.getInstance();
    Set<Integer> pids = Collections.emptySet();
    try {
        pids = platformInstance.killProcessAndChildren(p, false, pids, userDecorator);
        // TODO: [P41214162] configurable timeout
        // Wait for it to die, but ignore the outcome and just forcefully kill it and all its
        // children anyway. This way, any misbehaving children or grandchildren will be killed
        // whether or not the parent behaved appropriately.
        // Wait up to 5 seconds for each child process to stop
        List<PidProcess> pidProcesses = pids.stream().map(Processes::newPidProcess).collect(Collectors.toList());
        for (PidProcess pp : pidProcesses) {
            pp.waitFor(gracefulShutdownTimeout.getSeconds(), TimeUnit.SECONDS);
        }
        if (pidProcesses.stream().anyMatch(pidProcess -> {
            try {
                return pidProcess.isAlive();
            } catch (IOException ignored) {
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return false;
        })) {
            logger.atWarn().log("Command {} did not respond to interruption within timeout. Going to kill it now", this);
        }
        platformInstance.killProcessAndChildren(p, true, pids, userDecorator);
        if (!p.waitFor(5, TimeUnit.SECONDS) && !isClosed.get()) {
            throw new IOException("Could not stop " + this);
        }
    } catch (InterruptedException e) {
        // If we're interrupted make sure to kill the process before returning
        try {
            platformInstance.killProcessAndChildren(p, true, pids, userDecorator);
        } catch (InterruptedException ignore) {
        }
    }
}
Also used : Platform(com.aws.greengrass.util.platforms.Platform) PidProcess(org.zeroturnaround.process.PidProcess) PidProcess(org.zeroturnaround.process.PidProcess) IOException(java.io.IOException)

Example 3 with Platform

use of com.aws.greengrass.util.platforms.Platform in project aws-greengrass-nucleus by aws-greengrass.

the class WindowsPlatformTest method GIVEN_file_system_permission_WHEN_convert_to_acl_THEN_succeed.

@Test
void GIVEN_file_system_permission_WHEN_convert_to_acl_THEN_succeed() throws IOException, InterruptedException {
    // No permission
    List<AclEntry> aclEntryList = WindowsPlatform.WindowsFileSystemPermissionView.aclEntries(FileSystemPermission.builder().build(), tempDir);
    assertThat(aclEntryList, hasSize(1));
    // Owner
    AclFileAttributeView view = Files.getFileAttributeView(tempDir, AclFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
    UserPrincipal owner = view.getOwner();
    aclEntryList = WindowsPlatform.WindowsFileSystemPermissionView.aclEntries(FileSystemPermission.builder().ownerRead(true).build(), tempDir);
    assertThat(aclEntryList, hasSize(2));
    assertThat(aclEntryList.get(0).principal(), equalTo(owner));
    assertThat(aclEntryList.get(0).type(), equalTo(AclEntryType.ALLOW));
    assertThat(aclEntryList.get(0).permissions(), containsInAnyOrder(WindowsPlatform.READ_PERMS.toArray()));
    aclEntryList = WindowsPlatform.WindowsFileSystemPermissionView.aclEntries(FileSystemPermission.builder().ownerWrite(true).build(), tempDir);
    assertThat(aclEntryList, hasSize(2));
    assertThat(aclEntryList.get(0).principal(), equalTo(owner));
    assertThat(aclEntryList.get(0).type(), equalTo(AclEntryType.ALLOW));
    assertThat(aclEntryList.get(0).permissions(), containsInAnyOrder(WindowsPlatform.WRITE_PERMS.toArray()));
    aclEntryList = WindowsPlatform.WindowsFileSystemPermissionView.aclEntries(FileSystemPermission.builder().ownerExecute(true).build(), tempDir);
    assertThat(aclEntryList, hasSize(2));
    assertThat(aclEntryList.get(0).principal(), equalTo(owner));
    assertThat(aclEntryList.get(0).type(), equalTo(AclEntryType.ALLOW));
    assertThat(aclEntryList.get(0).permissions(), containsInAnyOrder(WindowsPlatform.EXECUTE_PERMS.toArray()));
    // Group
    UserPrincipalLookupService userPrincipalLookupService = tempDir.getFileSystem().getUserPrincipalLookupService();
    // "Users" is a well known group and should be present on all Windows. Other well known groups that could be
    // used here includes: "Power Users", "Authenticated Users", "Administrators".
    String ownerGroup = USERS_GROUP_NAME;
    GroupPrincipal groupPrincipal = userPrincipalLookupService.lookupPrincipalByGroupName(ownerGroup);
    aclEntryList = WindowsPlatform.WindowsFileSystemPermissionView.aclEntries(FileSystemPermission.builder().ownerGroup(ownerGroup).groupRead(true).build(), tempDir);
    assertThat(aclEntryList, hasSize(2));
    assertThat(aclEntryList.get(0).principal(), equalTo(groupPrincipal));
    assertThat(aclEntryList.get(0).type(), equalTo(AclEntryType.ALLOW));
    assertThat(aclEntryList.get(0).permissions(), containsInAnyOrder(WindowsPlatform.READ_PERMS.toArray()));
    aclEntryList = WindowsPlatform.WindowsFileSystemPermissionView.aclEntries(FileSystemPermission.builder().ownerGroup(ownerGroup).groupWrite(true).build(), tempDir);
    assertThat(aclEntryList, hasSize(2));
    assertThat(aclEntryList.get(0).principal(), equalTo(groupPrincipal));
    assertThat(aclEntryList.get(0).type(), equalTo(AclEntryType.ALLOW));
    assertThat(aclEntryList.get(0).permissions(), containsInAnyOrder(WindowsPlatform.WRITE_PERMS.toArray()));
    aclEntryList = WindowsPlatform.WindowsFileSystemPermissionView.aclEntries(FileSystemPermission.builder().ownerGroup(ownerGroup).groupExecute(true).build(), tempDir);
    assertThat(aclEntryList, hasSize(2));
    assertThat(aclEntryList.get(0).principal(), equalTo(groupPrincipal));
    assertThat(aclEntryList.get(0).type(), equalTo(AclEntryType.ALLOW));
    assertThat(aclEntryList.get(0).permissions(), containsInAnyOrder(WindowsPlatform.EXECUTE_PERMS.toArray()));
    // Other
    GroupPrincipal everyone = userPrincipalLookupService.lookupPrincipalByGroupName(EVERYONE_GROUP_NAME);
    aclEntryList = WindowsPlatform.WindowsFileSystemPermissionView.aclEntries(FileSystemPermission.builder().otherRead(true).build(), tempDir);
    assertThat(aclEntryList, hasSize(2));
    assertThat(aclEntryList.get(0).principal(), equalTo(everyone));
    assertThat(aclEntryList.get(0).type(), equalTo(AclEntryType.ALLOW));
    assertThat(aclEntryList.get(0).permissions(), containsInAnyOrder(WindowsPlatform.READ_PERMS.toArray()));
    aclEntryList = WindowsPlatform.WindowsFileSystemPermissionView.aclEntries(FileSystemPermission.builder().otherWrite(true).build(), tempDir);
    assertThat(aclEntryList, hasSize(2));
    assertThat(aclEntryList.get(0).principal(), equalTo(everyone));
    assertThat(aclEntryList.get(0).type(), equalTo(AclEntryType.ALLOW));
    assertThat(aclEntryList.get(0).permissions(), containsInAnyOrder(WindowsPlatform.WRITE_PERMS.toArray()));
    aclEntryList = WindowsPlatform.WindowsFileSystemPermissionView.aclEntries(FileSystemPermission.builder().otherExecute(true).build(), tempDir);
    assertThat(aclEntryList, hasSize(2));
    assertThat(aclEntryList.get(0).principal(), equalTo(everyone));
    assertThat(aclEntryList.get(0).type(), equalTo(AclEntryType.ALLOW));
    assertThat(aclEntryList.get(0).permissions(), containsInAnyOrder(WindowsPlatform.EXECUTE_PERMS.toArray()));
    Platform platform = Platform.getInstance();
    Path under = tempDir.resolve("under");
    under.toFile().createNewFile();
    platform.setPermissions(FileSystemPermission.builder().ownerRead(true).ownerWrite(true).ownerExecute(true).otherWrite(true).build(), under, FileSystemPermission.Option.SetMode);
    AclFileAttributeView initialOwnerAcl = Files.getFileAttributeView(under, AclFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
    int ownerAclCount = 0;
    int ggAclCount = 0;
    int everyoneAclCount = 0;
    for (AclEntry aclEntry : initialOwnerAcl.getAcl()) {
        String name = aclEntry.principal().getName();
        if (name.equals("\\" + EVERYONE_GROUP_NAME)) {
            everyoneAclCount++;
        }
        if (name.contains(platform.getPrivilegedGroup())) {
            ggAclCount++;
        }
        if (name.contains(initialOwnerAcl.getOwner().getName())) {
            ownerAclCount++;
        }
    }
    assertEquals(3 + (initialOwnerAcl.getOwner().getName().contains(platform.getPrivilegedGroup()) ? 1 : 0), ownerAclCount);
    assertEquals(1 + (initialOwnerAcl.getOwner().getName().contains(platform.getPrivilegedGroup()) ? 3 : 0), ggAclCount);
    assertEquals(1, everyoneAclCount);
    String username = "ABCTEST";
    try {
        createWindowsTestUser(username, WINDOWS_TEST_PASSWORD);
        platform.setPermissions(FileSystemPermission.builder().ownerUser(username).build(), under, FileSystemPermission.Option.SetOwner);
        AclFileAttributeView updatedOwnerAcl = Files.getFileAttributeView(under, AclFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
        assertThat(updatedOwnerAcl.getOwner().getName(), containsString(username));
        List<AclEntry> updatedAcl = updatedOwnerAcl.getAcl();
        assertThat(updatedAcl, hasSize(5));
        ownerAclCount = 0;
        ggAclCount = 0;
        everyoneAclCount = 0;
        for (AclEntry aclEntry : updatedAcl) {
            String name = aclEntry.principal().getName();
            if (name.equals("\\" + EVERYONE_GROUP_NAME)) {
                everyoneAclCount++;
            }
            if (name.contains(platform.getPrivilegedGroup())) {
                ggAclCount++;
            }
            if (name.contains(updatedOwnerAcl.getOwner().getName())) {
                ownerAclCount++;
            }
        }
        assertEquals(3, ownerAclCount);
        assertEquals(1, ggAclCount);
        assertEquals(1, everyoneAclCount);
    } finally {
        deleteWindowsTestUser(username);
    }
}
Also used : UserPrincipalLookupService(java.nio.file.attribute.UserPrincipalLookupService) Path(java.nio.file.Path) AclFileAttributeView(java.nio.file.attribute.AclFileAttributeView) Platform(com.aws.greengrass.util.platforms.Platform) GroupPrincipal(java.nio.file.attribute.GroupPrincipal) AclEntry(java.nio.file.attribute.AclEntry) Matchers.emptyOrNullString(org.hamcrest.Matchers.emptyOrNullString) Matchers.containsString(org.hamcrest.Matchers.containsString) UserPrincipal(java.nio.file.attribute.UserPrincipal) Test(org.junit.jupiter.api.Test)

Aggregations

Platform (com.aws.greengrass.util.platforms.Platform)3 IOException (java.io.IOException)2 DockerLoginException (com.aws.greengrass.componentmanager.plugins.docker.exceptions.DockerLoginException)1 DockerServiceUnavailableException (com.aws.greengrass.componentmanager.plugins.docker.exceptions.DockerServiceUnavailableException)1 UserNotAuthorizedForDockerException (com.aws.greengrass.componentmanager.plugins.docker.exceptions.UserNotAuthorizedForDockerException)1 Path (java.nio.file.Path)1 AclEntry (java.nio.file.attribute.AclEntry)1 AclFileAttributeView (java.nio.file.attribute.AclFileAttributeView)1 GroupPrincipal (java.nio.file.attribute.GroupPrincipal)1 UserPrincipal (java.nio.file.attribute.UserPrincipal)1 UserPrincipalLookupService (java.nio.file.attribute.UserPrincipalLookupService)1 HashMap (java.util.HashMap)1 Matchers.containsString (org.hamcrest.Matchers.containsString)1 Matchers.emptyOrNullString (org.hamcrest.Matchers.emptyOrNullString)1 Test (org.junit.jupiter.api.Test)1 PidProcess (org.zeroturnaround.process.PidProcess)1