Search in sources :

Example 1 with Logger

use of com.aws.greengrass.logging.api.Logger in project aws-greengrass-nucleus by aws-greengrass.

the class LifecycleTest method GIVEN_state_running_WHEN_errored_3_times_THEN_broken.

@Test
void GIVEN_state_running_WHEN_errored_3_times_THEN_broken() throws InterruptedException {
    lifecycle = spy(new Lifecycle(greengrassService, logger, greengrassService.getPrivateConfig()));
    initLifecycleState(lifecycle, State.NEW);
    CountDownLatch reachedRunning1 = new CountDownLatch(1);
    CountDownLatch reachedRunning2 = new CountDownLatch(1);
    CountDownLatch reachedRunning3 = new CountDownLatch(1);
    Mockito.doAnswer(mock -> {
        lifecycle.reportState(State.RUNNING);
        reachedRunning1.countDown();
        return null;
    }).doAnswer(mock -> {
        lifecycle.reportState(State.RUNNING);
        reachedRunning2.countDown();
        return null;
    }).doAnswer(mock -> {
        lifecycle.reportState(State.RUNNING);
        reachedRunning3.countDown();
        return null;
    }).when(greengrassService).startup();
    lifecycle.initLifecycleThread();
    lifecycle.requestStart();
    assertTrue(reachedRunning1.await(5, TimeUnit.SECONDS));
    verify(lifecycle, timeout(2000)).setState(any(), eq(State.RUNNING));
    // We verify that setState is called, but that doesn't verify that the call to setState ended which is what
    // we actually need to know in order to move on to the next part of the test.
    // So, validate that it has actually set the state to be running before reporting
    // the next error. Otherwise, it may register an error from STARTING instead of from RUNNING
    assertThat(greengrassService::getState, eventuallyEval(is(State.RUNNING)));
    // Report 1st error
    lifecycle.reportState(State.ERRORED);
    assertTrue(reachedRunning2.await(5, TimeUnit.SECONDS));
    verify(lifecycle, timeout(2000).times(2)).setState(any(), eq(State.RUNNING));
    assertThat(greengrassService::getState, eventuallyEval(is(State.RUNNING)));
    // Report 2nd error
    lifecycle.reportState(State.ERRORED);
    assertTrue(reachedRunning3.await(5, TimeUnit.SECONDS));
    verify(lifecycle, timeout(2000).times(3)).setState(any(), eq(State.RUNNING));
    assertThat(greengrassService::getState, eventuallyEval(is(State.RUNNING)));
    // Report 3rd error
    lifecycle.reportState(State.ERRORED);
    verify(lifecycle, timeout(10_000)).setState(any(), eq(State.BROKEN));
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) RUNTIME_STORE_NAMESPACE_TOPIC(com.aws.greengrass.lifecyclemanager.GreengrassService.RUNTIME_STORE_NAMESPACE_TOPIC) YAMLMapper(com.fasterxml.jackson.dataformat.yaml.YAMLMapper) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) ByteArrayInputStream(java.io.ByteArrayInputStream) State(com.aws.greengrass.dependency.State) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) Map(java.util.Map) LogManager(com.aws.greengrass.logging.impl.LogManager) ThreadFactory(java.util.concurrent.ThreadFactory) Configuration(com.aws.greengrass.config.Configuration) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) Instant(java.time.Instant) EventuallyLambdaMatcher.eventuallyEval(com.github.grantwest.eventually.EventuallyLambdaMatcher.eventuallyEval) ZoneId(java.time.ZoneId) Executors(java.util.concurrent.Executors) Test(org.junit.jupiter.api.Test) Topics(com.aws.greengrass.config.Topics) CountDownLatch(java.util.concurrent.CountDownLatch) STATE_TOPIC_NAME(com.aws.greengrass.lifecyclemanager.Lifecycle.STATE_TOPIC_NAME) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Matchers.is(org.hamcrest.Matchers.is) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Setter(lombok.Setter) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) PRIVATE_STORE_NAMESPACE_TOPIC(com.aws.greengrass.lifecyclemanager.GreengrassService.PRIVATE_STORE_NAMESPACE_TOPIC) Mock(org.mockito.Mock) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Mockito.spy(org.mockito.Mockito.spy) Coerce(com.aws.greengrass.util.Coerce) Mockito.lenient(org.mockito.Mockito.lenient) UpdateBehaviorTree(com.aws.greengrass.config.UpdateBehaviorTree) Mockito.timeout(org.mockito.Mockito.timeout) GGExtension(com.aws.greengrass.testcommons.testutilities.GGExtension) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Context(com.aws.greengrass.dependency.Context) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) ExecutorService(java.util.concurrent.ExecutorService) Executor(java.util.concurrent.Executor) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) DependencyType(com.amazon.aws.iot.greengrass.component.common.DependencyType) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Topic(com.aws.greengrass.config.Topic) Mockito(org.mockito.Mockito) AfterEach(org.junit.jupiter.api.AfterEach) Clock(java.time.Clock) Logger(com.aws.greengrass.logging.api.Logger) InputStream(java.io.InputStream) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test)

Example 2 with Logger

use of com.aws.greengrass.logging.api.Logger in project aws-greengrass-nucleus by aws-greengrass.

the class LogManagerHelperTest method GIVEN_mock_service_WHEN_getComponentLogger_THEN_logs_to_correct_log_file.

@Test
void GIVEN_mock_service_WHEN_getComponentLogger_THEN_logs_to_correct_log_file() throws IOException {
    when(mockGreengrassService.getServiceName()).thenReturn("MockService");
    LogConfig.getRootLogConfig().setStore(LogStore.FILE);
    Logger componentLogger = LogManagerHelper.getComponentLogger(mockGreengrassService);
    componentLogger.atInfo().log("Something");
    LogConfig logConfig = LogManager.getLogConfigurations().get("MockService");
    File logFile = new File(logConfig.getStoreName());
    assertThat(logFile, aFileNamed(equalToIgnoringCase("MockService.log")));
    List<String> lines = Files.readAllLines(logFile.toPath());
    assertThat(lines.get(0), containsString("Something"));
    File ggLogFile = new File(LogManager.getRootLogConfiguration().getStoreName());
    assertThat(ggLogFile, aFileNamed(equalToIgnoringCase("greengrass.log")));
    assertEquals(0, ggLogFile.length());
}
Also used : Matchers.containsString(org.hamcrest.Matchers.containsString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Logger(com.aws.greengrass.logging.api.Logger) File(java.io.File) LogConfig(com.aws.greengrass.logging.impl.config.LogConfig) Test(org.junit.jupiter.api.Test)

Example 3 with Logger

use of com.aws.greengrass.logging.api.Logger in project aws-greengrass-nucleus by aws-greengrass.

the class SystemServiceUtils method runCommand.

/**
 * Simply run a command with privileges.
 *
 * @param logger Logger to use
 * @param eventName logging event
 * @param command command to run
 * @param ignoreError ignore errors from this command
 * @throws IOException for command failure
 * @throws InterruptedException if interrupted while running
 */
@SuppressWarnings("PMD.CloseResource")
static void runCommand(Logger logger, String eventName, String command, boolean ignoreError) throws IOException, InterruptedException {
    logger.atDebug(eventName).log(command);
    Exec exec = Platform.getInstance().createNewProcessRunner().withShell(command);
    if (Platform.getInstance().getPrivilegedUser() != null) {
        exec.withUser(Platform.getInstance().getPrivilegedUser());
    }
    if (Platform.getInstance().getPrivilegedGroup() != null) {
        exec.withGroup(Platform.getInstance().getPrivilegedGroup());
    }
    boolean success = exec.withOut(s -> logger.atWarn(eventName).kv("command", command).kv("stdout", s.toString().trim()).log()).withErr(s -> logger.atError(eventName).kv("command", command).kv("stderr", s.toString().trim()).log()).successful(true);
    if (!success && !ignoreError) {
        throw new IOException(String.format("Command %s failed", command));
    }
}
Also used : Exec(com.aws.greengrass.util.Exec) Platform(com.aws.greengrass.util.platforms.Platform) Exec(com.aws.greengrass.util.Exec) KernelAlternatives(com.aws.greengrass.lifecyclemanager.KernelAlternatives) IOException(java.io.IOException) Logger(com.aws.greengrass.logging.api.Logger) IOException(java.io.IOException)

Example 4 with Logger

use of com.aws.greengrass.logging.api.Logger in project aws-greengrass-nucleus by aws-greengrass.

the class LifecycleTest method GIVEN_state_running_WHEN_errored_long_time_in_between_THEN_not_broken.

@Test
void GIVEN_state_running_WHEN_errored_long_time_in_between_THEN_not_broken() throws InterruptedException {
    Clock clock = Clock.fixed(Instant.now(), ZoneId.systemDefault());
    context.put(Clock.class, clock);
    lifecycle = spy(new Lifecycle(greengrassService, logger, greengrassService.getPrivateConfig()));
    initLifecycleState(lifecycle, State.NEW);
    CountDownLatch reachedRunning1 = new CountDownLatch(1);
    CountDownLatch reachedRunning2 = new CountDownLatch(1);
    CountDownLatch reachedRunning3 = new CountDownLatch(1);
    CountDownLatch reachedRunning4 = new CountDownLatch(1);
    Mockito.doAnswer(mock -> {
        lifecycle.reportState(State.RUNNING);
        reachedRunning1.countDown();
        return null;
    }).doAnswer(mock -> {
        lifecycle.reportState(State.RUNNING);
        reachedRunning2.countDown();
        return null;
    }).doAnswer(mock -> {
        lifecycle.reportState(State.RUNNING);
        reachedRunning3.countDown();
        return null;
    }).doAnswer(mock -> {
        lifecycle.reportState(State.RUNNING);
        reachedRunning4.countDown();
        return null;
    }).when(greengrassService).startup();
    lifecycle.initLifecycleThread();
    lifecycle.requestStart();
    assertTrue(reachedRunning1.await(5, TimeUnit.SECONDS));
    verify(lifecycle, timeout(1000)).setState(any(), eq(State.RUNNING));
    // Report 1st error
    lifecycle.reportState(State.ERRORED);
    assertTrue(reachedRunning2.await(5, TimeUnit.SECONDS));
    verify(lifecycle, timeout(1000).times(2)).setState(any(), eq(State.RUNNING));
    // Report 2nd error
    lifecycle.reportState(State.ERRORED);
    assertTrue(reachedRunning3.await(5, TimeUnit.SECONDS));
    verify(lifecycle, timeout(1000).times(3)).setState(any(), eq(State.RUNNING));
    // Report 3rd error, but after a while
    clock = Clock.offset(clock, Duration.ofHours(1).plusMillis(1));
    context.put(Clock.class, clock);
    lifecycle.reportState(State.ERRORED);
    assertTrue(reachedRunning4.await(5, TimeUnit.SECONDS));
    verify(lifecycle, timeout(1000).times(4)).setState(any(), eq(State.RUNNING));
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) RUNTIME_STORE_NAMESPACE_TOPIC(com.aws.greengrass.lifecyclemanager.GreengrassService.RUNTIME_STORE_NAMESPACE_TOPIC) YAMLMapper(com.fasterxml.jackson.dataformat.yaml.YAMLMapper) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) ByteArrayInputStream(java.io.ByteArrayInputStream) State(com.aws.greengrass.dependency.State) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) Map(java.util.Map) LogManager(com.aws.greengrass.logging.impl.LogManager) ThreadFactory(java.util.concurrent.ThreadFactory) Configuration(com.aws.greengrass.config.Configuration) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) Instant(java.time.Instant) EventuallyLambdaMatcher.eventuallyEval(com.github.grantwest.eventually.EventuallyLambdaMatcher.eventuallyEval) ZoneId(java.time.ZoneId) Executors(java.util.concurrent.Executors) Test(org.junit.jupiter.api.Test) Topics(com.aws.greengrass.config.Topics) CountDownLatch(java.util.concurrent.CountDownLatch) STATE_TOPIC_NAME(com.aws.greengrass.lifecyclemanager.Lifecycle.STATE_TOPIC_NAME) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Matchers.is(org.hamcrest.Matchers.is) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Setter(lombok.Setter) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) PRIVATE_STORE_NAMESPACE_TOPIC(com.aws.greengrass.lifecyclemanager.GreengrassService.PRIVATE_STORE_NAMESPACE_TOPIC) Mock(org.mockito.Mock) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Mockito.spy(org.mockito.Mockito.spy) Coerce(com.aws.greengrass.util.Coerce) Mockito.lenient(org.mockito.Mockito.lenient) UpdateBehaviorTree(com.aws.greengrass.config.UpdateBehaviorTree) Mockito.timeout(org.mockito.Mockito.timeout) GGExtension(com.aws.greengrass.testcommons.testutilities.GGExtension) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Context(com.aws.greengrass.dependency.Context) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) ExecutorService(java.util.concurrent.ExecutorService) Executor(java.util.concurrent.Executor) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) DependencyType(com.amazon.aws.iot.greengrass.component.common.DependencyType) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Topic(com.aws.greengrass.config.Topic) Mockito(org.mockito.Mockito) AfterEach(org.junit.jupiter.api.AfterEach) Clock(java.time.Clock) Logger(com.aws.greengrass.logging.api.Logger) InputStream(java.io.InputStream) Clock(java.time.Clock) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test)

Example 5 with Logger

use of com.aws.greengrass.logging.api.Logger in project aws-greengrass-nucleus by aws-greengrass.

the class LogManagerHelperTest method GIVEN_nondefault_options_on_root_logger_WHEN_create_component_logger_THEN_inherits_options.

@Test
void GIVEN_nondefault_options_on_root_logger_WHEN_create_component_logger_THEN_inherits_options() {
    LogManager.reconfigureAllLoggers(LogConfigUpdate.builder().level(Level.TRACE).format(LogFormat.JSON).build());
    when(mockGreengrassService.getServiceName()).thenReturn("MockService2");
    Logger logger = LogManagerHelper.getComponentLogger(mockGreengrassService);
    assertTrue(logger.isTraceEnabled());
    assertEquals(LogFormat.JSON, LogManager.getLogConfigurations().get("MockService2").getFormat());
}
Also used : Logger(com.aws.greengrass.logging.api.Logger) Test(org.junit.jupiter.api.Test)

Aggregations

Logger (com.aws.greengrass.logging.api.Logger)8 Test (org.junit.jupiter.api.Test)7 Configuration (com.aws.greengrass.config.Configuration)3 Topics (com.aws.greengrass.config.Topics)3 UpdateBehaviorTree (com.aws.greengrass.config.UpdateBehaviorTree)3 Context (com.aws.greengrass.dependency.Context)3 LogConfig (com.aws.greengrass.logging.impl.config.LogConfig)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 IOException (java.io.IOException)3 DependencyType (com.amazon.aws.iot.greengrass.component.common.DependencyType)2 Topic (com.aws.greengrass.config.Topic)2 State (com.aws.greengrass.dependency.State)2 PRIVATE_STORE_NAMESPACE_TOPIC (com.aws.greengrass.lifecyclemanager.GreengrassService.PRIVATE_STORE_NAMESPACE_TOPIC)2 RUNTIME_STORE_NAMESPACE_TOPIC (com.aws.greengrass.lifecyclemanager.GreengrassService.RUNTIME_STORE_NAMESPACE_TOPIC)2 STATE_TOPIC_NAME (com.aws.greengrass.lifecyclemanager.Lifecycle.STATE_TOPIC_NAME)2 LogManager (com.aws.greengrass.logging.impl.LogManager)2 LogConfigUpdate (com.aws.greengrass.logging.impl.config.model.LogConfigUpdate)2 GGExtension (com.aws.greengrass.testcommons.testutilities.GGExtension)2 Coerce (com.aws.greengrass.util.Coerce)2 YAMLMapper (com.fasterxml.jackson.dataformat.yaml.YAMLMapper)2