Search in sources :

Example 41 with InstanceInfo

use of com.netflix.appinfo.InstanceInfo in project eureka by Netflix.

the class InstanceResource method updateMetadata.

/**
     * Updates user-specific metadata information. If the key is already available, its value will be overwritten.
     * If not, it will be added.
     * @param uriInfo - URI information generated by jersey.
     * @return response indicating whether the operation was a success or
     *         failure.
     */
@PUT
@Path("metadata")
public Response updateMetadata(@Context UriInfo uriInfo) {
    try {
        InstanceInfo instanceInfo = registry.getInstanceByAppAndId(app.getName(), id);
        // ReplicationInstance information is not found, generate an error
        if (instanceInfo == null) {
            logger.error("Cannot find instance while updating metadata for instance {}", id);
            return Response.serverError().build();
        }
        MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
        Set<Entry<String, List<String>>> entrySet = queryParams.entrySet();
        Map<String, String> metadataMap = instanceInfo.getMetadata();
        // Metadata map is empty - create a new map
        if (Collections.emptyMap().getClass().equals(metadataMap.getClass())) {
            metadataMap = new ConcurrentHashMap<String, String>();
            InstanceInfo.Builder builder = new InstanceInfo.Builder(instanceInfo);
            builder.setMetadata(metadataMap);
            instanceInfo = builder.build();
        }
        // Add all the user supplied entries to the map
        for (Entry<String, List<String>> entry : entrySet) {
            metadataMap.put(entry.getKey(), entry.getValue().get(0));
        }
        registry.register(instanceInfo, false);
        return Response.ok().build();
    } catch (Throwable e) {
        logger.error("Error updating metadata for instance " + id, e);
        return Response.serverError().build();
    }
}
Also used : Entry(java.util.Map.Entry) List(java.util.List) InstanceInfo(com.netflix.appinfo.InstanceInfo) Path(javax.ws.rs.Path) PUT(javax.ws.rs.PUT)

Example 42 with InstanceInfo

use of com.netflix.appinfo.InstanceInfo in project eureka by Netflix.

the class EurekaUtilsTest method testIsInVpc.

@Test
public void testIsInVpc() {
    InstanceInfo instanceInfo1 = new InstanceInfo.Builder(InstanceInfoGenerator.takeOne()).setDataCenterInfo(new DataCenterInfo() {

        @Override
        public Name getName() {
            return Name.MyOwn;
        }
    }).build();
    Assert.assertFalse(EurekaUtils.isInVpc(instanceInfo1));
    InstanceInfo instanceInfo2 = InstanceInfoGenerator.takeOne();
    Assert.assertFalse(EurekaUtils.isInVpc(instanceInfo2));
    InstanceInfo instanceInfo3 = InstanceInfoGenerator.takeOne();
    ((AmazonInfo) instanceInfo3.getDataCenterInfo()).getMetadata().put(AmazonInfo.MetaDataKey.vpcId.getName(), "vpc-123456");
    Assert.assertTrue(EurekaUtils.isInVpc(instanceInfo3));
}
Also used : DataCenterInfo(com.netflix.appinfo.DataCenterInfo) InstanceInfo(com.netflix.appinfo.InstanceInfo) Test(org.junit.Test)

Example 43 with InstanceInfo

use of com.netflix.appinfo.InstanceInfo in project eureka by Netflix.

the class Jersey2ReplicationClient method sendHeartBeat.

/**
     * Compared to regular heartbeat, in the replication channel the server may return a more up to date
     * instance copy.
     */
@Override
public EurekaHttpResponse<InstanceInfo> sendHeartBeat(String appName, String id, InstanceInfo info, InstanceStatus overriddenStatus) {
    String urlPath = "apps/" + appName + '/' + id;
    Response response = null;
    try {
        WebTarget webResource = jerseyClient.target(serviceUrl).path(urlPath).queryParam("status", info.getStatus().toString()).queryParam("lastDirtyTimestamp", info.getLastDirtyTimestamp().toString());
        if (overriddenStatus != null) {
            webResource = webResource.queryParam("overriddenstatus", overriddenStatus.name());
        }
        Builder requestBuilder = webResource.request();
        addExtraHeaders(requestBuilder);
        // Jersey2 refuses to handle PUT with no body
        response = requestBuilder.accept(MediaType.APPLICATION_JSON_TYPE).put(Entity.entity("{}", MediaType.APPLICATION_JSON_TYPE));
        InstanceInfo infoFromPeer = null;
        if (response.getStatus() == Status.CONFLICT.getStatusCode() && response.hasEntity()) {
            infoFromPeer = response.readEntity(InstanceInfo.class);
        }
        return anEurekaHttpResponse(response.getStatus(), infoFromPeer).type(MediaType.APPLICATION_JSON_TYPE).build();
    } finally {
        if (logger.isDebugEnabled()) {
            logger.debug("[heartbeat] Jersey HTTP PUT {}; statusCode={}", urlPath, response == null ? "N/A" : response.getStatus());
        }
        if (response != null) {
            response.close();
        }
    }
}
Also used : EurekaHttpResponse(com.netflix.discovery.shared.transport.EurekaHttpResponse) EurekaHttpResponse.anEurekaHttpResponse(com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse) ReplicationListResponse(com.netflix.eureka.cluster.protocol.ReplicationListResponse) Response(javax.ws.rs.core.Response) Builder(javax.ws.rs.client.Invocation.Builder) WebTarget(javax.ws.rs.client.WebTarget) InstanceInfo(com.netflix.appinfo.InstanceInfo)

Example 44 with InstanceInfo

use of com.netflix.appinfo.InstanceInfo in project eureka by Netflix.

the class StatusFilter method doFilter.

/*
     * (non-Javadoc)
     *
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
     * javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    InstanceInfo myInfo = ApplicationInfoManager.getInstance().getInfo();
    InstanceStatus status = myInfo.getStatus();
    if (status != InstanceStatus.UP && response instanceof HttpServletResponse) {
        HttpServletResponse httpRespone = (HttpServletResponse) response;
        httpRespone.sendError(SC_TEMPORARY_REDIRECT, "Current node is currently not ready to serve requests -- current status: " + status + " - try another DS node: ");
    }
    chain.doFilter(request, response);
}
Also used : InstanceStatus(com.netflix.appinfo.InstanceInfo.InstanceStatus) HttpServletResponse(javax.servlet.http.HttpServletResponse) InstanceInfo(com.netflix.appinfo.InstanceInfo)

Example 45 with InstanceInfo

use of com.netflix.appinfo.InstanceInfo in project eureka by Netflix.

the class ElasticNetworkInterfaceBinder method bind.

/**
     * Binds an ENI to the instance.
     *
     * The candidate ENI's are deduced in the same wa the EIP binder works: Via dns records or via service urls,
     * depending on configuration.
     *
     * It will try to attach the first ENI that is:
     *      Available
     *      For this subnet
     *      In the list of candidate ENI's
     *
     * @throws MalformedURLException
     */
public void bind() throws MalformedURLException {
    InstanceInfo myInfo = ApplicationInfoManager.getInstance().getInfo();
    String myInstanceId = ((AmazonInfo) myInfo.getDataCenterInfo()).get(AmazonInfo.MetaDataKey.instanceId);
    String myZone = ((AmazonInfo) myInfo.getDataCenterInfo()).get(AmazonInfo.MetaDataKey.availabilityZone);
    final List<String> ips = getCandidateIps();
    Ordering<NetworkInterface> ipsOrder = Ordering.natural().onResultOf(new Function<NetworkInterface, Integer>() {

        public Integer apply(NetworkInterface networkInterface) {
            return ips.indexOf(networkInterface.getPrivateIpAddress());
        }
    });
    AmazonEC2 ec2Service = getEC2Service();
    String subnetId = instanceData(myInstanceId, ec2Service).getSubnetId();
    DescribeNetworkInterfacesResult result = ec2Service.describeNetworkInterfaces(new DescribeNetworkInterfacesRequest().withFilters(new Filter("private-ip-address", ips)).withFilters(new Filter("status", Lists.newArrayList("available"))).withFilters(new Filter("subnet-id", Lists.newArrayList(subnetId))));
    if (result.getNetworkInterfaces().isEmpty()) {
        logger.info("No ip is free to be associated with this instance. Candidate ips are: {} for zone: ", ips, myZone);
    } else {
        NetworkInterface selected = ipsOrder.min(result.getNetworkInterfaces());
        ec2Service.attachNetworkInterface(new AttachNetworkInterfaceRequest().withNetworkInterfaceId(selected.getNetworkInterfaceId()).withDeviceIndex(1).withInstanceId(myInstanceId));
    }
}
Also used : AmazonEC2(com.amazonaws.services.ec2.AmazonEC2) InstanceInfo(com.netflix.appinfo.InstanceInfo) AmazonInfo(com.netflix.appinfo.AmazonInfo)

Aggregations

InstanceInfo (com.netflix.appinfo.InstanceInfo)192 Test (org.junit.Test)74 Application (com.netflix.discovery.shared.Application)35 Applications (com.netflix.discovery.shared.Applications)22 AmazonInfo (com.netflix.appinfo.AmazonInfo)21 ArrayList (java.util.ArrayList)19 InstanceStatus (com.netflix.appinfo.InstanceInfo.InstanceStatus)11 Before (org.junit.Before)11 DiscoveryClient (com.netflix.discovery.DiscoveryClient)10 DecoderWrapper (com.netflix.discovery.converters.wrappers.DecoderWrapper)10 Lease (com.netflix.eureka.lease.Lease)9 HashMap (java.util.HashMap)8 Response (javax.ws.rs.core.Response)8 DataCenterInfo (com.netflix.appinfo.DataCenterInfo)7 CodecWrappers (com.netflix.discovery.converters.wrappers.CodecWrappers)7 EncoderWrapper (com.netflix.discovery.converters.wrappers.EncoderWrapper)7 ByteArrayInputStream (java.io.ByteArrayInputStream)7 ApplicationInfoManager (com.netflix.appinfo.ApplicationInfoManager)6 EurekaEntityFunctions.mergeApplications (com.netflix.discovery.util.EurekaEntityFunctions.mergeApplications)6 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)6