public EC2Controller(IConfiguration configuration)
        {
            var region          = configuration["CI:AWSRegion"];
            var accessKeyId     = configuration["CI:AWSAccessKey"];
            var secretAccessKey = configuration["CI:AWSSecretKey"];

            imageId            = configuration["CI:DefaultAMI"];
            serverKeyId        = configuration["CI:SSHKeyPair"];
            instanceType       = InstanceType.FindValue(configuration["CI:InstanceType"]);
            subnet             = configuration["CI:AWSSubnet"];
            securityGroup      = configuration["CI:AWSSecurityGroup"];
            rootFileSystemSnap = configuration["CI:RootFileSystemSnap"];
            rootFileSystemPath = configuration["CI:RootFileSystemPath"];
            defaultVolumeSize  = Convert.ToInt32(configuration["CI:DefaultVolumeSizeGiB"]);
            encryptVolumes     = Convert.ToBoolean(configuration["CI:EncryptVolumes"]);
            allowHibernate     = Convert.ToBoolean(configuration["CI:UseHibernate"]);

            // TODO: should *all* the variables be checked here
            if (string.IsNullOrEmpty(region) || string.IsNullOrEmpty(accessKeyId) ||
                string.IsNullOrEmpty(secretAccessKey) || string.IsNullOrEmpty(imageId))
            {
                Configured = false;
                return;
            }

            if (allowHibernate && !encryptVolumes)
            {
                throw new ArgumentException("Encryption must be enabled if hibernate is enabled");
            }

            // A quick sanity check on the volume sizes
            if (defaultVolumeSize < 5 || defaultVolumeSize > 1000)
            {
                throw new ArgumentException("Volume size should be between 5 and 1000 gigabytes");
            }

            ec2Client = new AmazonEC2Client(new BasicAWSCredentials(accessKeyId, secretAccessKey), new AmazonEC2Config()
            {
                RegionEndpoint       = RegionEndpoint.GetBySystemName(region),
                AuthenticationRegion = region
            });

            Configured = true;
        }
예제 #2
0
        public bool request_spot(string instance_type, string availability_zone, string spot_price, string key_tag)
        {
            write_log(region + " に対してスポットリクエストを作成しています。");
            int nn = setting_.getValueInt("common", "request_spot_width_of_minutes");

            try
            {
                InstanceNetworkInterfaceSpecification instanceNetworkInterfaceSpecification = new InstanceNetworkInterfaceSpecification();
                instanceNetworkInterfaceSpecification.DeviceIndex = 0;
                instanceNetworkInterfaceSpecification.SubnetId    = subnet_ids[availability_zone];
                instanceNetworkInterfaceSpecification.Groups.Add(security_group_id);
                instanceNetworkInterfaceSpecification.AssociatePublicIpAddress = true;

                LaunchSpecification launchSpecification = new LaunchSpecification();
                launchSpecification.ImageId      = image_id;
                launchSpecification.KeyName      = Helper.build_name(setting_, key_tag);
                launchSpecification.InstanceType = InstanceType.FindValue(instance_type);
                launchSpecification.Placement    = new SpotPlacement(region + availability_zone);
                launchSpecification.NetworkInterfaces.Add(instanceNetworkInterfaceSpecification);

                var client   = get_client();
                var spot_req = new RequestSpotInstancesRequest();
                spot_req.SpotPrice           = spot_price;
                spot_req.InstanceCount       = 1;
                spot_req.Type                = SpotInstanceType.OneTime;
                spot_req.ValidUntil          = DateTime.Now.AddMinutes(nn);
                spot_req.LaunchSpecification = launchSpecification;
                var query_res = client.RequestSpotInstances(spot_req);

                spot_request_id = query_res.SpotInstanceRequests[0].SpotInstanceRequestId;
            }
            catch (Exception ex)
            {
                write_log("ERROR: " + ex.ToString());
                return(false);
            }
            return(true);
        }
예제 #3
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;
        }