Softlayer

时间:2016-08-03 10:26:28

标签: ibm-cloud-infrastructure

我正在尝试使用Java Client创建一个缩放组。 如何设置NetworkComponent,Storage(San,local),LoadBalancer和Policy? 这是创建组对象的示例代码。我想确保这是一种正确的设置方式。请检查我对代码的评论。谢谢。

        Group.Service scaleGroupService = Group.service(client);

        Location location = new Location();
        location.setName("hkg02");

        Guest guest = new Guest();
        guest.setDomain("softlayer.com");
        guest.setHostname("hostnametest");
        guest.setMaxMemory(new Long(1024));
        guest.setPostInstallScriptUri("https://www.softlayer.com/script");
        guest.setStartCpus(new Long(1));
        guest.setDatacenter(location);
        guest.setHourlyBillingFlag(true);
        guest.setLocalDiskFlag(false); 
        guest.setOperatingSystemReferenceCode("CENTOS_LATEST");
// To set Network component     
//      guest.getNetworkComponents().get(0).setMaxSpeed(maxSpeed);
// To set Storage
//      guest.setBlockDeviceTemplateGroup(blockDeviceTemplateGroup);


        Group scaleGroup = new Group();
        scaleGroup.setCooldown(new Long(1800));
        scaleGroup.setMaximumMemberCount(new Long(5));
        scaleGroup.setMinimumMemberCount(new Long(1));
        scaleGroup.setName("testVSI");
        scaleGroup.setRegionalGroupId(new Long(102));
        scaleGroup.setSuspendedFlag(false);
        scaleGroup.setTerminationPolicyId(new Long(2));
        scaleGroup.setVirtualGuestMemberTemplate(guest);
        scaleGroup.setVirtualGuestMemberCount(new Long(0));
// To set Loadbalancer      
//      scaleGroup.getLoadBalancers().set(index, loadbalancer element)
// To set Policy
//      scaleGroup.getPolicies().set(index, policy element)

        Gson gson = new Gson();
        System.out.println(gson.toJson(scaleGroupService.createObject(scaleGroup))); 

1 个答案:

答案 0 :(得分:0)

这里有一个java脚本,用于创建 Scale Group ,定义 NetworkComponent 存储(San,local) LoadBalancer 政策

正如您在脚本中看到的那样:

  

virtualGuestMemberTemplate.setLocalDiskFlag(假);

它定义磁盘是LOCAL(true)还是SAN(false)。

我认为理解它是一件单调乏味的事情,但它的工作方式是有效的,我会尝试改进剧本。

package com.softlayer.api.ScaleGroup;

import com.softlayer.api.ApiClient;
import com.softlayer.api.RestApiClient;
import com.softlayer.api.service.Location;
import com.softlayer.api.service.network.application.delivery.controller.loadbalancer.health.Check;
import com.softlayer.api.service.network.application.delivery.controller.loadbalancer.health.check.Type;
import com.softlayer.api.service.scale.Group;
import com.softlayer.api.service.scale.LoadBalancer;
import com.softlayer.api.service.scale.Policy;
import com.softlayer.api.service.scale.network.Vlan;
import com.softlayer.api.service.scale.policy.action.Scale;
import com.softlayer.api.service.virtual.Guest;
import com.softlayer.api.service.virtual.disk.Image;
import com.softlayer.api.service.virtual.guest.block.Device;
import com.softlayer.api.service.virtual.guest.network.Component;
import java.util.ArrayList;
import java.util.List;

/**
 * This script creates a Scale Group with Load Balancer and Policy
 *
 * Important Manual Page:
 * http://sldn.softlayer.com/reference/services/SoftLayer_Scale_Group
 * http://sldn.softlayer.com/reference/services/SoftLayer_Scale_Group/createObject
 * http://sldn.softlayer.com/reference/services/SoftLayer_Scale_Group/getAvailableRegionalGroups
 * http://sldn.softlayer.com/reference/datatypes/SoftLayer_Scale_Group
 *
 * @license <http://sldn.softlayer.com/article/License>
 * @authon SoftLayer Technologies, Inc. <sldn@softlayer.com>
 * @version 0.2.2 (master branch)
 */
public class CreateObject {
    /**
     * This is the constructor, is used to create a scale group
     */
    public CreateObject() {
        // Declare your SoftLayer username and apiKey
        String username = "set me";
        String apiKey = "set me";

        // Create client
        ApiClient client = new RestApiClient().withCredentials(username, apiKey);
        Group.Service groupService = Group.service(client);

        // Define SoftLayer_Scale_Group object that you wish to create
        Group templateObject = new Group();
        templateObject.setCooldown(new Long(1800));
        templateObject.setMaximumMemberCount(new Long(5));
        templateObject.setMinimumMemberCount(new Long(1));
        templateObject.setName("TestRcv2");
        templateObject.setRegionalGroupId(new Long(463));
        templateObject.setTerminationPolicyId(new Long(2));
        templateObject.setSuspendedFlag(false);

        // Define SoftLayer_Virtual_Guest
        Guest virtualGuestMemberTemplate = new Guest();
        virtualGuestMemberTemplate.setHostname("rcvtest");
        virtualGuestMemberTemplate.setDomain("softlayer.com");
        virtualGuestMemberTemplate.setMaxMemory(new Long(1024));
        virtualGuestMemberTemplate.setStartCpus(new Long(1));

        // Define block devices, First Block Device
        Device firstBlock = new Device();
        firstBlock.setDevice("0");
        Image firstImage = new Image();
        firstImage.setCapacity(new Long(100));
        firstBlock.setDiskImage(firstImage);
        // Second Block Device
        Device secondBlock = new Device();
        secondBlock.setDevice("2");
        Image secondImage = new Image();
        secondImage.setCapacity(new Long(400));
        secondBlock.setDiskImage(secondImage);
        // Third Block Device
        Device thirdBlock = new Device();
        thirdBlock.setDevice("3");
        Image thirdImage = new Image();
        thirdImage.setCapacity(new Long(750));
        thirdBlock.setDiskImage(thirdImage);
        // Adding Block Devices to the template
        virtualGuestMemberTemplate.getBlockDevices().add(firstBlock);
        virtualGuestMemberTemplate.getBlockDevices().add(secondBlock);
        virtualGuestMemberTemplate.getBlockDevices().add(thirdBlock);
        // Define Location
        Location location = new Location();
        location.setName("hou02");
        virtualGuestMemberTemplate.setDatacenter(location);
        // Define Hourly billing and local disk
        virtualGuestMemberTemplate.setHourlyBillingFlag(true);
        virtualGuestMemberTemplate.setLocalDiskFlag(false);
        // Define Network Components
        Component networkComponent = new Component();
        networkComponent.setMaxSpeed(new Long(10));
        virtualGuestMemberTemplate.getNetworkComponents().add(networkComponent);
        // Define OS
        virtualGuestMemberTemplate.setOperatingSystemReferenceCode("WIN_2012-STD-R2_64");
        virtualGuestMemberTemplate.setPrivateNetworkOnlyFlag(false);

        // Define Vlans
        Vlan firstVlan = new Vlan();
        firstVlan.setNetworkVlanId(new Long(1072495));
        Vlan secondVlan = new Vlan();
        secondVlan.setNetworkVlanId(new Long(1072493));
        List<Vlan> networkVlans = new ArrayList<Vlan>();
        networkVlans.add(firstVlan);
        networkVlans.add(secondVlan);
        // Adding Vlans to the template
        templateObject.getNetworkVlans().addAll(networkVlans);
        // Adding Virtual Guest member template to the template
        templateObject.setVirtualGuestMemberTemplate(virtualGuestMemberTemplate);

        // Load Balancer
        LoadBalancer loadBalancer = new LoadBalancer();
        loadBalancer.setDeleteFlag(false);
        loadBalancer.setPort(new Long(80));
        // Set Server Id
        loadBalancer.setVirtualServerId(new Long(222155));
        // Define TYpe
        Type type = new Type();
        type.setKeyname("HTTP");
        Check healthCheck = new Check();
        healthCheck.setType(type);
        loadBalancer.setHealthCheck(healthCheck);
        // Adding Load Balancer to the template
        templateObject.getLoadBalancers().add(loadBalancer);

        // Define Policy
        Policy policy = new Policy();
        policy.setCooldown(new Long(1800));
        policy.setName("newPolicyName");
        // Define Action for the policy
        Scale scaleActions = new Scale();
        scaleActions.setScaleType("RELATIVE");
        scaleActions.setAmount(new Long(4));
        policy.getScaleActions().add(scaleActions);
        // Add Policy to the template
        templateObject.getPolicies().add(policy);

        try {
            Group result = groupService.createObject(templateObject);
            System.out.println(result);
        } catch (Exception e) {
            System.out.println("Error: " + e);
        }
    }

    /**
     * This is the main method which makes use of CreateObject method.
     *
     * @param args
     * @return Nothing
     */
    public static void main(String[] args) {
        new CreateObject();
    }

}

请告诉我,对此有任何疑问或评论。

这是另一个脚本:

package com.softlayer.api.ScaleGroup;

import com.google.gson.Gson;
import com.softlayer.api.ApiClient;
import com.softlayer.api.RestApiClient;
import com.softlayer.api.service.Account;
import com.softlayer.api.service.Location;
import com.softlayer.api.service.network.application.delivery.controller.loadbalancer.VirtualIpAddress;
import com.softlayer.api.service.network.application.delivery.controller.loadbalancer.VirtualServer;
import com.softlayer.api.service.network.application.delivery.controller.loadbalancer.health.Check;
import com.softlayer.api.service.network.application.delivery.controller.loadbalancer.health.check.Type;
import com.softlayer.api.service.provisioning.Hook;
import com.softlayer.api.service.scale.Group;
import com.softlayer.api.service.scale.LoadBalancer;
import com.softlayer.api.service.scale.Policy;
import com.softlayer.api.service.scale.network.Vlan;
import com.softlayer.api.service.scale.policy.action.Scale;
import com.softlayer.api.service.security.ssh.Key;
import com.softlayer.api.service.virtual.Guest;
import com.softlayer.api.service.virtual.disk.Image;
import com.softlayer.api.service.virtual.guest.block.Device;
import com.softlayer.api.service.virtual.guest.network.Component;

/**
 * This script creates a Scale Group with Load Balancer and Policy
 *
 * Important Manual Page:
 * http://sldn.softlayer.com/reference/services/SoftLayer_Scale_Group
 * http://sldn.softlayer.com/reference/services/SoftLayer_Scale_Group/createObject
 * http://sldn.softlayer.com/reference/services/SoftLayer_Scale_Group/getAvailableRegionalGroups
 * http://sldn.softlayer.com/reference/datatypes/SoftLayer_Scale_Group
 *
 * @license <http://sldn.softlayer.com/article/License>
 * @authon SoftLayer Technologies, Inc. <sldn@softlayer.com>
 * @version 0.2.2 (master branch)
 */
public class CreateObject {
    /**
     * This is the constructor, is used to create a scale group
     */
    public CreateObject() {
        // Declare your SoftLayer username and apiKey
        String username = "set me";
        String apiKey = "set me";

        // Create client and services
        ApiClient client = new RestApiClient().withCredentials(username, apiKey);
        Group.Service groupService = Group.service(client);
        com.softlayer.api.service.scale.termination.Policy.Service terminationPolicyService = com.softlayer.api.service.scale.termination.Policy.service(client);
        Account.Service accountService = Account.service(client);
        VirtualIpAddress.Service virtualIpAddressService = VirtualIpAddress.service(client);

        /**
         * Group Configuration
         * Group Details
         */
        String groupName = "RuberCuellartest3";
        String region = "na-usa-south-1";
        String datacenter = "hou02";
        String terminationPolicy = "Newest";

        /**
         * Network
         * Vlans
         */
        Long[] networkVlans = {new Long(1244), new Long(1318)};

        /**
         * Group Settings
         */
        Long minimumMemberCount = new Long(1);
        Long maximumMemberCount = new Long(5);
        Long cooldown = new Long(1800);

        /**
         * Member Configuration
         * Member Details
         */
        String hostname = "rcvtest";
        String domain = "softlayer.com";

        /**
         * Computing Instance
         */
        Long cores = new Long(1);
        Long ram = new Long(8);
        Long speed = new Long(100);
        String[] sshKeys = {"tonny", "Rahul"};

        /**
         * Operating System
         */
        String operatingSystem = "WIN_2012-STD-R2_64";

        /**
         * Storage
         * diskType options "SAN" and "LOCAL"
         */
        //String diskType = "SAN";
        //Long[] sizes = {new Long(100), new Long(200), new Long(400)};
        String diskType = "SAN";
        Long[] sizes = {new Long(100), new Long(100)};


        /**
         * Post-Install Script
         * Fill with the post provision script name or fill with the url script that you wish to set
         */
        String namePostInstall = "Neo4j";

        /**
         * Local Load Balancer
         */
        String virtualIp = "173.193.117.96";
        String serviceGroup = "DNS";
        Long serviceGroupPort = new Long(53);
        Long port = new Long(100);
        String serviceHealthCheckType = "HTTP";

        /**
         * Policies
         * Policy Name
         */
        String policyName = "PolicyNameRuber";
        Long policyCooldown = new Long(1800);
        /**
         * Action Options:
         * 1. Scale group to quantity (absolute) = ABSOLUTE
         * 2. Scale group by percentage = PERCENT
         * 3. Scale group by quantity = RELATIVE
         */
        String action = "PERCENT";
        Long amountAction = new Long(100);


        /**
         * Define SoftLayer_Scale_Group object that you wish to create
         */
        Group templateObject = new Group();
        templateObject.setName(groupName);
        templateObject.setRegionalGroupId(getRegionalGroupId(groupService, region));
        templateObject.setTerminationPolicyId(getTerminationPolicy(terminationPolicyService, terminationPolicy));
        templateObject.setCooldown(cooldown);
        templateObject.setMaximumMemberCount(maximumMemberCount);
        templateObject.setMinimumMemberCount(minimumMemberCount);

        templateObject.setSuspendedFlag(false);

        // Define SoftLayer_Virtual_Guest
        Guest virtualGuestMemberTemplate = new Guest();
        virtualGuestMemberTemplate.setHostname(hostname);
        virtualGuestMemberTemplate.setDomain(domain);
        virtualGuestMemberTemplate.setMaxMemory(ram);
        virtualGuestMemberTemplate.setStartCpus(cores);


        String[] devices = {"0", "2", "3", "4", "5", "6"};
        for(int i = 0; i<sizes.length ; i++){
            Device firstBlock = new Device();
            firstBlock.setDevice(devices[i]);
            Image firstImage = new Image();
            firstImage.setCapacity(sizes[i]);
            firstBlock.setDiskImage(firstImage);
            virtualGuestMemberTemplate.getBlockDevices().add(firstBlock);
        }

        // Define Location
        Location location = new Location();
        location.setName(datacenter);
        virtualGuestMemberTemplate.setDatacenter(location);

        // Define Hourly billing and local disk
        virtualGuestMemberTemplate.setHourlyBillingFlag(true);
        if(diskType.equals("LOCAL"))
        {
            virtualGuestMemberTemplate.setLocalDiskFlag(true);
        }else{virtualGuestMemberTemplate.setLocalDiskFlag(false);}

        // Network Components
        Component networkComponent = new Component();
        networkComponent.setMaxSpeed(speed);
        virtualGuestMemberTemplate.getNetworkComponents().add(networkComponent);
        // OS
        virtualGuestMemberTemplate.setOperatingSystemReferenceCode(operatingSystem);
        virtualGuestMemberTemplate.setPrivateNetworkOnlyFlag(false);
        // Ssh key
        for(int i = 0; i<sshKeys.length; i++)
        {
            Key newKey = new Key();
            newKey.setId(getSshKeys(accountService, sshKeys[i]));
            virtualGuestMemberTemplate.getSshKeys().add(newKey);
        }

        // Provision Script
        if(namePostInstall != "")
        {
            virtualGuestMemberTemplate.setPostInstallScriptUri(getPostInstallScript(accountService, namePostInstall));
        }

        // Network Vlans
        for(int i = 0; i<networkVlans.length; i++)
        {
            Vlan vlan = new Vlan();
            vlan.setNetworkVlanId(getVlanId(accountService, networkVlans[i]));
            templateObject.getNetworkVlans().add(vlan);

        }

        // Adding Virtual Guest member template to the template
        templateObject.setVirtualGuestMemberTemplate(virtualGuestMemberTemplate);

        // Load Balancer
        LoadBalancer loadBalancer = new LoadBalancer();
        loadBalancer.setDeleteFlag(false);
        loadBalancer.setPort(port);
        // Set Server Id
        loadBalancer.setVirtualServerId(getVirtualServerId(accountService, serviceGroupPort, virtualIp));


        // Define Type
        Type type = new Type();
        type.setKeyname(serviceHealthCheckType);
        Check healthCheck = new Check();
        healthCheck.setType(type);
        loadBalancer.setHealthCheck(healthCheck);
        // Adding Load Balancer to the template
        templateObject.getLoadBalancers().add(loadBalancer);

        // Define Policy
        Policy policy = new Policy();
        policy.setCooldown(policyCooldown);
        policy.setName(policyName);
        // Define Action for the policy
        Scale scaleActions = new Scale();
        scaleActions.setScaleType(action);
        scaleActions.setAmount(amountAction);
        policy.getScaleActions().add(scaleActions);
        // Add Policy to the template
        templateObject.getPolicies().add(policy);

        Gson gson = new Gson();
        System.out.println(gson.toJson(templateObject));

        try {
            Group result = groupService.createObject(templateObject);
            System.out.println(result);
        } catch (Exception e) {
            System.out.println("Error: " + e);
        }
    }


    /**
     * Retrieves rion identifier
     * @param region string
     * @return region identifier
     */
    public Long getRegionalGroupId(Group.Service groupService, String region)
    {
        Long regionId = new Long(0);
        for(com.softlayer.api.service.location.Group regionalGroup : groupService.getAvailableRegionalGroups())
        {
            if(regionalGroup.getName().equals(region))
            {
                regionId = regionalGroup.getId();
            }
        }
        return regionId;
    }

    /**
     * Returns policy termination identifier
     * @param policyService
     * @param name
     * @return Policy termination identifier
     */
    public Long getTerminationPolicy(com.softlayer.api.service.scale.termination.Policy.Service policyService, String name)
    {
        Long id = new Long(0);
        for(com.softlayer.api.service.scale.termination.Policy policy : policyService.getAllObjects())
        {
            if(policy.getName().equals(name))
            {
                id = policy.getId();
            }
        }
        return id;
    }

    /**
     * Retrieves a network vlan identifier
     * @param accountService Account Service
     * @param vlanNumber The number of vlan
     * @return Vlan's identifier
     */
    public Long getVlanId(Account.Service accountService, Long vlanNumber)
    {
        Long vlanId = new Long(0);
        for(com.softlayer.api.service.network.Vlan vlan : accountService.getNetworkVlans())
        {
            if(vlan.getVlanNumber().equals(vlanNumber))
            {
                vlanId = vlan.getId();
            }
        }
        return vlanId;
    }


    public Long getVirtualServerId(Account.Service accountService, Long serviceGroupPort, String ipAddress)
    {
        Long serverId = new Long(0);

        accountService.withMask().adcLoadBalancers().ipAddress().ipAddress();
        accountService.withMask().adcLoadBalancers().virtualServers();

        for(VirtualIpAddress virtualIpAddress : accountService.getObject().getAdcLoadBalancers())
        {
            if(virtualIpAddress.getIpAddress().getIpAddress().equals(ipAddress))
            {
                for(VirtualServer virtualServer : virtualIpAddress.getVirtualServers())
                {
                    if(virtualServer.getPort().equals(serviceGroupPort))
                    {
                        serverId = virtualServer.getId();
                    }
                }
            }
        }
        return serverId;
    }

    /**
     * Retrieves ssh key's identifier
     * @param accountService Account Service
     * @param name Label's name from ssh key
     * @return The Ssh Key's identifier
     */
    public Long getSshKeys(Account.Service accountService, String name)
    {
        Long id = new Long(0);
        for(Key key : accountService.getSshKeys())
        {
            if(key.getLabel().equals(name))
            {
                id = key.getId();
            }
        }
        return id;

    }

    /**
     * Retrieves Post Provision URI
     * @param accountService Account Service
     * @param postInstallName The name from post install script
     * @return The Provision script URI
     */
    public String getPostInstallScript(Account.Service accountService, String postInstallName)
    {
        String script = "";
        for(Hook hook : accountService.getPostProvisioningHooks())
        {
            if(hook.getName().equals(postInstallName))
            {
                script = hook.getUri();
                return script;
            }
        }
        return postInstallName;
    }

    /**
     * This is the main method which makes use of CreateObject method.
     *
     * @param args
     * @return Nothing
     */
    public static void main(String[] args) {
        new CreateObject();
    }

}