Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright (C) 2013-2015 Dell, Inc ==================================================================== Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ====================================================================
 
 
 package org.dasein.cloud.azure.network;
 
 
 import  javax.annotation.Nonnull;
 import  javax.annotation.Nullable;
Created by Vlad_Munthiu on 6/10/2014.
 
     static private final Logger logger = Logger.getLogger(AzureLoadBalancerSupport.class);
     static private final Logger wire   = Azure.getWireLogger(AzureLoadBalancerSupport.class);
 
     public static final String RESOURCE_PROFILES = "/services/WATM/profiles";
     public static final String RESOURCE_PROFILE = "/services/WATM/profiles/%s";
     public static final String RESOURCE_DEFINITIONS = "/services/WATM/profiles/%s/definitions";
     public static final String RESOURCE_DEFINITION = "/services/WATM/profiles/%s/definitions/1";
 
     private volatile transient AzureLoadBalancerCapabilities capabilities;
     public static final String TRAFFIC_MANAGER_DNS_NAME = "trafficmanager.net";
 
     public AzureLoadBalancerSupport(@Nonnull Azure provider) {
         super(provider);
 
          = new AzureLoadBalancerCapabilities(provider);
     }

    
Provides access to meta-data about load balancer capabilities in the current region of this cloud.

Returns:
a description of the features supported by this region of this cloud
Throws:
org.dasein.cloud.InternalException an error occurred within the Dasein Cloud API implementation
org.dasein.cloud.CloudException an error occurred within the cloud provider
 
     @Nonnull
     @Override
         return ;
     }

    
Indicates whether the current account has access to load balancer services in the current region.

Returns:
true if the current account has access to load balancer services in the current region
Throws:
org.dasein.cloud.CloudException an error occurred with the cloud provider while performing this action
org.dasein.cloud.InternalException an error occurred within the Dasein Cloud implementation while performing this action
 
     @Override
     public boolean isSubscribed() throws CloudExceptionInternalException {
         return true;
     }
 
     @Override
     public LoadBalancerHealthCheck createLoadBalancerHealthCheck(@Nullable String name, @Nullable String description, @Nullable String host, @Nullable LoadBalancerHealthCheck.HCProtocol protocolint port, @Nullable String pathint intervalint timeoutint healthyCountint unhealthyCountthrows CloudExceptionInternalException{
         throw new OperationNotSupportedException("Health check should be created only when creating the load balancer for Microsoft Azure cloud");
     }
 
     @Override
         throw new OperationNotSupportedException("Health check should be created only when creating the load balancer for Microsoft Azure cloud");
     }
    @Override
    public @Nonnull String createLoadBalancer(@Nonnull LoadBalancerCreateOptions optionsthrows CloudExceptionInternalException {
        if(options.getHealthCheckOptions() == null)
            throw new InternalException("Cannot create load balancer without health check options");
        if(options.getName() == null || options.getName().isEmpty())
            throw new InternalException("Cannot create load balancer without a name");
            throw new InternalException("Azure only supports HTTP and HTTPS protocol for HealthCheckOptions");
        ProfileModel profileModel = new ProfileModel();
        profileModel.setDomainName(String.format("%s.%s"options.getName(), ));
        profileModel.setName(options.getName());
        AzureMethod azureMethod = new AzureMethod(this.getProvider());
        try {
            azureMethod.post(profileModel);
        }
        catch (JAXBException e)
        {
            .error(e.getMessage());
            throw new InternalException(e);
        }
        DefinitionModel definition = new DefinitionModel();
        //add dnsOptions
        DefinitionModel.DnsOptions dnsOptions = new DefinitionModel.DnsOptions();
        dnsOptions.setTimeToLiveInSeconds("300");
        definition.setDnsOptions(dnsOptions);
        //add monitor
        DefinitionModel.MonitorModel monitor = new DefinitionModel.MonitorModel();
        monitor.setIntervalInSeconds("30");
        monitor.setTimeoutInSeconds("10");
        monitor.setToleratedNumberOfFailures("3");
        monitor.setProtocol(options.getHealthCheckOptions().getProtocol().toString());
        monitor.setPort(String.valueOf(options.getHealthCheckOptions().getPort()));
        DefinitionModel.HttpOptionsModel httpOptions = new DefinitionModel.HttpOptionsModel();
        httpOptions.setVerb("GET");
        httpOptions.setRelativePath(options.getHealthCheckOptions().getPath());
        httpOptions.setExpectedStatusCode("200");
        monitor.setHttpOptions(httpOptions);
        monitors.add(monitor);
        definition.setMonitors(monitors);
        //add policy
        DefinitionModel.PolicyModel policy = new DefinitionModel.PolicyModel();
        String loadBalancingMethod = "RoundRobin";
        LbListener lbListener =  options.getListeners()[0];
        if(lbListener != null) {
            if (lbListener.getAlgorithm() != null && lbListener.getAlgorithm() == .) {
                loadBalancingMethod = "Performance";
            }
            else if(lbListener.getAlgorithm() != null && lbListener.getAlgorithm() == .) {
                loadBalancingMethod = "Failover";
            }
            //default is RoundRobin
        }
        policy.setLoadBalancingMethod(loadBalancingMethod);
        for(LoadBalancerEndpoint endPoint : options.getEndpoints())
        {
            DefinitionModel.EndPointModel endPointModel = new DefinitionModel.EndPointModel();
            endPointModel.setDomainName(endPoint.getEndpointValue());
            endPointModel.setStatus("Enabled");
            endPointModel.setType("CloudService");
            endPointsToAdd.add(endPointModel);
        }
        policy.setEndPoints(endPointsToAdd);
        definition.setPolicy(policy);
        try {
            azureMethod.post(String.format(options.getName()), definition);
        }
        catch (Exception ex)
        {
            try {
                //try to remove previously created profile from TrafficManager
                azureMethod.invoke("DELETE"this.getContext().getAccountNumber(),
                        String.format(options.getName()), null);
                .error(ex.getMessage());
                throw new CloudException(ex);
            }
            catch (Exception e)
            {
                .error(e.getMessage());
                throw new CloudException(e);
            }
        }
        return options.getName();
    }
    @Override
    public void removeLoadBalancer(@Nonnull String loadBalancerIdthrows CloudExceptionInternalException
    {
        if(loadBalancerId == null || loadBalancerId.isEmpty())
        throw new InternalException("Cannot remove load balancer. Please specify the id for load balancer to remove");
        AzureMethod method = new AzureMethod(this.getProvider());
        method.invoke("DELETE"this.getContext().getAccountNumber(), String.format(loadBalancerId), null);
    }
    @Override
    {
        ProviderContext ctx = this.getProvider().getContext();
        ifctx == null ) {
            throw new AzureConfigException("No context was specified for this request");
        }
        ArrayList<LoadBalancerloadBalancers = new ArrayList<LoadBalancer>();
        ProfilesModel profileResponseModels = getProfiles();
        if(profileResponseModels == null)
            return Collections.emptyList();
        if(profileResponseModels.getProfiles() == null)
            return Collections.emptyList();
        for (ProfileModel profile : profileResponseModels.getProfiles())
        {
            DefinitionModel definitionModel = getDefinition(profile.getName());
            LoadBalancer loadBalancer = toLoadBalancer(ctxprofiledefinitionModel);
            loadBalancers.add(loadBalancer);
        }
        return loadBalancers;
    }
    @Override
    public LoadBalancer getLoadBalancer(@Nonnull String loadBalancerIdthrows CloudExceptionInternalException
    {
        ProviderContext ctx = this.getProvider().getContext();
        ifctx == null ) {
            throw new AzureConfigException("No context was specified for this request");
        }
        ProfileModel profileModel = getProfile(loadBalancerId);
        if(profileModel == null)
            return null;
        DefinitionModel definitionModel = getDefinition(loadBalancerId);
        return toLoadBalancer(ctxprofileModeldefinitionModel);
    }
    private LoadBalancer toLoadBalancer(ProviderContext ctxProfileModel profileModelDefinitionModel definitionModel) {
        LoadBalancerState lbState = definitionModel.getStatus().equalsIgnoreCase("enabled") ? . : .;
        String lbId = profileModel.getDomainName().substring(0, profileModel.getDomainName().indexOf("."));
        LoadBalancer loadBalancer = LoadBalancer.getInstance(ctx.getAccountNumber(), nulllbIdlbState,
                profileModel.getName(), profileModel.getName(), .profileModel.getDomainName());
        loadBalancer.setProviderLBHealthCheckId(lbId);
        LbAlgorithm lbAlgorithm = .;
        if(definitionModel.getPolicy().getLoadBalancingMethod().equalsIgnoreCase("performance"))
            lbAlgorithm = .;
        else if(definitionModel.getPolicy().getLoadBalancingMethod().equalsIgnoreCase("failover"))
            lbAlgorithm = .;
        LbListener lbListener = LbListener.getInstance(lbAlgorithm""null, 0, 0);
        loadBalancer.withListeners(lbListener);
        return loadBalancer;
    }
    @Override
    public void addIPEndpoints(@Nonnull String toLoadBalancerId, @Nonnull String ... ipAddressesthrows CloudExceptionInternalException {
        throw new OperationNotSupportedException("Adding IP endpoints to an existing load balancer is not currently supported by Microsoft Azure cloud");
    }
    @Override
    public void addServers(@Nonnull String toLoadBalancerId, @Nonnull String ... serverIdsToAddthrows CloudExceptionInternalException
    {
        DefinitionModel definitionModel = getDefinition(toLoadBalancerId);
        for (String serverToAddId : serverIdsToAdd)
        {
            String[] parts = serverToAddId.split(":");
            DefinitionModel.EndPointModel endPointModel = new DefinitionModel.EndPointModel();
            endPointModel.setDomainName(parts[0] + ".cloudapp.net");
            endPointModel.setStatus("Enabled");
            endPointModel.setType("CloudService");
            if(definitionModel.getPolicy().getEndPoints() == null)
                definitionModel.getPolicy().setEndPoints(new ArrayList<DefinitionModel.EndPointModel>());
            definitionModel.getPolicy().getEndPoints().add(endPointModel);
        }
        try {
            AzureMethod method = new AzureMethod(this.getProvider());
            method.post(String.format(toLoadBalancerId), definitionModel);
        } catch (JAXBException e) {
            .error(e.getMessage());
            throw new InternalException(e);
        }
    }
    @Override
    public @Nonnull Iterable<LoadBalancerEndpointlistEndpoints(@Nonnull String forLoadBalancerIdthrows CloudExceptionInternalException
    {
        final Azure provider = getProvider();
        // this list VM call can be very slow, so we cache for a short time to help with clients calling
        // listEndpoints() on many LBs in a short period of time.
        Cache<VirtualMachinecache = Cache.getInstance(provider"LoadBalancerVMs"VirtualMachine.class.new TimePeriod<Minute>(1, .));
        Collection<VirtualMachinevirtualMachines = (Collection<VirtualMachine>)cache.get(provider.getContext());
        if (virtualMachines == null) {
            virtualMachines = new ArrayList<VirtualMachine>();
            for (VirtualMachine vm : provider.getComputeServices().getVirtualMachineSupport().listVirtualMachines()) {
                virtualMachines.add(vm);
            }
            cache.put(provider.getContext(), virtualMachines);
        }
        DefinitionModel definitionModel = getDefinition(forLoadBalancerId);
        ArrayList<LoadBalancerEndpointendpoints = new ArrayList<LoadBalancerEndpoint>();
        for (DefinitionModel.EndPointModel endPoint : definitionModel.getPolicy().getEndPoints())
        {
            LbEndpointState lbState = endPoint.getStatus().equalsIgnoreCase("enabled") ? . : .;
            ArrayList<VirtualMachinevmsWithEndpointDNS = findVMsForDNS(virtualMachinesendPoint.getDomainName());
            for(VirtualMachine vm : vmsWithEndpointDNS) {
                LoadBalancerEndpoint lbEndpoint = LoadBalancerEndpoint.getInstance(.vm.getProviderVirtualMachineId(), lbState);
                endpoints.add(lbEndpoint);
            }
        }
        return endpoints;
    }
    private ArrayList<VirtualMachinefindVMsForDNS(Iterable<VirtualMachinevirtualMachinesString dnsName)
    {
        ArrayList<VirtualMachinevirtualMachinesFound = new ArrayList<VirtualMachine>();
        for (VirtualMachine virtualMachine : virtualMachines)
        {
            if(virtualMachine.getPublicDnsAddress().equalsIgnoreCase(dnsName))
                virtualMachinesFound.add(virtualMachine);
        }
        return virtualMachinesFound;
    }
    @Override
    public void removeServers(@Nonnull String fromLoadBalancerId, @Nonnull String... serverIdsToRemovethrows CloudExceptionInternalException
    {
        DefinitionModel definitionModel = getDefinition(fromLoadBalancerId);
        for (String serverToRemoveId : serverIdsToRemove) {
            String[] parts = serverToRemoveId.split(":");
            for (DefinitionModel.EndPointModel endPoint : definitionModel.getPolicy().getEndPoints()) {
                if(endPoint.getDomainName().startsWith(parts[0] + ".")){
                    itemsToRemove.add(endPoint);
                }
            }
        }
        definitionModel.getPolicy().getEndPoints().removeAll(itemsToRemove);
        try {
            AzureMethod method = new AzureMethod(this.getProvider());
            method.post(String.format(fromLoadBalancerId), definitionModel);
        } catch (JAXBException e) {
            .error(e.getMessage());
            throw new InternalException(e);
        }
    }
    @Override
    {
        ProviderContext ctx = this.getProvider().getContext();
        ifctx == null ) {
            throw new AzureConfigException("No context was specified for this request");
        }
        ProfilesModel profilesModel = getProfiles();
        if(profilesModel == null)
            return Collections.emptyList();
        if(profilesModel.getProfiles() == null)
            return Collections.emptyList();
        ArrayList<LoadBalancerHealthCheckloadBalancerHealthChecks = new ArrayList<LoadBalancerHealthCheck>();
        for (ProfileModel profile : profilesModel.getProfiles())
        {
            DefinitionModel definitionModel = getDefinition(profile.getName());
            DefinitionModel.MonitorModel currentMonitor = definitionModel.getMonitors().get(0);
            LoadBalancerHealthCheck.HCProtocol protocol =
                    currentMonitor.getProtocol().equalsIgnoreCase("http") ? .. : ..;
            LoadBalancerHealthCheck loadBalancerHealthCheck =  LoadBalancerHealthCheck.getInstance(profile.getName(),
                                                                    protocol,
                                                                    Integer.parseInt(currentMonitor.getPort()),
                                                                    currentMonitor.getHttpOptions().getRelativePath(),
                                                                    Integer.parseInt(currentMonitor.getIntervalInSeconds()),
                                                                    Integer.parseInt(currentMonitor.getTimeoutInSeconds()),
                                                                    1,
                                                                    Integer.parseInt(currentMonitor.getToleratedNumberOfFailures()));
            loadBalancerHealthCheck.addProviderLoadBalancerId(profile.getName());
            if(opts == null || (opts.matches(loadBalancerHealthCheck)))
                loadBalancerHealthChecks.add(loadBalancerHealthCheck);
        }
        return loadBalancerHealthChecks;
    }
    @Override
    public LoadBalancerHealthCheck getLoadBalancerHealthCheck(@Nonnull String providerLBHealthCheckId, @Nullable String providerLoadBalancerId)throws CloudExceptionInternalException
    {
        if(providerLBHealthCheckId == null)
            throw new InternalException("Cannot retrieve Load Balancer Health Check when providerLBHealthCheckId is not provided");
        String profileId = providerLoadBalancerId != null ? providerLoadBalancerId : providerLBHealthCheckId;
        DefinitionModel definitionModel = getDefinition(profileId);
        DefinitionModel.MonitorModel currentMonitor = definitionModel.getMonitors().get(0);
        LoadBalancerHealthCheck.HCProtocol protocol =
                currentMonitor.getProtocol().equalsIgnoreCase("http") ? .. : ..;
        LoadBalancerHealthCheck loadBalancerHealthCheck =  LoadBalancerHealthCheck.getInstance(profileId,
                protocol,
                Integer.parseInt(currentMonitor.getPort()),
                currentMonitor.getHttpOptions().getRelativePath(),
                Integer.parseInt(currentMonitor.getIntervalInSeconds()),
                Integer.parseInt(currentMonitor.getTimeoutInSeconds()),
                1,
                Integer.parseInt(currentMonitor.getToleratedNumberOfFailures()));
        loadBalancerHealthCheck.addProviderLoadBalancerId(profileId);
        return loadBalancerHealthCheck;
    }
    @Override
    public LoadBalancerHealthCheck modifyHealthCheck(@Nonnull String providerLBHealthCheckId, @Nonnull HealthCheckOptions optionsthrows InternalExceptionCloudException
    {
        if(options == null)
            throw new InternalException("Cannot modify Health Check definition when HealthCheckOptions are not provided");
        String loadBalancerId = providerLBHealthCheckId;
        if(options.getProviderLoadBalancerId() != null)
            loadBalancerId = options.getProviderLoadBalancerId();
        if(loadBalancerId == null)
            throw new InternalException("Load balancer id not provided");
            throw new InternalException("Azure health check monitor supports only HTTP and HTTPS protocols");
        DefinitionModel.MonitorModel monitorModel = new DefinitionModel.MonitorModel();
        monitorModel.setProtocol(options.getProtocol().toString());
        monitorModel.setPort(String.valueOf(options.getPort()));
        monitorModel.setIntervalInSeconds("30");
        monitorModel.setTimeoutInSeconds("10");
        monitorModel.setToleratedNumberOfFailures("3");
        DefinitionModel.HttpOptionsModel httpOptions = new DefinitionModel.HttpOptionsModel();
        httpOptions.setVerb("GET");
        httpOptions.setRelativePath(options.getPath());
        httpOptions.setExpectedStatusCode("200");
        monitorModel.setHttpOptions(httpOptions);
        DefinitionModel definitionModel = getDefinition(loadBalancerId);
        definitionModel.getMonitors().set(0, monitorModel);
        try {
            AzureMethod method = new AzureMethod(this.getProvider());
            method.post(String.format(loadBalancerId), definitionModel);
        } catch (JAXBException e) {
            .error(e.getMessage());
            throw new InternalException(e);
        }
        return getLoadBalancerHealthCheck(loadBalancerIdnull);
    }
    private DefinitionModel getDefinition(String profileNamethrows CloudExceptionInternalException {
        AzureMethod method = new AzureMethod(this.getProvider());
        return method.get(DefinitionModel.class, String.format(profileName));
    }
    private ProfileModel getProfile(String profileNamethrows CloudExceptionInternalException {
        AzureMethod method = new AzureMethod(this.getProvider());
        return method.get(ProfileModel.class, String.format(profileName));
    }
        AzureMethod method = new AzureMethod(this.getProvider());
        return method.get(ProfilesModel.class);
    }
New to GrepCode? Check out our FAQ X