private static async Task <Image> getImage(ComputeClient computeClient, string compartmentId, Shape shape)
        {
            ListImagesRequest listImagesRequest = new ListImagesRequest
            {
                Shape           = shape.ShapeProp,
                CompartmentId   = compartmentId,
                OperatingSystem = OPERATING_SYSTEM
            };
            ListImagesResponse response = await computeClient.ListImages(listImagesRequest);

            List <Image> images = response.Items;

            if (images.Count == 0)
            {
                logger.Error("No available image was found.");
            }

            // For demonstration, we just return the first image but for Production code you should have a better
            // way of determining what is needed.
            //
            // Note the latest version of the images for the same operating system is returned firstly.
            Image image = images[0];

            logger.Info($"Found Image: {image.DisplayName}");
            return(image);
        }
 protected override void ProcessRecord()
 {
     base.ProcessRecord();
     try
     {
         client?.Dispose();
         int timeout = GetPreferredTimeout();
         WriteDebug($"Cmdlet Timeout : {timeout} milliseconds.");
         client = new ComputeClient(AuthProvider, new Oci.Common.ClientConfiguration
         {
             RetryConfiguration = retryConfig,
             TimeoutMillis      = timeout,
             ClientUserAgent    = PSUserAgent
         });
         string region = GetPreferredRegion();
         if (region != null)
         {
             WriteDebug("Choosing Region:" + region);
             client.SetRegion(region);
         }
         if (Endpoint != null)
         {
             WriteDebug("Choosing Endpoint:" + Endpoint);
             client.SetEndpoint(Endpoint);
         }
     }
     catch (Exception ex)
     {
         TerminatingErrorDuringExecution(ex);
     }
 }
示例#3
0
        static void Main(string[] args)
        {
            //InstanceContext instanceContext = new InstanceContext(new CallbackImpl());
            //DuplexChannelFactory<ICompute> channelFactory =
            //    new DuplexChannelFactory<ICompute>(instanceContext, "Compute_Endpoint");
            //var proxy = channelFactory.CreateChannel();
            //using ( proxy as IDisposable)
            //{

            //    proxy.Add(2, 1);
            //}

            InstanceContext instanceContext = new InstanceContext(new CallbackImpl());

            using (var proxy = new ComputeClient(instanceContext))
            {
                proxy.Add(2, 1);
                //proxy.Add(1.0,2.0);//通信关闭
            }
            using (var proxy = new ComputeClient(instanceContext))
            {
                proxy.Add(1.0, 2.0);
            }


            Console.ReadKey();
        }
示例#4
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string username = null;
            string password = null;
            string url      = null;

            if (!DA.GetData(0, ref username))
            {
                return;
            }
            if (!DA.GetData(1, ref password))
            {
                return;
            }
            if (!DA.GetData(2, ref url))
            {
                return;
            }

            var client = new ComputeClient(url);
            var tokens = client.Auth(username, password);
            var output = new Inputs
            {
                Auth = tokens,
                Url  = url
            };

            DA.SetData(0, output.ToJson());
        }
示例#5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="IgniteClient"/> class.
        /// </summary>
        /// <param name="clientConfiguration">The client configuration.</param>
        public IgniteClient(IgniteClientConfiguration clientConfiguration)
        {
            Debug.Assert(clientConfiguration != null);

            _configuration = new IgniteClientConfiguration(clientConfiguration);

            _marsh = new Marshaller(_configuration.BinaryConfiguration)
            {
                Ignite = this
            };

            _transactions = new TransactionsClient(this, clientConfiguration.TransactionConfiguration);

            _socket = new ClientFailoverSocket(_configuration, _marsh, _transactions);

            _binProc = _configuration.BinaryProcessor ?? new BinaryProcessorClient(_socket);

            _binary = new Impl.Binary.Binary(_marsh);

            _cluster = new ClientCluster(this);

            _compute = new ComputeClient(this, ComputeClientFlags.None, TimeSpan.Zero, null);

            _services = new ServicesClient(this);
        }
        private static async Task printInstance(ComputeClient computeClient, VirtualNetworkClient virtualNetworkClient, Instance instance)
        {
            ListVnicAttachmentsRequest listVnicAttachmentsRequest = new ListVnicAttachmentsRequest
            {
                CompartmentId = instance.CompartmentId,
                InstanceId    = instance.Id
            };
            ListVnicAttachmentsResponse listVnicAttachmentsResponse = await computeClient.ListVnicAttachments(listVnicAttachmentsRequest);

            List <VnicAttachment> vnicAttachments = listVnicAttachmentsResponse.Items;
            VnicAttachment        vnicAttachment  = vnicAttachments[0];

            GetVnicRequest getVnicRequest = new GetVnicRequest
            {
                VnicId = vnicAttachment.VnicId
            };
            GetVnicResponse getVnicResponse = await virtualNetworkClient.GetVnic(getVnicRequest);

            Vnic vnic = getVnicResponse.Vnic;

            logger.Info($"Virtual Network Interface Card: {vnic.Id}");

            InstanceAgentConfig instanceAgentConfig = instance.AgentConfig;
            bool   monitoringEnabled = instanceAgentConfig.IsMonitoringDisabled.HasValue ? instanceAgentConfig.IsMonitoringDisabled.Value : false;
            string monitoringStatus  = (monitoringEnabled ? "Enabled" : "Disabled");

            logger.Info($"Instance ID: {instance.Id} has monitoring {monitoringStatus}");
        }
示例#7
0
        public void UpdateVM_DoNotSerializeProtected()
        {
            string         guidString        = "f978ade9"; //We need to be under 24 char for storage, so making it shorter for almost all names
            string         resourceGroupName = string.Format("{0}-{1}-{2}", prefix, resourcePrefix, guidString);
            string         storageName       = string.Format("{0}{1}{2}", prefix, storagePrefix, guidString);
            string         vmName            = string.Format("{0}-{1}-{2}", prefix, vmPrefix, guidString);
            VirtualMachine vm1;
            ResourceGroup  resGroup = null;

            //string executingAssemblyPath = typeof(Microsoft.Rest.ClientRuntime.E2E.Tests.ScenarioTests.VMTests).GetTypeInfo().Assembly.Location;
            //HttpMockServer.RecordsDirectory = Path.Combine(Path.GetDirectoryName(executingAssemblyPath), "SessionRecords");

            using (base.MockContext = MockContext.Start(this.GetType().FullName))
            {
                try
                {
                    //Type.GetType("System.Int32").GetTypeInfo().Assembly.Location
                    string newVmId = "5C6F1669-C183-4BFC-9BBB-138E0892E917";
                    string asName  = "as5913";
                    resGroup = CreateResourceGroup(resourceGroupName);
                    StorageAccount storageAccount = CreateStorageAccount(resGroup, storageName);
                    ImageReference imageRef       = GetPlatformVMImage(useWindowsImage: true);
                    VirtualMachine vm             = CreateVirtualMachine(resGroup.Name, vmName, asName, storageAccount.Name, imageRef, out vm1);

                    //Create a new VM and Update VmId protected Property
                    MyVm myNewVm = new MyVm(vm);
                    myNewVm.UpdateVm(newVmId);
                    VirtualMachine updatedVm = myNewVm as VirtualMachine;

                    // Update VM
                    AzureOperationResponse <VirtualMachine> putResponse = Task <AzureOperationResponse <VirtualMachine> > .Run(async() =>
                    {
                        return(await ComputeClient.VirtualMachines.BeginCreateOrUpdateWithHttpMessagesAsync(resGroup.Name, updatedVm.Name, updatedVm).ConfigureAwait(false));
                    }).GetAwaiter().GetResult();

                    //Get Request Content and verify it does not contain VmId property
                    string requestContentStr = ComputeClient.GetRequestContent();
                    Assert.False(requestContentStr.Contains("VmId"));

                    //Get VM Object
                    VirtualMachine getVm = putResponse.Body;

                    // Verify the vmPutResponse does not contain updated VmId
                    Assert.NotEqual(newVmId, getVm.VmId);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                    throw;
                }
                finally
                {
                    ResourceClient.ResourceGroups.Delete(resGroup.Name);
                }
            }
        }
示例#8
0
        public void ComputeClient_GetToken()
        {
            var tokens = client.Auth(user.username, user.password);

            Console.WriteLine($"Got access token: {tokens.Access}");

            Console.Write($"Decoded token: {ComputeClient.DecodeTokenToJson(tokens.Access)}");

            Assert.IsNotNull(tokens.Access, "_value should be true");
        }
        private static async Task <Shape> getShape(ComputeClient client, string compartmentId, AvailabilityDomain availabilityDomain)
        {
            ListShapesRequest listShapesRequest = new ListShapesRequest
            {
                CompartmentId      = compartmentId,
                AvailabilityDomain = availabilityDomain.Name
            };
            ListShapesResponse listShapesResponse = await client.ListShapes(listShapesRequest);

            Shape shape = listShapesResponse.Items.Find(x => x.ShapeProp.StartsWith("VM"));

            return(shape);
        }
示例#10
0
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            var identityClient = new CloudIdentityClient("https://identity.api.rackspacecloud.com");
            var tokenResponse  = await identityClient.Authenticate();

            var computeEndpoint = tokenResponse.GetEndpoint("cloudServersOpenStack", "IAD");
            var computeClient   = new ComputeClient(computeEndpoint.PublicUrl, tokenResponse.Token.Id);
            var servers         = await computeClient.ListServersAsync();

            var flavors = await computeClient.ListFlavorsDetailedAsync();

            Console.WriteLine("Hello World!");
        }
        private static async Task terminateInstance(ComputeClient computeClient, Instance instance)
        {
            logger.Info($"Terminating Instance: {instance.Id}");
            TerminateInstanceRequest terminateInstanceRequest = new TerminateInstanceRequest {
                InstanceId = instance.Id
            };
            await computeClient.TerminateInstance(terminateInstanceRequest);

            WaiterConfiguration waiterConfiguration = new WaiterConfiguration
            {
                MaxAttempts           = 20,
                GetNextDelayInSeconds = DelayStrategy.GetExponentialDelayInSeconds
            };
            GetInstanceRequest getInstanceRequest = new GetInstanceRequest {
                InstanceId = instance.Id
            };

            computeClient.Waiters.ForInstance(getInstanceRequest, waiterConfiguration, Instance.LifecycleStateEnum.Terminated).Execute();

            logger.Info($"Terminated Instance: {instance.Id}");
        }
示例#12
0
        public void SetUp()
        {
            client = new ComputeClient(user.host);

            // Get the JWT access tokens as usual
            var tokens = client.Auth(user.username, user.password);

            Console.WriteLine($"Got access token: {tokens.Access}");

            // Core input string (from previous/upstream component(s))
            core_input = new Inputs {
                Auth = tokens,
                Url  = user.host
            }.ToJson();

            // Input parameters (these will be input into the component)
            project_name   = "Project Test";
            project_number = 1;
            task_name      = "Test Task";
            create         = false;
        }
        private static async Task <Instance> createInstance(ComputeClient computeClient, LaunchInstanceDetails launchInstanceDetails)
        {
            logger.Info("Launching an instance.....");
            LaunchInstanceRequest launchInstanceRequest = new LaunchInstanceRequest {
                LaunchInstanceDetails = launchInstanceDetails
            };
            LaunchInstanceResponse launchInstanceResponse = await computeClient.LaunchInstance(launchInstanceRequest);

            GetInstanceRequest getInstanceRequest = new GetInstanceRequest {
                InstanceId = launchInstanceResponse.Instance.Id
            };
            WaiterConfiguration waiterConfiguration = new WaiterConfiguration
            {
                MaxAttempts           = 20,
                GetNextDelayInSeconds = DelayStrategy.GetExponentialDelayInSeconds
            };
            GetInstanceResponse getInstanceResponse = computeClient.Waiters.ForInstance(getInstanceRequest, waiterConfiguration, Instance.LifecycleStateEnum.Running).Execute();

            Instance instance = getInstanceResponse.Instance;

            return(instance);
        }
示例#14
0
        public void SetUp()
        {
            client = new ComputeClient(user.host);

            // Get the JWT access tokens as usual
            var tokens = client.Auth(user.username, user.password);

            Console.WriteLine($"Got access token: {tokens.Access}");

            // Core input string (from previous/upstream component(s))
            core_input = new Inputs {
                Auth        = tokens,
                Url         = user.host,
                Project     = project,
                Task        = task,
                Mesh        = mesh,
                CFDSolution = solution
            }.ToJson();

            // Input parameters (these will be input into the component)
            compute = false;
        }
示例#15
0
        public static void MonitoringResourceExample(ClientConfig config)
        {
            // create client
            var identityClient = new IdentityClient(config);

            var computeClient = new ComputeClient(config);

            var monitoringClient = new MonitoringClient(config);

            var listCompartmenRequest = new ListCompartmentRequest()
            {
                CompartmentId          = identityClient.Config.TenancyId,
                CompartmentIdInSubtree = true,
                AccessLevel            = ListCompartmentRequest.AccessLevels.ACCESSIBLE,
                Limit = 10
            };
            // get compartment
            var listCompartment = identityClient.ListCompartment(listCompartmenRequest).Items;

            Console.WriteLine("* List Instance Metrics------------------------");
            foreach (var compartment in listCompartment)
            {
                if (!compartment.IsAccessible.HasValue || !compartment.IsAccessible.Value)
                {
                    continue;
                }
                var listInstanceRequest = new ListInstancesRequest()
                {
                    CompartmentId  = compartment.Id,
                    Limit          = 50,
                    LifecycleState = ListInstancesRequest.LifecycleStates.RUNNING,
                    SortOrder      = SortOrder.ASC
                };

                var now     = DateTime.UtcNow.AddHours(-2);
                var endTime = DateTime.UtcNow;
                // get instance
                var listInstance = computeClient.ListInstances(listInstanceRequest).Items;
                foreach (var instance in listInstance)
                {
                    Console.WriteLine($" |-{instance.DisplayName}------------");

                    // get all computeagent
                    var listMetricsRequest = new ListMetricsRequest()
                    {
                        CompartmentId          = compartment.Id,
                        CompartmentIdInSubtree = compartment.CompartmentId == config.TenancyId,
                        ListMetricsDetails     = new ListMetricsDetails()
                        {
                            Namespace        = "oci_computeagent",
                            DimensionFilters = new DimensionFilter()
                            {
                                ResourceId = instance.Id
                            }
                        }
                    };
                    // get Metrics
                    try
                    {
                        var listMetrics = monitoringClient.ListMetrics(listMetricsRequest).Items;
                        foreach (var metrics in listMetrics)
                        {
                            Console.WriteLine($"\t| Mertics: {metrics.Name}");
                            Console.WriteLine($"\t| NameSpace: {metrics.Namespace}");
                            // metric dimensions
                            //Console.WriteLine($"\t| {metrics.Dimensions}".Replace("\n", ""));

                            var summarizeMetricsDataRequest = new SummarizeMetricsDataRequest()
                            {
                                CompartmentId               = compartment.Id,
                                CompartmentIdInSubtree      = compartment.CompartmentId == config.TenancyId,
                                SummarizeMetricsDataDetails = new SummarizeMetricsDataDetails()
                                {
                                    Namespace = metrics.Namespace,
                                    Query     = metrics.Name + "[1h]{resourceId = \"" + instance.Id + "\"}.mean()",
                                    StartTime = now.ToString("yyyy-MM-ddThh:MM:ssZ"),
                                    EndTime   = endTime.ToString("yyyy-MM-ddThh:MM:ssZ")
                                }
                            };

                            var SummarizeMetricsDatas = monitoringClient.SummarizeMetricsData(summarizeMetricsDataRequest).Items;
                            foreach (var summaryData in SummarizeMetricsDatas)
                            {
                                foreach (var aggregatedDatapoint in summaryData.AggregatedDatapoints)
                                {
                                    Console.WriteLine("\t| {");
                                    Console.WriteLine($"\t| \tTimeStamp: {aggregatedDatapoint.Timestamp}");
                                    Console.WriteLine($"\t| \tValue: {aggregatedDatapoint.Value}");
                                    Console.WriteLine("\t| }");
                                }
                            }
                        }
                    }
                    catch (WebException we)
                    {
                        Console.WriteLine($"notfund:{we.Message}");
                    }
                }
            }
            Console.WriteLine("* List compartment Alarms------------------------");
            foreach (var compartment in listCompartment)
            {
                Console.WriteLine("  Alarm status------------------------");
                var listAlarmsStatusRequest = new ListAlarmsStatusRequest()
                {
                    CompartmentId = compartment.Id,
                    Limit         = 1000
                };
                var alarmStatus = monitoringClient.ListAlarmsStatus(listAlarmsStatusRequest);
                if (alarmStatus.Items.Count > 0)
                {
                    Console.WriteLine($" |-{compartment.Name}------------");

                    foreach (var alarm in alarmStatus.Items)
                    {
                        Console.WriteLine($"\tid:{alarm.Id}");
                        Console.WriteLine($"\tname:{alarm.DisplayName}");
                        Console.WriteLine($"\tstatus:{alarm.Status}");
                        Console.WriteLine($"\tseverity:{alarm.Severity}");
                    }
                }

                var listAlarmsRequest = new ListAlarmsRequest()
                {
                    CompartmentId = compartment.Id,
                    Limit         = 10
                };

                Console.WriteLine("  Alarm logs------------------------");
                var listAlarms = monitoringClient.ListAlarms(listAlarmsRequest);
                if (listAlarms.Items.Count > 0)
                {
                    Console.WriteLine($" |-{compartment.Name}------------");

                    foreach (var alarm in listAlarms.Items)
                    {
                        Console.WriteLine($"\tid:{alarm.Id}");
                        Console.WriteLine($"\tname:{alarm.DisplayName}");
                        Console.WriteLine($"\tdestinations:{alarm.Destinations}");
                        Console.WriteLine($"\tenable:{alarm.IsEnabled}");
                        Console.WriteLine($"\tstate:{alarm.LifecycleState}");

                        var getAlarmHistoryRequest = new GetAlarmHistoryRequest()
                        {
                            AlarmId = alarm.Id,
                            TimestampGreaterThanOrEqualTo = DateTime.UtcNow.ToString()
                        };
                        var history = monitoringClient.GetAlarmHistory(getAlarmHistoryRequest);
                        foreach (var his in history.AlarmHistoryCollection.Entries)
                        {
                            Console.WriteLine($"\t\t|-summary:{his.Summary}");
                            Console.WriteLine($"\t\t| timestamp:{his.Timestamp}");
                            Console.WriteLine($"\t\t| timestampTriggered:{his.TimestampTriggered}");
                        }
                    }
                }

                // Transactions Per Second (TPS) per-tenancy limit for this operation: 1.
                System.Threading.Thread.Sleep(1000);
            }
        }
        public static void InstanceConsoleDisplay(ClientConfig config)
        {
            // create client
            ComputeClient computeClient = new ComputeClient(config)
            {
                Region = Regions.US_ASHBURN_1
            };

            BlockstorageClient blockstorageClient = new BlockstorageClient(config)
            {
                Region = Regions.US_ASHBURN_1
            };

            VirtualNetworkClient networkingClient = new VirtualNetworkClient(config)
            {
                Region = Regions.US_ASHBURN_1
            };

            // get instanse list(RUNNING only)
            Console.WriteLine("* List Instance------------------------");
            var listInstanceRequest = new ListInstancesRequest()
            {
                // target compartment is root compartment(tenancy)
                CompartmentId  = computeClient.Config.TenancyId,
                Limit          = 50,
                LifecycleState = ListInstancesRequest.LifecycleStates.RUNNING,
                SortOrder      = SortOrder.ASC,
                SortBy         = ListInstancesRequest.SortByParam.TIMECREATED
            };
            // get instance
            var listInstance = computeClient.ListInstances(listInstanceRequest);

            listInstance.Items.ForEach(instance => {
                GetInstanceRequest getInstanceRequest = new GetInstanceRequest()
                {
                    InstanceId = instance.Id
                };
                var insDetail = computeClient.GetInstance(getInstanceRequest).Instance;
                Console.WriteLine(" |-" + insDetail.DisplayName);
                Console.WriteLine(" | id: " + insDetail.Id);
                Console.WriteLine(" | AD: " + insDetail.AvailabilityDomain);
                Console.WriteLine(" | shape: " + insDetail.Shape);
                Console.WriteLine(" | state: " + insDetail.LifecycleState);
                Console.WriteLine(" |\t|- * SourceDetails");
                Console.WriteLine(" |\t|\t type: " + insDetail.SourceDetails.SourceType);
                if ("image".Equals(insDetail.SourceDetails.SourceType))
                {
                    Console.WriteLine(" |\t|\t id: " + insDetail.SourceDetails.ImageId);

                    // get sourceDetail machine image
                    GetImageRequest getImageRequest = new GetImageRequest()
                    {
                        ImageId = insDetail.SourceDetails.ImageId
                    };
                    var machineimage = computeClient.GetImage(getImageRequest);
                    Console.WriteLine(" |\t|\t name: " + machineimage.Image.DisplayName);
                    Console.WriteLine(" |\t|\t sizeInMBs: " + machineimage.Image.SizeInMBs);
                }
                else
                {
                    Console.WriteLine(" |\t|\t id: " + insDetail.SourceDetails.BootVolumeId);

                    // get sourceDetail bootVolume
                    GetBootVolumeRequest getBootVolumeRequest = new GetBootVolumeRequest()
                    {
                        BootVolumeId = insDetail.SourceDetails.BootVolumeId
                    };
                    var bootvol = blockstorageClient.GetBootVolume(getBootVolumeRequest);
                    Console.WriteLine(" |\t|\t name: " + bootvol.BootVolume.DisplayName);
                    Console.WriteLine(" |\t|\t sizeInGBs: " + bootvol.BootVolume.SizeInGBs.Value);
                }

                // get instance atattch bootvolumes
                var bootvolumeAtattch = new ListBootVolumeAttachmentsRequest()
                {
                    InstanceId         = instance.Id,
                    CompartmentId      = instance.CompartmentId,
                    AvailabilityDomain = instance.AvailabilityDomain,
                    Limit = 50
                };
                var listBvAtattch = computeClient.ListBootVolumeAttachments(bootvolumeAtattch);
                listBvAtattch.Items.ForEach(bootVolAtt => {
                    Console.WriteLine(" |\t|- * BootVolume");

                    // get bootvolume
                    var getBootVolumeRequest = new GetBootVolumeRequest()
                    {
                        BootVolumeId = bootVolAtt.BootVolumeId
                    };
                    var bv = blockstorageClient.GetBootVolume(getBootVolumeRequest);
                    Console.WriteLine(" |\t|\t name:" + bv.BootVolume.DisplayName);
                    Console.WriteLine(" |\t|\t id:" + bv.BootVolume.Id);
                    Console.WriteLine(" |\t|\t state:" + bv.BootVolume.LifecycleState);
                    Console.WriteLine(" |\t|\t sizeInGBs:" + bv.BootVolume.SizeInGBs.Value);
                });

                // get instance atattch vnics
                var vnicAtattch = new ListVnicAttachmentsRequest()
                {
                    InstanceId         = instance.Id,
                    CompartmentId      = instance.CompartmentId,
                    AvailabilityDomain = instance.AvailabilityDomain,
                    Limit = 50
                };
                var listVnicAtattch = computeClient.ListVnicAttachments(vnicAtattch);
                listVnicAtattch.Items.ForEach(vnicA => {
                    Console.WriteLine(" |\t|- * Vnic");
                    GetVnicRequest getVnicRequest = new GetVnicRequest()
                    {
                        VnicId = vnicA.VnicId
                    };
                    var vnic = networkingClient.GetVnic(getVnicRequest);
                    Console.WriteLine(" |\t|\t name:" + vnic.Vnic.DisplayName);
                    Console.WriteLine(" |\t|\t id:" + vnic.Vnic.Id);
                    Console.WriteLine(" |\t|\t state:" + vnic.Vnic.LifecycleState);
                    Console.WriteLine(" |\t|\t privateIp:" + vnic.Vnic.PrivateIp);
                    Console.WriteLine(" |\t|\t publicIp:" + vnic.Vnic.PublicIp);
                });

                // get instance atattch volumes
                var volumeAtattch = new ListVolumeAttachmentsRequest()
                {
                    InstanceId         = instance.Id,
                    CompartmentId      = instance.CompartmentId,
                    AvailabilityDomain = instance.AvailabilityDomain,
                    Limit = 50
                };
                var listVolAtattch = computeClient.ListVolumeAttachments(volumeAtattch);
                listVolAtattch.Items.ForEach(volAtt => {
                    Console.WriteLine(" |\t|- * Volume");

                    // get bootvolume
                    var getVolumeRequest = new GetVolumeRequest()
                    {
                        VolumeId = volAtt.VolumeId
                    };
                    var vol = blockstorageClient.GetVolume(getVolumeRequest);
                    Console.WriteLine(" |\t|\t name:" + vol.Volume.DisplayName);
                    Console.WriteLine(" |\t|\t id:" + vol.Volume.Id);
                    Console.WriteLine(" |\t|\t state:" + vol.Volume.LifecycleState);
                    Console.WriteLine(" |\t|\t sizeInGBs:" + vol.Volume.SizeInGBs.Value);
                });
            });

            // get list Machine Images
            Console.WriteLine();
            Console.WriteLine("* List Image------------------------ max 10");
            var listImagesRequest = new ListImagesRequest()
            {
                // target compartment is root compartment(tenancy)
                CompartmentId  = config.TenancyId,
                Limit          = 10,
                LifecycleState = ListImagesRequest.LifecycleStates.AVAILABLE,
                SortOrder      = SortOrder.ASC,
                SortBy         = ListImagesRequest.SortByParam.TIMECREATED
            };
            // get instance
            var listImage = computeClient.ListImages(listImagesRequest);

            listImage.Items.ForEach(image =>
            {
                Console.WriteLine(" |-" + image.DisplayName);
                Console.WriteLine(" | id: " + image.Id);
                Console.WriteLine(" | os: " + image.OperatingSystem);
                Console.WriteLine(" | os ver: " + image.OperatingSystemVersion);
                Console.WriteLine(" | lifecycle: " + image.LifecycleState);
                Console.WriteLine(" | sizeInMBs: " + image.SizeInMBs);
                Console.WriteLine(" | BaseMachineId: " + image.BaseImageId);
            });
        }
示例#17
0
        private void doDeploy(string subscriptionID, AzureOAuth2Token token, string id, AzureTemplate template, IConfigSectionNode customData)
        {
            var nicName = id;

            var networkClient = new NetworkClient(this, DEFAULT_RESOURCE, subscriptionID, token);

            string           securityGroup    = null;
            NetworkInterface networkInterface = null;
            List <NetworkInterfaceIPConfiguration> ipConfigurations = null;
            List <NetworkInterface> networkInterfaces = null;

            foreach (var ni in template.NetworkInterfaces.OrderBy(ni => ni.SecurityGroup))
            {
                if (networkInterfaces == null)
                {
                    networkInterfaces = new List <NetworkInterface>();
                }
                var subnet   = networkClient.GetSubnet(template.Group, ni.VNet, ni.Subnet);
                var publicIP = ni.PublicIP.IsNotNullOrWhiteSpace() ? networkClient.GetPublicIPAddress(template.Group, ni.PublicIP) : null;

                if (securityGroup != ni.SecurityGroup)
                {
                    securityGroup = ni.SecurityGroup;
                    if (networkInterface != null)
                    {
                        networkInterfaces.Add(networkClient.CreateOrUpdateNetworkInterface(template.Group, nicName, networkInterface));
                    }
                    networkInterface = null;
                }

                if (networkInterface == null)
                {
                    var nsg = ni.SecurityGroup.IsNotNullOrWhiteSpace() ? networkClient.GetNetworkSecurityGroup(template.Group, ni.SecurityGroup) : null;

                    ipConfigurations = new List <NetworkInterfaceIPConfiguration>();

                    networkInterface = new NetworkInterface
                    {
                        Location   = template.Location,
                        Properties = new NetworkInterfacePropertiesFormat
                        {
                            IPConfigurations     = ipConfigurations,
                            NetworkSecurityGroup = nsg
                        }
                    };
                }

                ipConfigurations.Add(new NetworkInterfaceIPConfiguration
                {
                    Properties = new NetworkInterfaceIPConfigurationPropertiesFormat
                    {
                        Subnet          = subnet,
                        PublicIPAddress = publicIP
                    }
                });
            }

            if (networkInterface != null)
            {
                networkInterfaces.Add(networkClient.CreateOrUpdateNetworkInterface(template.Group, nicName, networkInterface));
            }

            var computeClient = new ComputeClient(this, subscriptionID, token);

            computeClient.CreateOrUpdateVirtualMachine(template.Group, id, new VirtualMachine
            {
                Location   = template.Location,
                Properties = new VirtualMachinePropertiesFormat
                {
                    hardwareProfile = new HardwareProfile {
                        vmSize = template.HardwareProfile
                    },
                    storageProfile = new StorageProfile
                    {
                        osDisk = new OSDisk
                        {
                            osType       = OperatingSystemTypes.Windows,
                            name         = id + ".SYSTEM",
                            createOption = DiskCreateOptionTypes.fromImage,
                            image        = new VirtualHardDisk {
                                uri = template.ImageUri
                            },
                            vhd = new VirtualHardDisk {
                                uri = template.OSDiskUri.Args(id + ".SYSTEM")
                            },
                            caching = CachingTypes.ReadWrite
                        }
                    },
                    osProfile = new OSProfile
                    {
                        computerName  = id,
                        adminUserName = template.AdminUsername,
                        adminPassword = template.AdminPassword
                    },
                    networkProfile = new NetworkProfile
                    {
                        networkInterfaces = networkInterfaces.Select(ni => new NetworkInterfaceReference(ni)).ToList()
                    }
                }
            });

            throw new NotImplementedException();
        }
示例#18
0
        public static async Task CreateVmAsync(
            string subscriptionId,
            string resourceGroup,
            string location,
            string vmName)
        {
            // Initialize Client
            var resourceClient = new ResourceClient(subscriptionId, new DefaultAzureCredential(true));
            var networkClient  = new NetworkClient(subscriptionId, new DefaultAzureCredential(true));
            var computeClient  = new ComputeClient(subscriptionId, new DefaultAzureCredential(true));

            // Create Resource Group
            await resourceClient.ResourceGroups.CreateOrUpdateAsync(resourceGroup, new ResourceGroup(location));

            // Create AvailabilitySet
            // TODO: Review initializer
            var availabilitySet = new AvailabilitySet(location);

            availabilitySet.PlatformFaultDomainCount  = 2;
            availabilitySet.PlatformUpdateDomainCount = 5;
            availabilitySet.Sku = new Sku()
            {
                Name = "Aligned"
            };

            availabilitySet = await computeClient.AvailabilitySets
                              .CreateOrUpdateAsync(resourceGroup, vmName + "_aSet", availabilitySet);

            // Create IP Address
            // TODO: Review other initializers
            var ipAddress = new PublicIPAddress();

            ipAddress.PublicIPAddressVersion   = IPVersion.IPv4;
            ipAddress.PublicIPAllocationMethod = IPAllocationMethod.Dynamic;
            ipAddress.Location = location;

            ipAddress = await networkClient
                        .PublicIPAddresses.StartCreateOrUpdate(resourceGroup, vmName + "_ip", ipAddress)
                        .WaitForCompletionAsync();

            // Create VNet
            var vnet = new VirtualNetwork();

            vnet.Location = location;
            vnet.AddAddressSpace("10.0.0.0/16");
            vnet.AddNewSubnet("mySubnet", "10.0.0.0/24");
            vnet.AddNewSubnet("mySubnet1", "10.0.1.0/24");

            vnet = await networkClient.VirtualNetworks
                   .StartCreateOrUpdate(resourceGroup, vmName + "_vent", vnet)
                   .WaitForCompletionAsync();

            // Create Network interface
            var nic = new NetworkInterface();

            nic.Location = location;
            nic.UseExistingVirtualNetwork(vnet, "mySubnet");
            nic.UseExistingPublicIP(ipAddress);

            nic = await networkClient.NetworkInterfaces
                  .StartCreateOrUpdate(resourceGroup, vmName + "_nic", nic)
                  .WaitForCompletionAsync();

            var vm = new VirtualMachine(location);

            vm.AddExistingNetworkInterface(nic.Id, true);
            vm.SetAvailabilitySet(availabilitySet.Id);
            vm.ConfigureLinuxWithPassword(
                VirtualMachineSizeTypes.StandardB1Ms,
                "testVM",
                "azureUser",
                "azure12345QWE!",
                configuration: new LinuxConfiguration {
                DisablePasswordAuthentication = false, ProvisionVMAgent = true
            });

            await computeClient.VirtualMachines
            .StartCreateOrUpdate(resourceGroup, vmName, vm)
            .WaitForCompletionAsync();
        }
示例#19
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string username = null;
            string password = null;
            var    url      = "https://compute.procedural.build";
            var    retry    = false;

            if (!DA.GetData(0, ref username))
            {
                return;
            }
            if (!DA.GetData(1, ref password))
            {
                return;
            }
            DA.GetData(2, ref url);
            DA.GetData(3, ref retry);

            var client = new ComputeClient(url);

            if (retry)
            {
                StringCache.ClearCache();
            }

            //Async Execution
            var cacheKey     = username + password + url;
            var cachedTokens = StringCache.getCache(cacheKey);

            DA.DisableGapLogic();
            if (cachedTokens == null)
            {
                var queueName = "login";
                // Get queue lock
                var queueLock = StringCache.getCache(queueName);
                if (queueLock != "true")
                {
                    StringCache.setCache(queueName, "true");
                    QueueManager.addToQueue(queueName, () =>
                    {
                        try
                        {
                            var results = client.Auth(username, password);

                            if (results.ErrorMessages != null)
                            {
                                StringCache.setCache(cacheKey, "error");
                                throw new Exception(results.ErrorMessages.First());
                            }
                            if (results.ErrorMessages == null)
                            {
                                StringCache.ClearCache();
                                cachedTokens = results.ToJson();
                                StringCache.setCache(cacheKey, cachedTokens);
                            }
                        }
                        catch (Exception e)
                        {
                            StringCache.setCache(InstanceGuid.ToString(), e.Message);
                        }

                        ExpireSolutionThreadSafe(true);
                        Thread.Sleep(2000);
                        StringCache.setCache(queueName, "");
                    });
                }
            }


            // Read from Cache
            var errors = StringCache.getCache(InstanceGuid.ToString());

            if (errors != null)
            {
                if (errors.Contains("(401) Unauthorized"))
                {
                    errors = "Could not login with the provided credentials. Try again.";
                }

                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, errors);
            }

            var tokens = new AuthTokens();

            if (cachedTokens != null)
            {
                tokens = tokens.FromJson(cachedTokens);
                var output = new Inputs
                {
                    Auth = tokens,
                    Url  = url
                };
                DA.SetData(0, output.ToJson());
            }
        }
示例#20
0
        public static async Task CreateVmAsync(
            string subscriptionId,
            string resourceGroup,
            string location,
            string vmName)
        {
            // Initialize Client
            var resourceClient = new ResourceClient(subscriptionId, new DefaultAzureCredential(true));
            var networkClient  = new NetworkClient(subscriptionId, new DefaultAzureCredential(true));
            var computeClient  = new ComputeClient(subscriptionId, new DefaultAzureCredential(true));

            // Create Resource Group
            await resourceClient.ResourceGroups.CreateOrUpdateAsync(resourceGroup, new ResourceGroup(location));

            // Create AvailabilitySet
            var availabilitySet = new AvailabilitySet(location);

            //// Following are optional, has default, probably no need for helpers as there are simple types.
            //// For other complex properties, need to evaluate common usage scenarios
            availabilitySet.PlatformFaultDomainCount  = 5;
            availabilitySet.PlatformUpdateDomainCount = 2;
            availabilitySet.Sku = new Sku()
            {
                Name = "Aligned"
            };

            availabilitySet = await computeClient.AvailabilitySets
                              .CreateOrUpdateAsync(resourceGroup, vmName + "_aSet", availabilitySet);

            // Create IP Address
            var ipAddress = new PublicIPAddress();

            // TODO Need to review. Downside of using string instead of enum is intellisense is messed up. But extensibility may trump this.
            // While . is easier to see intellisense, still does not give sense of necessary required properties.
            // Initializer helper should be added for initialization.
            ipAddress.PublicIPAddressVersion   = IPVersion.IPv4;
            ipAddress.PublicIPAllocationMethod = IPAllocationMethod.Dynamic;
            ipAddress.Location = location;

            ipAddress = await networkClient
                        .PublicIPAddresses.StartCreateOrUpdate(resourceGroup, vmName + "_ip", ipAddress)
                        .WaitForCompletionAsync();

            // Create VNet
            var vnet = new VirtualNetwork();

            vnet.Location = location;
            vnet.Subnets.Add(new Subnet()
            {
                Name = "name", AddressPrefix = "10.0.0.0/1"
            });
            vnet.AddressSpace.AddressPrefixes.Add("10.0.0.0/16");
            // TODO: vnet.Subnets.AddExistingSubnet("existing id");

            vnet = await networkClient.VirtualNetworks
                   .StartCreateOrUpdate(resourceGroup, vmName + "_vent", vnet)
                   .WaitForCompletionAsync();

            // Create Network interface
            var nic = new NetworkInterface();

            nic.Location = location;
            // TODO may need helper extensions for existing and new
            nic.IpConfigurations.Add(new NetworkInterfaceIPConfiguration()
            {
                Name    = "Primary",
                Primary = true,
                Subnet  = new Subnet()
                {
                    Id = vnet.Subnets.First().Id
                },
                PrivateIPAllocationMethod = IPAllocationMethod.Dynamic,
                PublicIPAddress           = new PublicIPAddress()
                {
                    Id = ipAddress.Id
                }
            });

            nic = await networkClient.NetworkInterfaces
                  .StartCreateOrUpdate(resourceGroup, vmName + "_nic", nic)
                  .WaitForCompletionAsync();

            var vm = new VirtualMachine(location);

            vm.NetworkProfile = new NetworkProfile {
                NetworkInterfaces = new[] { new NetworkInterfaceReference()
                                            {
                                                Id = nic.Id
                                            } }
            };
            vm.AvailabilitySet.Id = availabilitySet.Id;
            vm.OsProfile          = new OSProfile
            {
                // TODO User name, password, SSH should have helpers
                ComputerName       = "testVM",
                AdminUsername      = "******",
                AdminPassword      = "******",
                LinuxConfiguration = new LinuxConfiguration
                {
                    DisablePasswordAuthentication = false, ProvisionVMAgent = true
                }
            };
            vm.StorageProfile = new StorageProfile()
            {
                ImageReference = new ImageReference()
                {
                    Offer     = "UbuntuServer",
                    Publisher = "Canonical",
                    Sku       = "18.04-LTS",
                    Version   = "latest"
                },
                DataDisks = new List <DataDisk>()
            };
            // vm.SetLatestWindowsImage();

            await computeClient.VirtualMachines
            .StartCreateOrUpdate(resourceGroup, vmName, vm)
            .WaitForCompletionAsync();
        }
示例#21
0
 public ComputeWaiters(ComputeClient client, Oci.WorkrequestsService.WorkRequestClient workRequestClient)
 {
     this.client            = client;
     this.workRequestClient = workRequestClient;
 }
 public void SetUp()
 {
     client = new ComputeClient(user.host);
 }
        public static async Task MainInstance()
        {
            logger.Info("Starting example");

            var provider      = new ConfigFileAuthenticationDetailsProvider("DEFAULT");
            var compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID");

            var identityClient       = new IdentityClient(provider);
            var computeClient        = new ComputeClient(provider, new ClientConfiguration());
            var virtualNetworkClient = new VirtualNetworkClient(provider);
            var blockStorageClient   = new BlockstorageClient(provider);
            var networkCidrBlock     = "10.0.1.0/24";

            LaunchInstanceDetails launchInstanceDetails = null;
            Instance          instance               = null;
            BootVolume        bootVolume             = null;
            Instance          instanceFromBootVolume = null;
            Vcn               vcn               = null;
            Subnet            subnet            = null;
            CreateVnicDetails createVnicDetails = null;
            InternetGateway   internetGateway   = null;

            AvailabilityDomain availablityDomain = await getAvailabilityDomains(identityClient, compartmentId);

            logger.Info($"availability domain is {availablityDomain.Name}");

            Shape shape = await getShape(computeClient, compartmentId, availablityDomain);

            if (shape == null)
            {
                logger.Error($"No Shapes available in the availability domain: {availablityDomain.Name}");
                return;
            }
            logger.Info($"shape is {shape.ShapeProp}");
            Image image = await getImage(computeClient, compartmentId, shape);

            try
            {
                vcn = await createVcn(virtualNetworkClient, compartmentId, networkCidrBlock);

                // The Internet Gateway with updated Route Rules will enable the instance to connect to the public
                // internet. If it is not desired, remove the following two lines below that create an internet
                // gateway and add that internet gateway to the VCN route table.
                internetGateway = await createInternalGateway(virtualNetworkClient, compartmentId, vcn);
                await addInternetGatewayToDefaultRouteTable(virtualNetworkClient, vcn, internetGateway);

                subnet = await createSubnet(virtualNetworkClient, compartmentId, availablityDomain, networkCidrBlock, vcn);

                createVnicDetails = new CreateVnicDetails {
                    SubnetId = subnet.Id
                };

                launchInstanceDetails = new LaunchInstanceDetails
                {
                    AvailabilityDomain = availablityDomain.Name,
                    CompartmentId      = compartmentId,
                    Shape             = shape.ShapeProp,
                    CreateVnicDetails = createVnicDetails,
                    ImageId           = image.Id
                };

                instance = await createInstance(computeClient, launchInstanceDetails);
                await printInstance(computeClient, virtualNetworkClient, instance);

                logger.Info("Instance is being created via boot volume ...");
                // This boot volume is created based on the boot volume of previous instance which needs to be running
                bootVolume = await createBootVolume(blockStorageClient, compartmentId, availablityDomain, image);

                launchInstanceDetails  = createLaunchInstanceDetailsFromBootVolume(launchInstanceDetails, bootVolume);
                instanceFromBootVolume = await createInstance(computeClient, launchInstanceDetails);
                await printInstance(computeClient, virtualNetworkClient, instanceFromBootVolume);
            }
            catch (Exception e)
            {
                logger.Error($"Failed to call LaunchInstance API: {e.Message}");
            }
            finally
            {
                logger.Info("cleaning up resources");
                if (instanceFromBootVolume != null)
                {
                    await terminateInstance(computeClient, instanceFromBootVolume);
                }

                if (instance != null)
                {
                    await terminateInstance(computeClient, instance);
                }

                if (internetGateway != null)
                {
                    await clearRouteRulesFromDefaultRouteTable(virtualNetworkClient, vcn);
                    await deleteInternetGateway(virtualNetworkClient, internetGateway);
                }

                if (subnet != null)
                {
                    await deleteSubnet(virtualNetworkClient, subnet);
                }

                if (vcn != null)
                {
                    await deleteVcn(virtualNetworkClient, vcn);
                }

                identityClient.Dispose();
                computeClient.Dispose();
                virtualNetworkClient.Dispose();
                blockStorageClient.Dispose();

                logger.Info("End example");
            }
        }
示例#24
0
        public static async Task CreateVmAsync(
            string subscriptionId,
            string resourceGroup,
            string location,
            string vmName)
        {
            // Initialize Client
            var resourceClient = new ResourceClient(subscriptionId, new DefaultAzureCredential(true));
            var networkClient  = new NetworkClient(subscriptionId, new DefaultAzureCredential(true));
            var computeClient  = new ComputeClient(subscriptionId, new DefaultAzureCredential(true));

            // Create Resource Group
            await resourceClient.ResourceGroups.CreateOrUpdateAsync(resourceGroup, new ResourceGroup(location));

            // Create AvailabilitySet
            var availabilitySet = new AvailabilitySet(location)
            {
                PlatformUpdateDomainCount = 5,
                PlatformFaultDomainCount  = 2,
                Sku = new Sku()
                {
                    Name = "Aligned"
                }                                     // TODO. Verify new codegen on AvailabilitySetSkuTypes.Aligned
            };

            availabilitySet = await computeClient.AvailabilitySets
                              .CreateOrUpdateAsync(resourceGroup, vmName + "_aSet", availabilitySet);

            // Create IP Address
            // TODO verify why lack of (location) ctor.
            var ipAddress = new PublicIPAddress()
            {
                PublicIPAddressVersion   = IPVersion.IPv4,
                PublicIPAllocationMethod = IPAllocationMethod.Dynamic,
                Location = location,
            };

            ipAddress = await networkClient
                        .PublicIPAddresses.StartCreateOrUpdate(resourceGroup, vmName + "_ip", ipAddress)
                        .WaitForCompletionAsync();

            // Create VNet
            var vnet = new VirtualNetwork()
            {
                Location     = location,
                AddressSpace = new AddressSpace()
                {
                    AddressPrefixes = new List <string>()
                    {
                        "10.0.0.0/16"
                    }
                },
                Subnets = new List <Subnet>()
                {
                    new Subnet()
                    {
                        Name          = "mySubnet",
                        AddressPrefix = "10.0.0.0/24",
                    }
                },
            };

            vnet = await networkClient.VirtualNetworks
                   .StartCreateOrUpdate(resourceGroup, vmName + "_vent", vnet)
                   .WaitForCompletionAsync();

            // Create Network interface
            var nic = new NetworkInterface()
            {
                Location         = location,
                IpConfigurations = new List <NetworkInterfaceIPConfiguration>()
                {
                    new NetworkInterfaceIPConfiguration()
                    {
                        Name    = "Primary",
                        Primary = true,
                        Subnet  = new Subnet()
                        {
                            Id = vnet.Subnets.First().Id
                        },
                        PrivateIPAllocationMethod = IPAllocationMethod.Dynamic,
                        PublicIPAddress           = new PublicIPAddress()
                        {
                            Id = ipAddress.Id
                        }
                    }
                }
            };

            nic = await networkClient.NetworkInterfaces
                  .StartCreateOrUpdate(resourceGroup, vmName + "_nic", nic)
                  .WaitForCompletionAsync();

            var vm = new VirtualMachine(location)
            {
                NetworkProfile = new NetworkProfile {
                    NetworkInterfaces = new [] { new NetworkInterfaceReference()
                                                 {
                                                     Id = nic.Id
                                                 } }
                },
                OsProfile = new OSProfile
                {
                    ComputerName       = "testVM",
                    AdminUsername      = "******",
                    AdminPassword      = "******",
                    LinuxConfiguration = new LinuxConfiguration {
                        DisablePasswordAuthentication = false, ProvisionVMAgent = true
                    }
                },
                StorageProfile = new StorageProfile()
                {
                    ImageReference = new ImageReference()
                    {
                        Offer     = "UbuntuServer",
                        Publisher = "Canonical",
                        Sku       = "18.04-LTS",
                        Version   = "latest"
                    },
                    DataDisks = new List <DataDisk>()
                },
                HardwareProfile = new HardwareProfile()
                {
                    VmSize = VirtualMachineSizeTypes.StandardB1Ms
                },
            };

            vm.AvailabilitySet.Id = availabilitySet.Id;

            await computeClient.VirtualMachines
            .StartCreateOrUpdate(resourceGroup, vmName, vm)
            .WaitForCompletionAsync();
        }