示例#1
0
    public IDictionary <string, string> RunInstance(string amiId = null)
    {
        IDictionary <string, string> result = null;

        // Executa uma instância.
        try
        {
            if (amiId == null)
            {
                amiId = AwsEnv.DEFAULT_AMI_ID;
            }
            RunInstancesRequest runRequest = new RunInstancesRequest(amiId, 1, 1);
            runRequest.InstanceType = AwsEnv.DEFAULT_INST_TYPE;
            runRequest.KeyName      = AwsEnv.DEFAULT_KEY_NAME;
            runRequest.SecurityGroups.Add(AwsEnv.DEFAULT_SECURITY_GROUP);

            RunInstancesResponse runResponse = Ec2.RunInstances(runRequest);
            result = runResponse.ResponseMetadata.Metadata;
            result.Add("STATUS_CODE", runResponse.HttpStatusCode.ToString());
            result.Add("RESPONSE", runResponse.ToString());
        }
        catch (AmazonEC2Exception ex)
        {
            throw new AwsException(ex);
        }

        return(result);
    }
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            RunInstancesResponse response = new RunInstancesResponse();

            int originalDepth = context.CurrentDepth;
            int targetDepth   = originalDepth + 1;

            if (context.IsStartOfDocument)
            {
                targetDepth = 2;
            }

            while (context.ReadAtDepth(originalDepth))
            {
                if (context.IsStartElement || context.IsAttribute)
                {
                    if (context.TestExpression(".", targetDepth))
                    {
                        response.Reservation = ReservationUnmarshaller.Instance.Unmarshall(context);
                        continue;
                    }
                }
            }

            return(response);
        }
示例#3
0
        /// <summary>
        /// StartInstances utilizes EC2 interface to launch specified number of instances.
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        public int StartInstances(int count)
        {
            var configOptions = GetConfigOptions();
            var ctx           = AppUtility.GetContext();

            Debug.WriteLine(String.Format("StartInstances: {0}", count), this.GetType());
            var runRequest = new RunInstancesRequest();

            runRequest.ImageId      = ctx.AMI;
            runRequest.MinCount     = count;
            runRequest.MaxCount     = count;
            runRequest.InstanceType = ctx.InstanceType;
            Object instanceType;

            if (configOptions.TryGetValue("instance", out instanceType))
            {
                Debug.WriteLine("InstanceType Requested: " + instanceType, GetType());
                var instanceList = new List <string>()
                {
                    "t1.micro", "m1.small", "c1.medium"
                };
                if (!instanceList.Contains(instanceType))
                {
                    var msg = String.Format("Requested instanceType {0} not in {1}",
                                            instanceType, string.Join(",", instanceList.ToArray()));
                    Debug.WriteLine(msg);
                }
                else
                {
                    runRequest.InstanceType = (string)instanceType;
                }
            }

            runRequest.SecurityGroup = new System.Collections.Generic.List <String>()
            {
                ctx.SecurityGroup
            };
            runRequest.WithInstanceInitiatedShutdownBehavior("terminate");
            if (!String.IsNullOrEmpty(ctx.AvailabilityZone))
            {
                runRequest.Placement = new Placement();
                runRequest.Placement.AvailabilityZone = ctx.AvailabilityZone;
            }
            RunInstancesResponse response = client.RunInstances(runRequest);

            return(response.RunInstancesResult.Reservation.RunningInstance.Count());
        }
        public static RunInstancesResponse Unmarshall(UnmarshallerContext context)
        {
            RunInstancesResponse runInstancesResponse = new RunInstancesResponse();

            runInstancesResponse.HttpResponse = context.HttpResponse;
            runInstancesResponse.RequestId    = context.StringValue("RunInstances.RequestId");

            List <string> runInstancesResponse_instanceIdSets = new List <string>();

            for (int i = 0; i < context.Length("RunInstances.InstanceIdSets.Length"); i++)
            {
                runInstancesResponse_instanceIdSets.Add(context.StringValue("RunInstances.InstanceIdSets[" + i + "]"));
            }
            runInstancesResponse.InstanceIdSets = runInstancesResponse_instanceIdSets;

            return(runInstancesResponse);
        }
        public static RunInstancesResponse Unmarshall(UnmarshallerContext _ctx)
        {
            RunInstancesResponse runInstancesResponse = new RunInstancesResponse();

            runInstancesResponse.HttpResponse = _ctx.HttpResponse;
            runInstancesResponse.RequestId    = _ctx.StringValue("RunInstances.RequestId");
            runInstancesResponse.TradePrice   = _ctx.FloatValue("RunInstances.TradePrice");

            List <string> runInstancesResponse_instanceIdSets = new List <string>();

            for (int i = 0; i < _ctx.Length("RunInstances.InstanceIdSets.Length"); i++)
            {
                runInstancesResponse_instanceIdSets.Add(_ctx.StringValue("RunInstances.InstanceIdSets[" + i + "]"));
            }
            runInstancesResponse.InstanceIdSets = runInstancesResponse_instanceIdSets;

            return(runInstancesResponse);
        }
示例#6
0
        static void EC2_instance_operations()
        {
            try
            {
                // Launch the instance
                AmazonEC2Client     ec2     = new AmazonEC2Client();
                RunInstancesRequest request = new RunInstancesRequest();
                request.ImageId      = "ami-bf4193c7"; /* AMI ID in your region */
                request.InstanceType = "t1.micro";     /* Flavor */
                request.MinCount     = 1;
                request.MaxCount     = 1;
                request.KeyName      = "access"; /* Name of the key-pair */
                RunInstancesResponse response = ec2.RunInstances(request);

                Console.WriteLine("Launching instance....waiting for 30 seconds..");

                System.Threading.Thread.Sleep(30000);


                // Check the state
                var instances = response.Reservation.Instances;
                var id        = instances[0].InstanceId;
                var state     = instances[0].State;
                Console.WriteLine("State is : {0}", state.Name);

                Console.WriteLine("Terminating the instance..");

                // Terminate the instance
                var terminate_request = new TerminateInstancesRequest();
                terminate_request.InstanceIds.Add(instances[0].InstanceId);

                var terminate_response   = ec2.TerminateInstances(terminate_request);
                var terminating_instance = terminate_response.TerminatingInstances[0];

                Console.WriteLine("Terminating instance : {0}", terminating_instance.InstanceId);
                Console.WriteLine("Instance state : {0}", terminating_instance.CurrentState.Name);
            }
            catch (AmazonEC2Exception exception)
            {
                Console.WriteLine("Error!");
                Console.WriteLine(exception.ErrorCode);
            }
            Console.ReadKey();
        }
        public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            RunInstancesResponse response = new RunInstancesResponse();

            int targetDepth = 2;

            while (context.Read())
            {
                if (context.IsStartElement || context.IsAttribute)
                {
                    if (context.TestExpression(".", targetDepth))
                    {
                        response.Reservation = ReservationUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                }
            }


            return(response);
        }
示例#8
0
        /// <summary>
        /// Creates (Runs) a new EC2 instance from the stored AMI image.
        /// </summary>
        /// <param name="imageId"></param>
        /// <param name="numberOfInstances"></param>
        /// <param name="keyName"></param>
        /// <param name="userData"></param>
        /// <param name="securityGroups"></param>
        /// <param name="availabilityZone">The AWS availability zone (us-east-1a, us-east-1b, us-east-1c, us-east-1d, eu-west-1a, eu-west-1b)</param>
        /// <returns>Returns a list of ALL instances not terminated, not just the ones started.</returns>
        public List <string> RunInstance(string imageId, int numberOfInstances, string keyName, string userData, string[] securityGroups, string availabilityZone)
        {
            var request = new RunInstancesRequest
            {
                ImageId       = imageId,
                MinCount      = numberOfInstances,
                MaxCount      = numberOfInstances,
                KeyName       = keyName,
                UserData      = userData,
                SecurityGroup = new List <string>(securityGroups)
            };

            if (!string.IsNullOrEmpty(availabilityZone))
            {
                request.Placement = new Placement {
                    AvailabilityZone = availabilityZone
                };
            }

            RunInstancesResponse response = Client.RunInstances(request);

            return(response.RunInstancesResult.Reservation.RunningInstance.Select(runningInstance => runningInstance.InstanceId).ToList());
        }
示例#9
0
        internal void LaunchServer(ref bool actionSucceeded, ref string actionMessage)
        {
            try
            {
                string keyPairPath = string.Empty;
                LaunchRequest.KeyPairName = $"KeyPair-{Guid.NewGuid().ToString()}";
                while (!CreateKeyPair(LaunchRequest.KeyPairName, ref keyPairPath))
                {
                    LaunchRequest.KeyPairName = Guid.NewGuid().ToString();
                }

                DescribeVpcsRequest  vpcRequest  = new DescribeVpcsRequest();
                DescribeVpcsResponse vpcResponse = Ec2Client.DescribeVpcsAsync(vpcRequest).GetAwaiter().GetResult();

                Vpc defaultVPC = vpcResponse.Vpcs.Find(x => x.IsDefault); //get the default vpc

                List <Filter> subnetFilter = new List <Filter>()
                {
                    new Filter()
                    {
                        Name = "availability-zone", Values = new List <string>()
                        {
                            LaunchRequest.AvailabilityZone
                        }
                    },
                    new Filter()
                    {
                        Name = "vpc-id", Values = new List <string>()
                        {
                            defaultVPC.VpcId
                        }
                    }
                };

                DescribeSubnetsRequest subnetRequest = new DescribeSubnetsRequest();
                subnetRequest.Filters = subnetFilter;
                DescribeSubnetsResponse subnetResponse = Ec2Client.DescribeSubnetsAsync(subnetRequest).GetAwaiter().GetResult();
                Subnet defaultSubnet = subnetResponse.Subnets.FirstOrDefault();

                Filter SGFilter = new Filter
                {
                    Name   = "vpc-id",
                    Values = new List <string>()
                    {
                        defaultVPC.VpcId
                    }
                };

                DescribeSecurityGroupsRequest SGrequest = new DescribeSecurityGroupsRequest();
                SGrequest.Filters.Add(SGFilter);
                DescribeSecurityGroupsResponse SGresponse = Ec2Client.DescribeSecurityGroupsAsync(SGrequest).GetAwaiter().GetResult();
                SecurityGroup defaultSG = SGresponse.SecurityGroups.FirstOrDefault();

                InstanceNetworkInterfaceSpecification defaultENI = new InstanceNetworkInterfaceSpecification()
                {
                    DeviceIndex = 0,
                    SubnetId    = defaultSubnet.SubnetId,
                    Groups      = new List <string>()
                    {
                        defaultSG.GroupId
                    },
                    AssociatePublicIpAddress = true
                };

                List <InstanceNetworkInterfaceSpecification> enis = new List <InstanceNetworkInterfaceSpecification>()
                {
                    defaultENI
                };

                EbsBlockDevice ebsBlockDevice = new EbsBlockDevice
                {
                    VolumeSize = 10,
                    VolumeType = GetActualStorageType(LaunchRequest.StorageType)
                };
                BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping
                {
                    DeviceName = "/dev/xvda"
                };
                blockDeviceMapping.Ebs = ebsBlockDevice;

                var launchRequest = new RunInstancesRequest()
                {
                    ImageId             = GetImageID(LaunchRequest.AMIType),
                    InstanceType        = GetActualInstanceType(LaunchRequest.InstanceType),
                    MinCount            = LaunchRequest.NumOfInstances,
                    MaxCount            = LaunchRequest.NumOfInstances,
                    KeyName             = LaunchRequest.KeyPairName,
                    Placement           = new Placement(LaunchRequest.AvailabilityZone),
                    NetworkInterfaces   = enis,
                    BlockDeviceMappings = new List <BlockDeviceMapping>()
                    {
                        blockDeviceMapping
                    }
                };

                RunInstancesResponse launchResponse = Ec2Client.RunInstancesAsync(launchRequest).GetAwaiter().GetResult();

                List <String> instanceIds = new List <string>();
                foreach (Instance instance in launchResponse.Reservation.Instances)
                {
                    Console.WriteLine(instance.InstanceId);
                    instanceIds.Add(instance.InstanceId);
                }

                actionSucceeded = true;
                actionMessage   = $"The instance(s) are being launched. Please check the AWS Console to verify. {keyPairPath}";
            }
            catch (Exception ex)
            {
                context.Logger.LogLine($"ServerOperationsHelper::LaunchServer {ex.Message}");
                context.Logger.LogLine($"ServerOperationsHelper::LaunchServer {ex.StackTrace}");
                actionSucceeded = false;
                actionMessage   = $"Could not launch the server . Please contact your administrator.";
            }
        }
        // 该示例要运行成功,需要修改一些网络和安全组的设置。
        // 请慎重运行该示例,因为创建成功后会产生扣费。
        static void Main1(string[] args)
        {
            try
            {
                // 必要步骤:
                // 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。
                // 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。
                // 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人,
                // 以免泄露密钥对危及你的财产安全。
                Credential cred = new Credential
                {
                    SecretId  = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_ID"),
                    SecretKey = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_KEY")
                };

                // 实例化一个client选项,可选的,没有特殊需求可以跳过
                ClientProfile clientProfile = new ClientProfile();
                // 非必要步骤
                // 实例化一个客户端配置对象,可以指定超时时间等配置
                HttpProfile httpProfile = new HttpProfile();
                // 代理服务器,当你的环境下有代理服务器时设定
                httpProfile.WebProxy = Environment.GetEnvironmentVariable("HTTPS_PROXY");

                clientProfile.HttpProfile = httpProfile;

                // 实例化要请求产品(以cvm为例)的client对象
                // 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,或者引用预设的常量,clientProfile是可选的
                CvmClient client = new CvmClient(cred, "ap-guangzhou", clientProfile);

                // 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
                // 你可以直接查询SDK源码确定DescribeZonesRequest有哪些属性可以设置,
                // 属性可能是基本类型,也可能引用了另一个数据结构。
                // 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明。
                RunInstancesRequest req = new RunInstancesRequest();

                Placement placement = new Placement();
                placement.Zone = "ap-guangzhou-3";
                req.Placement  = placement;

                req.ImageId            = "img-8toqc6s3";
                req.InstanceChargeType = "POSTPAID_BY_HOUR";
                req.InstanceName       = "DOTNET_SDK_TEST";
                req.InstanceType       = "S2.SMALL1";

                InternetAccessible ia = new InternetAccessible();
                ia.InternetChargeType      = "BANDWIDTH_POSTPAID_BY_HOUR";
                ia.InternetMaxBandwidthOut = 10;
                ia.PublicIpAssigned        = true;
                req.InternetAccessible     = ia;

                LoginSettings ls = new LoginSettings();
                ls.Password       = "******";
                req.LoginSettings = ls;

                req.SecurityGroupIds = new string[] { "sg-icy671l9" };

                SystemDisk sd = new SystemDisk();
                sd.DiskSize    = 50;
                sd.DiskType    = "CLOUD_BASIC";
                req.SystemDisk = sd;

                VirtualPrivateCloud vpc = new VirtualPrivateCloud();
                vpc.VpcId               = "vpc-8ek64x3d";
                vpc.SubnetId            = "subnet-b1wk8b10";
                req.VirtualPrivateCloud = vpc;

                // 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的
                // 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应
                RunInstancesResponse resp = client.RunInstancesSync(req);

                // 输出json格式的字符串回包
                Console.WriteLine(AbstractModel.ToJsonString(resp));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.Read();
        }
        /// <summary>
        /// This method will look up the current VPC NAT ami in the region and create an instance in the subnet specified.
        /// </summary>
        /// <param name="ec2Client">The ec2client used to create the NAT instance</param>
        /// <param name="request">The properties used to launch the NAT instance.</param>
        /// <returns></returns>
        public static Instance LaunchNATInstance(IAmazonEC2 ec2Client, LaunchNATInstanceRequest request)
        {
            if (ec2Client == null)
            {
                throw new ArgumentNullException("ec2Client");
            }
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            if (string.IsNullOrEmpty(request.SubnetId))
            {
                throw new InvalidOperationException("request.SubnetId is null");
            }
            if (string.IsNullOrEmpty(request.InstanceType))
            {
                throw new InvalidOperationException("request.InstanceType is null");
            }

            List <Filter> filters = new List <Filter>()
            {
                new Filter()
                {
                    Name = "architecture", Values = new List <string>()
                    {
                        "x86_64"
                    }
                },
                new Filter()
                {
                    Name = "name", Values = new List <string>()
                    {
                        "ami-vpc-nat-*.x86_64-ebs"
                    }
                }
            };
            DescribeImagesResponse imageResponse = ec2Client.DescribeImages(new DescribeImagesRequest()
            {
                Filters = filters
            });
            var image = FindNATImage(ec2Client);

            if (image == null)
            {
                throw new AmazonEC2Exception("No NAT image found in this region");
            }

            RunInstancesRequest runRequest = new RunInstancesRequest()
            {
                InstanceType = request.InstanceType,
                KeyName      = request.KeyName,
                ImageId      = image.ImageId,
                MinCount     = 1,
                MaxCount     = 1,
                SubnetId     = request.SubnetId
            };
            RunInstancesResponse runResponse = ec2Client.RunInstances(runRequest);
            string instanceId = runResponse.Reservation.Instances[0].InstanceId;

            // Can't associated elastic IP address until the instance is available
            WaitForInstanceToStartUp(ec2Client, instanceId);

            ModifyInstanceAttributeRequest modifyRequest = new ModifyInstanceAttributeRequest()
            {
                InstanceId = instanceId,
                Attribute  = "sourceDestCheck",
                Value      = "false"
            };

            ec2Client.ModifyInstanceAttribute(modifyRequest);

            ec2Client.CreateTags(new CreateTagsRequest()
            {
                Resources = new List <string>()
                {
                    instanceId
                },
                Tags = new List <Tag>()
                {
                    new Tag()
                    {
                        Key = "Name", Value = "NAT"
                    }
                }
            });

            var allocationId = ec2Client.AllocateAddress(new AllocateAddressRequest()
            {
                Domain = "vpc"
            }).AllocationId;

            ec2Client.AssociateAddress(new AssociateAddressRequest()
            {
                InstanceId = instanceId, AllocationId = allocationId
            });

            var instance = ec2Client.DescribeInstances(new DescribeInstancesRequest()
            {
                InstanceIds = new List <string>()
                {
                    instanceId
                }
            }).Reservations[0].Instances[0];

            return(instance);
        }
示例#12
0
        // enumerate VPC security group and create a security group for EC2-VPC
        public void create_lunch_checkstatus_for_istance()
        {
            //Create an Amazon EC2 Client Using the the SDK
            var ec2Client = new AmazonEC2Client();
            // enumerate VPC security group
            string        secGroupName = "my-sample-sg-vpc";
            SecurityGroup mySG         = null;
            string        vpcID        = "vpc-7cdc5904";

            Amazon.EC2.Model.Filter vpcFilter = new Amazon.EC2.Model.Filter
            {
                Name   = "vpc-id",
                Values = new List <string>()
                {
                    vpcID
                }
            };
            var dsgRequest = new DescribeSecurityGroupsRequest();

            dsgRequest.Filters.Add(vpcFilter);
            var dsgResponse            = ec2Client.DescribeSecurityGroups(dsgRequest);
            List <SecurityGroup> mySGs = dsgResponse.SecurityGroups;

            foreach (SecurityGroup item in mySGs)
            {
                Console.WriteLine("Existing security group: " + item.GroupId);
                if (item.GroupName == secGroupName)
                {
                    mySG = item;
                }
            }
            //create a security group for EC2-VPC
            if (mySG == null)
            {
                var newSGRequest = new CreateSecurityGroupRequest()
                {
                    GroupName   = secGroupName,
                    Description = "My sample security group for EC2-VPC",
                    VpcId       = vpcID
                };
                var csgResponse = ec2Client.CreateSecurityGroup(newSGRequest);
                Console.WriteLine();
                Console.WriteLine("New security group: " + csgResponse.GroupId);

                List <string> Groups = new List <string>()
                {
                    csgResponse.GroupId
                };
                var newSgRequest = new DescribeSecurityGroupsRequest()
                {
                    GroupIds = Groups
                };
                var newSgResponse = ec2Client.DescribeSecurityGroups(newSgRequest);
                mySG = newSgResponse.SecurityGroups[0];
            }
            //Create and initialize an IpPermission object.

            //iprange = the IP addresses of your local machine
            string ipRange = "0.0.0.0/0";

            List <string> ranges = new List <string>()
            {
                ipRange
            };

            var ipPermission = new IpPermission()
            {
                IpProtocol = "tcp",
                //The beginning and end of the port range. This example specifies a single port, 3389, which is used to communicate with Windows over RDP.
                //it should be changed if u launch a linux instance (use 22 insted )
                FromPort = 3389,
                ToPort   = 3389,
                IpRanges = ranges
            };
            //Create and initialize an AuthorizeSecurityGroupIngressRequest object.

            var ingressRequest = new AuthorizeSecurityGroupIngressRequest();

            ingressRequest.GroupId = mySG.GroupId;
            ingressRequest.IpPermissions.Add(ipPermission);
            //Pass the request object to the AuthorizeSecurityGroupIngress method, which returns an AuthorizeSecurityGroupIngressResponse object.
            var ingressResponse = ec2Client.AuthorizeSecurityGroupIngress(ingressRequest);

            Console.WriteLine("New RDP rule for: " + ipRange);

            //Create and initialize a network interface.for lunch enstance
            string subnetID = "subnet-048d6c59";

            List <string> groups = new List <string>()
            {
                mySG.GroupId
            };
            var eni = new InstanceNetworkInterfaceSpecification()
            {
                DeviceIndex = 0,
                SubnetId    = subnetID,
                Groups      = groups,
                AssociatePublicIpAddress = true
            };
            List <InstanceNetworkInterfaceSpecification> enis = new List <InstanceNetworkInterfaceSpecification>()
            {
                eni
            };

            string amiID       = "ami-06a0d33fc8d328de0";
            string keyPairName = "my-sample-key";

            var launchRequest = new RunInstancesRequest()
            {
                ImageId           = amiID,
                InstanceType      = "m3.large",
                MinCount          = 1,
                MaxCount          = 1,
                KeyName           = keyPairName,
                NetworkInterfaces = enis
            };

            //launch
            RunInstancesResponse launchResponse = ec2Client.RunInstances(launchRequest);

            List <String> instanceIds = new List <string>();

            foreach (Instance instance in launchResponse.Reservation.Instances)
            {
                Console.WriteLine(instance.InstanceId);
                instanceIds.Add(instance.InstanceId);
            }
            //check the status of the enstance
            var instanceRequest = new DescribeInstancesRequest();

            instanceRequest.InstanceIds = new List <string>();
            instanceRequest.InstanceIds.AddRange(instanceIds);
            var response = ec2Client.DescribeInstances(instanceRequest);

            Console.WriteLine(response.Reservations[0].Instances[0].State.Name);
        }
示例#13
0
        public void launch()
        {
            //instance started.
            if (string.IsNullOrEmpty(_instanceId) == false)
            {
                return;
            }

            try
            {
                RunInstancesRequest request = new RunInstancesRequest();

                request.ImageId  = _amiId;
                request.MinCount = 1;
                request.MaxCount = 1;

                if (_defaultSecurityGroup == false)
                {
                    request.SecurityGroup.Add(_securityGroups);
                }
                else
                {
                    if (securitryGroupExistOnServer() == false)
                    {
                        createSecurityGroup();
                    }
                    request.SecurityGroup.Add(_securityGroups);
                }

                string keyPath = CAwsConfig.Instance.getKeyFilePath(_keyPairName);
                if (string.IsNullOrEmpty(keyPath) == true ||
                    File.Exists(keyPath) == false)
                {
                    if (keyExistOnServer() == false)
                    {
                        createKayPair();
                    }
                }
                request.KeyName = _keyPairName;

                RunInstancesResponse response = _service.RunInstances(request);
                if (response.IsSetRunInstancesResult())
                {
                    RunInstancesResult runInstancesResult = response.RunInstancesResult;
                    if (runInstancesResult.IsSetReservation())
                    {
                        if (runInstancesResult.Reservation.RunningInstance[0].IsSetInstanceId())
                        {
                            _instanceId = runInstancesResult.Reservation.RunningInstance[0].InstanceId;
                        }
                        if (runInstancesResult.Reservation.RunningInstance[0].IsSetPublicDnsName())
                        {
                            _publicDns = runInstancesResult.Reservation.RunningInstance[0].PublicDnsName;
                        }
                    }
                }

                if (string.IsNullOrEmpty(_instanceId) == true)
                {
                    throw new Exception("No instance id is returned.");
                }

                //return after the instance started up
                bool pending = true;
                while (pending == true)
                {
                    System.Threading.Thread.Sleep(5 * 1000);

                    DescribeInstancesRequest describeRequest = new DescribeInstancesRequest();
                    describeRequest.InstanceId.Add(_instanceId);
                    DescribeInstancesResponse describeResponse = _service.DescribeInstances(describeRequest);
                    DescribeInstancesResult   describeResult   = describeResponse.DescribeInstancesResult;

                    if (describeResult.Reservation.Count != 1)
                    {
                        throw new Exception("more than one instance with the same id");
                    }
                    if (describeResult.Reservation[0].RunningInstance.Count != 1)
                    {
                        throw new Exception("more than one running instance has the same id");
                    }

                    pending = describeResult.Reservation[0].RunningInstance[0].InstanceState.Name != "running";
                }
            }
            catch (AmazonEC2Exception ex)
            {
                throw new Exception("Caught Exception: " + ex.XML);
            }
        }
示例#14
0
        private void btnServerStart_Click(object sender, EventArgs e)
        {
            this.btnRefreshStatus.Enabled = false;
            this.btnServerStart.Enabled   = false;
            this.btnServerStopAll.Enabled = false;

            //Stop any other ones running first...
            this.btnServerStopAll_Click(null, null);

            try {
                Configuration configuration           = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                string        AMI                     = configuration.AppSettings.Settings["AMI"].Value;
                string        IP                      = configuration.AppSettings.Settings["IPAddress"].Value;
                string        type                    = configuration.AppSettings.Settings["InstanceType"].Value;
                string        securityGroup           = configuration.AppSettings.Settings["SecurityGroup"].Value;
                string        urlToStartupPackage     = "WZA_startupPackageURL=" + configuration.AppSettings.Settings["URLToStartupPackage"].Value;
                bool          shouldUseStartupPackage = bool.Parse(configuration.AppSettings.Settings["ShouldUseStartupPackage"].Value);

                this.statusStripLbl.Text = "Starting a Wowza server - " + DateTime.Now.ToShortTimeString();
                RunInstancesRequest req = new RunInstancesRequest();
                req.EbsOptimized = false;
                req.ImageId      = AMI;
                req.InstanceType = InstanceType.FindValue(type);
                req.MaxCount     = 1;
                req.MinCount     = 1;
                if (shouldUseStartupPackage)
                {
                    byte[] encbuff = System.Text.Encoding.UTF8.GetBytes(urlToStartupPackage);
                    req.UserData = Convert.ToBase64String(encbuff);
                }
                req.SecurityGroupIds = new List <string> {
                    securityGroup
                };
                RunInstancesResponse response = this.EC2.RunInstances(req);

                //wait
                AssociateAddressRequest addressReq = new AssociateAddressRequest();
                Instance latestInstance            = response.Reservation.Instances.OrderBy(o => o.LaunchTime).FirstOrDefault();

                int giveUpCount = 0;
                while (giveUpCount < 20)
                {
                    var statusRequest = new DescribeInstanceStatusRequest {
                        InstanceIds = { latestInstance.InstanceId }
                    };

                    var result = this.EC2.DescribeInstanceStatus(statusRequest);
                    if (result.InstanceStatuses.Count > 0 && result.InstanceStatuses[0].InstanceState.Code == 16)
                    {
                        break;
                    }

                    this.GetStatus(false);
                    giveUpCount++;

                    int timeout = 0;
                    while (timeout < 1000)
                    {
                        this.statusStripLbl.Text = "Waiting for the Wowza server to start- " + DateTime.Now.ToShortTimeString();
                        Application.DoEvents();
                        System.Threading.Thread.Sleep(100);
                        timeout++;
                    }
                }

                this.statusStripLbl.Text = "Associated the IP address " + IP + " to the new server - " + DateTime.Now.ToShortTimeString();

                addressReq.InstanceId = latestInstance.InstanceId;
                addressReq.PublicIp   = IP;
                AssociateAddressResponse addressResponse = this.EC2.AssociateAddress(addressReq);

                this.GetStatus(false);
            } catch (Exception ex) {
                this.statusStripLbl.Text = "Caught Exception: " + ex.Message;
            }

            this.btnRefreshStatus.Enabled = true;
            this.btnServerStart.Enabled   = true;
            this.btnServerStopAll.Enabled = true;
        }
示例#15
0
        public IEnumerable <string> CreateInstances(AwsBootstrapOptionsValues request)
        {
            RunInstancesResponse runResponse = _client.RunInstances(request.InstanceRequest);

            return(runResponse.Reservation.Instances.Select(x => x.InstanceId));
        }