private void updateExistingContainer(ContainerState c, ContainerListCallback callback) { boolean changed = false; ContainerState patch = new ContainerState(); // handle power state changes PowerState newPowerState = callback.containerIdsAndState.get(c.id); if (newPowerState != null && c.powerState != newPowerState && !ContainerState.CONTAINER_UNHEALTHY_STATUS.equals(c.status)) { // do not modify the power state set during the health config check! logInfo("Changing power state of container %s (%s) from %s to %s", c.names, c.documentSelfLink, c.powerState, newPowerState); changed = true; patch.powerState = newPowerState; } if (changed) { // power state is change - save the new state and inspect the container sendRequest(Operation .createPatch(this, c.documentSelfLink) .setBodyNoCloning(patch)); inspectContainer(c, ServiceTaskCallback.createEmpty()); } }
private void disableContainersForHost(String computeStateSelfLink) { QueryTask containerQuery = QueryUtil.buildPropertyQuery(ContainerState.class, ContainerState.FIELD_NAME_PARENT_LINK, computeStateSelfLink); ContainerState errorState = new ContainerState(); errorState.powerState = ContainerState.PowerState.ERROR; new ServiceDocumentQuery<>(getHost(), ContainerState.class).query( containerQuery, (r) -> { if (r.hasException()) { logWarning("Failed to retrieve containers for ComputeState: %s", computeStateSelfLink); return; } else if (r.hasResult()) { logWarning("Disable container %s, because host %s is unavailable", r.getDocumentSelfLink(), computeStateSelfLink); sendRequest(Operation .createPatch(this, r.getDocumentSelfLink()) .setAuthorizationContext(getSystemAuthorizationContext()) .setBodyNoCloning(errorState)); } }); }
/** * Build a {@link ContainerState} instance that has a user-defined network and the * system-defined "bridge" network. Also build the inspect command map representation and use * the {@link ContainerStateMapper} to produce the mapped {@link ContainerState}. Both states * should be identical. */ @Test public void testCompareRunningContainerInUserNetworkAndMatchedContainerStateShouldPass() { String networkName = "test-network"; String ipv4 = "172.100.0.100"; String ipv6 = "fe80::aa"; String[] aliases = new String[] { "alias" }; String[] links = new String[] { "service:alias" }; predefinedState.networks.put(networkName, createServiceNetwork(networkName, ipv4, ipv6, aliases, links)); addNetworkToInspectMap(predefinedInspectMap, networkName, ipv4, ipv6, aliases, links); ContainerState mappedState = new ContainerState(); ContainerStateMapper.propertiesToContainerState(mappedState, predefinedInspectMap); assertTrue("predefined and mapped state should be equal", areEqualContainerStates(predefinedState, mappedState)); }
private ContainerState createContainerState(String parentLink, boolean isDiscovered) throws Throwable { ContainerState containerState = new ContainerState(); containerState.descriptionLink = isDiscovered ? String.format("%s-%s", SystemContainerDescriptions.DISCOVERED_DESCRIPTION_LINK, UUID.randomUUID().toString()) : UUID.randomUUID().toString(); containerState.image = "test-image"; containerState.tenantLinks = Collections.singletonList(TENANT_LINKS); containerState.command = new String[] { CONTAINER_COMMAND }; containerState.id = UUID.randomUUID().toString(); containerState.names = new ArrayList<>(Arrays.asList("name_" + containerState.id)); containerState.parentLink = parentLink; containerState = doPost(containerState, ContainerFactoryService.SELF_LINK); PortBinding[] ports = new PortBinding[1]; PortBinding port = new PortBinding(); port.containerPort = "8263"; ports[0] = port; containerState.ports = Arrays.asList(ports); containerState.extraHosts = new String[] { "extra-docker.host" }; return containerState; }
private ContainerState createSystemContainerState(ContainerState containerState, ContainerDescription containerDesc, String containerHostLink) { String systemContainerName = isSystemContainer( SystemContainerDescriptions.getSystemContainerNames(), containerState.names); final ContainerState systemContainerState = new ContainerState(); systemContainerState.documentSelfLink = containerState.documentSelfLink; systemContainerState.names = new ArrayList<>(); systemContainerState.names.add(systemContainerName); systemContainerState.descriptionLink = containerDesc.documentSelfLink; systemContainerState.parentLink = containerHostLink; systemContainerState.powerState = ContainerState.PowerState.PROVISIONING; systemContainerState.adapterManagementReference = containerDesc.instanceAdapterReference; systemContainerState.image = containerDesc.image; systemContainerState.command = containerDesc.command; systemContainerState.groupResourcePlacementLink = GroupResourcePlacementService.DEFAULT_RESOURCE_PLACEMENT_LINK; systemContainerState.system = Boolean.TRUE; systemContainerState.volumes = containerDesc.volumes; systemContainerState.id = containerState.id; return systemContainerState; }
/** * Build a {@link ContainerState} instance that has a user-defined network and the * system-defined "bridge" network. Also build the inspect command map representation and use * the {@link ContainerStateMapper} to produce the mapped {@link ContainerState}. Both states * should be identical. * * Note: in this test only the mandatory network properties (name and IPv4 address) are set and * all the others are set to <code>null</code>. Test should pass again. */ @Test public void testCompareRunningContainerInUserNetworkWithDefaultPropertiesAndMatchedContainerStateShouldPass() { String networkName = "test-network"; String ipv4 = "172.100.0.100"; predefinedState.networks.put(networkName, createServiceNetwork(networkName, ipv4)); addNetworkToInspectMap(predefinedInspectMap, networkName, ipv4); ContainerState mappedState = new ContainerState(); ContainerStateMapper.propertiesToContainerState(mappedState, predefinedInspectMap); assertTrue("predefined and mapped state should be equal", areEqualContainerStates(predefinedState, mappedState)); }
@Test public void testGetContainerService() { ContainerState state1 = new ContainerState(); state1.name = "test"; state1.image = "test"; state1 = doPostWithProjectHeader(state1, ContainerFactoryService.SELF_LINK, testProject1.documentSelfLink, ContainerState.class); ContainerState state2 = new ContainerState(); state2.name = "test"; state2.image = "test"; state2 = doPostWithProjectHeader(state2, ContainerFactoryService.SELF_LINK, testProject2.documentSelfLink, ContainerState.class); ServiceDocumentQueryResult project1Docs = getDocumentsWithinProject( ContainerFactoryService.SELF_LINK, testProject1.documentSelfLink); assertEquals(1, project1Docs.documentLinks.size()); assertTrue(project1Docs.documentLinks.contains(state1.documentSelfLink)); ServiceDocumentQueryResult project2Docs = getDocumentsWithinProject( ContainerFactoryService.SELF_LINK, testProject2.documentSelfLink); assertEquals(1, project2Docs.documentLinks.size()); assertTrue(project2Docs.documentLinks.contains(state2.documentSelfLink)); }
@Test public void testGetShellNoHostShouldFail() throws Throwable { waitForServiceAvailability(ContainerShellService.SELF_LINK); waitForServiceAvailability(ComputeService.FACTORY_LINK); waitForServiceAvailability(ContainerDescriptionService.FACTORY_LINK); waitForServiceAvailability(CompositeDescriptionFactoryService.SELF_LINK); waitForServiceAvailability(ContainerFactoryService.SELF_LINK); ContainerState containerState = new ContainerState(); containerState.image = "test-image"; containerState = doPost(containerState, ContainerFactoryService.SELF_LINK); try { getDocument(String.class, ContainerShellService.SELF_LINK + "?id=" + UriUtils.getLastPathSegment(containerState.documentSelfLink)); fail("It should have failed!"); } catch (ServiceNotFoundException e) { assertTrue( e.getMessage().contains("Service not found: " + host.getPublicUriAsString())); } }
private void changeContainerName( Operation post) { DummyServiceTaskState body = post.getBody(DummyServiceTaskState.class); ContainerState containerState = new ContainerState(); containerState.name = DummySubscriber.class.getSimpleName(); containerState.documentSelfLink = body.containerState.documentSelfLink; // Patch Container's name. TestContext context = new TestContext(1, Duration.ofSeconds(20)); Operation.createPatch(UriUtils.buildUri(getHost(), containerState.documentSelfLink)) .setBody(containerState) .setReferer(getHost().getUri()) .setCompletion((o, e) -> { if (e != null) { post.fail(e); context.fail(e); return; } }).sendWith(getHost()); context.await(); }
private void testStateStuckInProvisioning(boolean isSystemContainerMissingOnHost) throws Throwable { String systemContainerId = extractId(systemContainerLink); addContainerToMockAdapter(COMPUTE_HOST_LINK, systemContainerId, SystemContainerDescriptions.AGENT_CONTAINER_NAME, image, computeState.tenantLinks); startAndWaitHostContainerListDataCollection(); waitForContainer(systemContainerLink, image, PowerState.RUNNING, "System container state should be running after regular data collection."); ContainerState cs = new ContainerState(); cs.powerState = PowerState.PROVISIONING; doPatch(cs, systemContainerLink); waitForContainer(systemContainerLink, image, PowerState.PROVISIONING, "System container state should be provisioning after patching it to provisioning."); startAndWaitHostContainerListDataCollection(); waitForContainer(systemContainerLink, image, PowerState.RUNNING, "System container state should be running after the second data collection when the" + " state was provisioning."); }
@Test public void testCreatedContainerShouldBeInspectedOnNetworkOperationFailure() throws Throwable { // delete provisioned containers removeContainer(); // create a new state that has never been data collected createContainerState(); // update the container state with a network that does not exist ServiceNetwork network = new ServiceNetwork(); network.name = "network"; ContainerState patch = new ContainerState(); patch.networks = new HashMap<>(); patch.networks.put(network.name, network); patchContainerState(patch); sendGetContainerStateRequest(); assertNull("Container ID should have been null before creation on host", containerState.id); // This should fail on the attempt to connect the container to the network createContainer(true /* expect error */); // The createContainer method will verify that the id has been collected }
protected void createContainerState() throws Throwable { waitForServiceAvailability(ContainerFactoryService.SELF_LINK); ContainerState containerState = new ContainerState(); assertNotNull("parentLink", parentComputeStateLink); containerState.parentLink = parentComputeStateLink; containerState.descriptionLink = containerDescriptionLink; containerState.names = new ArrayList<>(1); containerState.names.add(TEST_CONTAINER_NAME); List<String> tenantLinks = new ArrayList<>(); tenantLinks.add(TEST_CONTAINER_GROUP); containerState.tenantLinks = tenantLinks; containerState.env = TEST_ENV; // add a custom property containerState.customProperties = new HashMap<>(); containerState.customProperties.put(TEST_CUSTOM_PROP_NAME, TEST_CUSTOM_PROP_VALUE); ContainerState container = doPost(containerState, ContainerFactoryService.SELF_LINK); containerStateReference = UriUtils.extendUri(host.getUri(), container.documentSelfLink); }
private ContainerState createContainer(String groupResourcePlacementLink) throws Throwable { ContainerState containerState = new ContainerState(); containerState.id = UUID.randomUUID().toString(); containerState.names = new ArrayList<>(Arrays.asList("name_" + containerState.id)); containerState.command = new String[] { "cat" }; containerState.adapterManagementReference = URI .create("http://remote-host:8082/docker-executor"); containerState.address = "http://docker:5432/"; containerState.descriptionLink = UriUtils.buildUriPath( ContainerDescriptionService.FACTORY_LINK, "docker-nginx"); containerState.customProperties = new HashMap<>(); containerState.powerState = ContainerState.PowerState.RUNNING; containerState.parentLink = "/parent/link"; containerState.groupResourcePlacementLink = groupResourcePlacementLink; containerState = doPost(containerState, ContainerFactoryService.SELF_LINK); return containerState; } }
protected ContainerState createContainer(ContainerDescription desc, String hostLink) throws Throwable { ContainerState container = new ContainerState(); container.descriptionLink = desc.documentSelfLink; container.id = UUID.randomUUID().toString(); container.ports = desc.portBindings != null ? new ArrayList<>(Arrays.asList(desc.portBindings)) : null; List<String> hosts = new ArrayList<>(initialHostLinks); Collections.shuffle(hosts); container.parentLink = hostLink; container.powerState = PowerState.RUNNING; container.compositeComponentLink = UriUtils.buildUriPath( CompositeComponentFactoryService.SELF_LINK, state.contextId); container = doPost(container, ContainerFactoryService.SELF_LINK); assertNotNull(container); addForDeletion(container); return container; }
@Test public void testPatchExpiration() throws Throwable { ContainerState container = createContainer("/parent/1", "tenant1"); URI containerUri = UriUtils.buildUri(host, container.documentSelfLink); ContainerState patch = new ContainerState(); long expirationTime = Utils.fromNowMicrosUtc(TimeUnit.SECONDS.toMicros(30)); patch.documentExpirationTimeMicros = expirationTime; doOperation(patch, containerUri, false, Action.PATCH); ContainerState updatedContainer = getDocument(ContainerState.class, container.documentSelfLink); assertEquals(expirationTime, updatedContainer.documentExpirationTimeMicros); patch = new ContainerState(); patch.documentExpirationTimeMicros = -1; doOperation(patch, containerUri, false, Action.PATCH); updatedContainer = getDocument(ContainerState.class, container.documentSelfLink); assertEquals(0, updatedContainer.documentExpirationTimeMicros); }
private ContainerState createContainer(String parentLink, String group) throws Throwable { ContainerState containerState = new ContainerState(); containerState.id = UUID.randomUUID().toString(); containerState.names = new ArrayList<>(Arrays.asList("name_" + containerState.id)); containerState.command = new String[] { "cat" }; containerState.adapterManagementReference = URI .create("http://remote-host:8082/docker-executor"); containerState.address = "http://docker:5432/"; containerState.descriptionLink = UriUtils.buildUriPath( ContainerDescriptionService.FACTORY_LINK, "docker-nginx"); containerState.customProperties = new HashMap<>(); containerState.powerState = ContainerState.PowerState.RUNNING; containerState.parentLink = parentLink; containerState.tenantLinks = Collections.singletonList(group); containerState = doPost(containerState, ContainerFactoryService.SELF_LINK); return containerState; }
@Test public void TestMapContainerWithNullInputStatus() { ContainerState outState = new ContainerState(); Container inContainer = new Container(); inContainer.name = "test"; inContainer.image = "image"; KubernetesContainerStateMapper.mapContainer(outState, inContainer, null); Assert.assertNull(outState.name); Assert.assertNull(outState.names); Assert.assertNull(outState.id); Assert.assertNull(outState.image); Assert.assertNull(outState.command); Assert.assertNull(outState.env); Assert.assertNull(outState.ports); Assert.assertNull(outState.powerState); }
@Test public void testODataWithManyEntities() throws Throwable { int numberOfContainers = 6000; List<String> containers = new ArrayList<>(); for (int i = 0; i <= numberOfContainers; i++) { ContainerState state = createContainer("/parent/1", "tenant1"); containers.add(state.documentSelfLink); } for (int i = 0; i <= numberOfContainers; i++) { ContainerState containerState = new ContainerState(); containerState.customProperties = new HashMap<String, String>(); containerState.customProperties.put("keyTestProp", "valueTestProp"); doPatch(containerState, containers.get(i)); } queryContainers(numberOfContainers + 1); countQueryContainers(numberOfContainers + 1); }
@Test public void testEvaluateSimpleProvisioningBinding() { List<Binding> bindings = Arrays .asList(binding(Arrays.asList("parentLink"), "_resource~A~parentLink")); Map<String, NestedState> containers = new HashMap<>(); ContainerState containerState = new ContainerState(); containerState.parentLink = "some-host"; containers.put("A", new NestedState(containerState)); ContainerState containerStateE = new ContainerState(); NestedState evalObj = BindingEvaluator .evaluateProvisioningTimeBindings(new NestedState(containerStateE), bindings, containers); assertNotNull(evalObj); assertEquals(((ContainerState) evalObj.object).parentLink, containerState.parentLink); }
@Before public void setUp() throws Throwable { waitForServiceAvailability(ContainerDescriptionService.FACTORY_LINK); waitForServiceAvailability(CompositeDescriptionFactoryService.SELF_LINK); waitForServiceAvailability(ContainerFactoryService.SELF_LINK); state = new ContainerState(); state.id = updatedTestId; state.image = updatedTestValue; state = doPost(state, ContainerFactoryService.SELF_LINK); results = Collections.synchronizedList(new ArrayList<>()); subscriptionManager = new SubscriptionManager<>( host, host.getId(), state.documentSelfLink, ContainerState.class); waitForServiceAvailability(ServiceUriPaths.CORE_QUERY_TASKS); waitForServiceAvailability(state.documentSelfLink); }