Google Cloud Platform запускает несколько экземпляров с InstanceGroupManager - PullRequest
0 голосов
/ 26 июня 2019

Я пытаюсь запустить несколько экземпляров с Google Cloud Platform с InstanceGroupManager через Java API. Следующий порядок:

  1. Создание шаблона экземпляра
  2. Создание менеджера группы экземпляров с данным шаблоном экземпляра

Насколько я понимаю, если мне нужно создать несколько экземпляров, мне нужно создать эквивалентное количество дисков, где каждый из них будет назначен каждому созданному экземпляру. Проблема в том, что я создаю эквивалентное количество дисков, а затем создаю InstanceTemplate с ними. Однако когда я создаю экземпляры с InstanceGroupManager, второй экземпляр всегда завершается ошибкой из-за The disk resource XXX is already being used by instance-ABC. Итак, что я вижу, если создаю два диска (один - загрузочный диск, а другой - нет), два диска присоединяются к первому экземпляру, так что второй экземпляр не получает никаких дисков.

Я попытался упростить Java-код, который я здесь запускаю. Вы можете видеть, как я создаю InstanceTemplate, InstanceGroupManager и выполняю его.

    private void launchInstances(String instanceData, int instanceCount) GeneralSecurityException, IOException {
        Compute gcpClient = createGCPClient();
        String image = "projects/ubuntu-os-cloud/global/images/family/ubuntu-1804-lts";
        String securityGroup = "global/networks/default";
        String instanceType = "n1-highcpu-4";

        // create instance template
        InstanceTemplate instanceTemplate = new InstanceTemplate();
        String templateUUID = UUID.randomUUID().toString();
        instanceTemplate.setName("test-template-" + templateUUID);
        instanceTemplate.setProperties(buildInstanceProperties(instanceData, cloudRegionEntity, count));
        Operation createIntanceTemplateOp = gcpClient.instanceTemplates().insert("test-project", instanceTemplate).execute();

        // create instance group manager
        InstanceGroupManager instanceGroupManager = new InstanceGroupManager();
        InstanceGroupManagerVersion version = new InstanceGroupManagerVersion();
        version.setInstanceTemplate("global/instanceTemplates/" + instanceTemplate.getName());
        instanceGroupManager.setVersions(Collections.singletonList(version));
        instanceGroupManager.setTargetSize(count);
        instanceGroupManager.setName("intance-group-manager" + templateUUID);

        String zone = "us-west2-a"
        Operation launchInsGrOp = zone; gcpClient.instanceGroupManagers().insert("test-project", zone, instanceGroupManager).execute();
        launchInsGrOp = gcpClient.zoneOperations().get("test-project", zone, operation.getName()).execute();

    }

    private InstanceProperties buildInstanceProperties(String instanceData, String image, int instanceCount) {
        InstanceProperties instanceProperties = new InstanceProperties();

        // set disk properties
        instanceProperties.setDisks(buildAttachedDisk(image, instanceCount));

        // set metadata properties
        Metadata metadata = new Metadata();
        Metadata.Items item = new Metadata.Items();
        item.setKey("startup-script");
        item.setValue(instanceData);
        metadata.setItems(Collections.singletonList(item));
        instanceProperties.setMetadata(metadata);

        // set machine-type property
        instanceProperties.setMachineType("n1-highcpu-4");

        // set network-interface property
        instanceProperties.setNetworkInterfaces(Collections.singletonList(buildNetworkInterface("global/networks/default")));

        // build service account property
        instanceProperties.setServiceAccounts(Collections.singletonList(buildServiceAccount()));
        return instanceProperties;
    }

    private List<AttachedDisk> buildAttachedDisk(String machineType, int count) {
        List<AttachedDisk> attachedDisks = new ArrayList<>();
        for (int ind = 0; ind < count; ind++) {
            // Add attached Persistent Disk to be used by VM Instance.
            AttachedDisk attachedDisk = new AttachedDisk();
            attachedDisk.setAutoDelete(true);
            if (ind == 0) {
                attachedDisk.setBoot(true);
            } else {
                attachedDisk.setBoot(false);
            }
            attachedDisk.setType("PERSISTENT");
            AttachedDiskInitializeParams params = new AttachedDiskInitializeParams();
            params.setDiskName("test-disk-" + UUID.randomUUID().toString());

            // Specify the source operating system machine image to be used by the VM Instance.
            params.setSourceImage(machineType);
            attachedDisk.setInitializeParams(params);

            attachedDisks.add(attachedDisk);
        }

        return attachedDisks;
    }

1 Ответ

1 голос
/ 27 июня 2019

Я решил это, используя региональные группы экземпляров . В основном, использование gcpClient.regionInstanceGroupManagers().insert("test-project", "us-west2", instanceGroupManager).execute(); решило проблему.

...