Describes an instance.
        public void GetSecurityGroupMap_Ok()
        {
            var instances = new List<Instance>();
            for (int sgCount = 0; sgCount < 3; sgCount++)
            {
                var instance = new Instance {InstanceId = string.Format("i-{0}", sgCount)};
                for (int i = 0; i < sgCount; i++)
                {
                    instance.SecurityGroups.Add(new GroupIdentifier {GroupId = string.Format("sg-{0}", i)});
                }
                instances.Add(instance);
            }

            Ec2Mock.Setup(x => x.DescribeSecurityGroups(It.IsAny<DescribeSecurityGroupsRequest>()))
                   .Returns((DescribeSecurityGroupsRequest request) => new DescribeSecurityGroupsResponse
                   {
                       SecurityGroups = request.GroupIds.Select(x => new SecurityGroup {GroupId = x}).ToList()
                   });

            Dictionary<string, List<SecurityGroup>> map = SecurityGroupService.GetSecurityGroupMap(instances);
            for (int sgCount = 0; sgCount < 3; sgCount++)
            {
                map[string.Format("i-{0}", sgCount)].Count.Should().Be(sgCount);
            }
        }
 public IEnumerable<SecurityGroup> GetSecurityGroups(Instance instance)
 {
     var securityGroupIds = instance.SecurityGroups.Select(x => x.GroupId);
     var request = new DescribeSecurityGroupsRequest {GroupIds = securityGroupIds.ToList()};
     var response = _ec2Client.DescribeSecurityGroups(request);
     return response.SecurityGroups;
 }
 public Image GetImage(Instance instance)
 {
     var imageId = instance.ImageId;
     var request = new DescribeImagesRequest {ImageIds = new List<string> {imageId}};
     var response = _ec2Client.DescribeImages(request);
     return response.Images.FirstOrDefault();
 }
Example #4
0
        void UpdateUI()
        {
            dispatcherTimer.Start();
            bool  isChangingState = false;
            Regex searchRegex     = new Regex(@"^remote ((?:\d+\.?)+) (\d+)", RegexOptions.Multiline);

            using (var awsClient = GetClient())
            {
                var req = new Amazon.EC2.Model.DescribeInstancesRequest();
                req.InstanceIds.Add(settings["instance_id"]);
                var response = awsClient.DescribeInstances(req);
                targetInstance        = response.Reservations[0].Instances[0];
                Instances.ItemsSource = new Amazon.EC2.Model.Instance[] { targetInstance };
                if ((new int[] { 0, 32, 64 }).Contains(targetInstance.State.Code))
                {
                    ActionButton.IsEnabled = false;
                    isChangingState        = true;
                }
            }

            if (!isChangingState)
            {
                dispatcherTimer.Stop();
                ActionButton.IsEnabled = true;
                ActionButton.Content   = GetInstanceAction(targetInstance);
                ConfigureVPN(targetInstance);
            }
        }
Example #5
0
        public static string GetEC2PropFromString(string input, Amazon.EC2.Model.Instance i)
        {
            string result = "";

            input = input.Replace(" ", string.Empty);

            string[] inputArr = input.Split('=');
            if (inputArr.Length > 1)
            {
                if (inputArr[0].ToLower() == "tag")
                {
                    result = GetEC2Tag(i.Tags, inputArr[1]);
                }
            }
            else
            {
                switch (input.ToLower())
                {
                case "architecture":
                    result = i.Architecture;
                    break;

                case "blockdevicemappings":
                    result = GetBlockDeviceMappings(i.BlockDeviceMappings, "all");
                    break;

                case "blockdevicenames":
                    result = GetBlockDeviceMappings(i.BlockDeviceMappings, "name");
                    break;

                case "blockdevicevolumeids":
                    result = GetBlockDeviceMappings(i.BlockDeviceMappings, "volumeid");
                    break;

                case "ebsoptimized":
                    if (i.EbsOptimized != null)
                    {
                        result = i.EbsOptimized.ToString();
                    }
                    break;

                case "enasupport":
                    if (i.EnaSupport != null)
                    {
                        result = i.EnaSupport.ToString();
                    }
                    break;

                case "hypervisor":
                    result = i.Hypervisor;
                    break;

                case "iaminstanceprofile":
                    if (i.IamInstanceProfile != null)
                    {
                        result = i.IamInstanceProfile.Id;
                    }
                    break;

                case "instanceid":
                    result = i.InstanceId;
                    break;

                case "instancetype":
                    result = i.InstanceType;
                    break;

                case "kernelid":
                    result = i.KernelId;
                    break;

                case "keyname":
                    result = i.KeyName;
                    break;

                case "launchtime":
                    result = i.LaunchTime.ToString("yyyy-MM-dd HH:mm:ss");
                    break;

                case "monitoring":
                    if (i.Monitoring != null)
                    {
                        result = i.Monitoring.State.Value;
                    }
                    break;

                case "networkinterfaces":
                    result = GetNetworkInterfaces(i.NetworkInterfaces, "all");
                    break;

                case "networkinterfaceids":
                    result = GetNetworkInterfaces(i.NetworkInterfaces, "networkinterfaceIds");
                    break;

                case "networkinterfaceprivateips":
                    result = GetNetworkInterfaces(i.NetworkInterfaces, "networkinterfaceprivateips");
                    break;

                case "placement":
                    result = "";
                    break;

                case "platform":
                    if (i.Platform != null)
                    {
                        result = i.Platform.Value;
                    }
                    break;

                case "privatednsname":
                    result = i.PrivateDnsName;
                    break;

                case "privateipaddress":
                    result = i.PrivateIpAddress;
                    break;

                case "publicdnsname":
                    result = i.PublicDnsName;
                    break;

                case "publicipaddress":
                    result = i.PublicIpAddress;
                    break;

                case "rootdevicename":
                    result = i.RootDeviceName;
                    break;

                case "rootdevicetype":
                    if (i.RootDeviceType != null)
                    {
                        result = i.RootDeviceType.Value;
                    }
                    break;

                case "securitygroups":
                    result = GetEC2SecurityGroups(i.SecurityGroups);
                    break;

                case "snapshots":
                    result = GetSnapshots(i.BlockDeviceMappings, "all");
                    break;

                case "stackcreationtime":
                    string stackName = GetEC2Tag(i.Tags, Properties.Settings.Default.StackNameTag);
                    result = GetStackCreationTime(stackName);
                    break;

                case "stackname":
                    result = stackName = GetEC2Tag(i.Tags, Properties.Settings.Default.StackNameTag);
                    break;

                case "stackid":
                    result = stackName = GetEC2Tag(i.Tags, Properties.Settings.Default.StackIdTag);
                    break;

                case "stacklogicalid":
                    result = stackName = GetEC2Tag(i.Tags, Properties.Settings.Default.StackLogicalIdTag);
                    break;

                case "subnetid":
                    result = i.SubnetId;
                    break;

                case "state":
                    if (i.State != null)
                    {
                        result = i.State.Name;
                    }
                    break;

                case "imageid":
                    result = i.ImageId;
                    break;

                case "vpcid":
                    result = i.VpcId;
                    break;

                case "name":
                    if (i.Tags != null)
                    {
                        result = GetEC2Tag(i.Tags, "name");
                    }
                    break;

                default:
                    break;
                }
            }

            return(result);
        }
Example #6
0
 public void StopInstance(Instance instance)
 {
     var stopRequest = new StopInstancesRequest(new List<string> { instance.InstanceId });
     var stopResult = _client.StopInstances(stopRequest);
     //var stateChangeList = stopResult.StoppingInstances;
 }
        /// <summary>
        /// Gets the data for EC2 Instances in a given Profile and Region.
        /// </summary>
        /// <param name="aprofile"></param>
        /// <param name="Region2Scan"></param>
        /// <returns></returns>
        public DataTable GetEC2Instances(string aprofile, string Region2Scan)
        {
            DataTable ToReturn = AWSTables.GetComponentTable("EC2");
            RegionEndpoint Endpoint2scan = RegionEndpoint.USEast1;
            Amazon.Runtime.AWSCredentials credential;
            credential = new Amazon.Runtime.StoredProfileAWSCredentials(aprofile);
            //Convert the Region2Scan to an AWS Endpoint.
            foreach (var aregion in RegionEndpoint.EnumerableAllRegions)
            {
                if (aregion.DisplayName.Equals(Region2Scan))
                {
                    Endpoint2scan = aregion;
                    continue;
                }
            }

            var ec2 = new Amazon.EC2.AmazonEC2Client(credential, Endpoint2scan);
            string accountid = GetAccountID(aprofile);
            var request = new DescribeInstanceStatusRequest();



            

            request.IncludeAllInstances = true;
            DescribeInstanceStatusResponse instatresponse = new DescribeInstanceStatusResponse();
            var indatarequest = new DescribeInstancesRequest();
            try
            {
                instatresponse = ec2.DescribeInstanceStatus(request);
            }
            catch (Exception ex)
            {
                string test = "";//Quepaso? 
            }

            //Get a list of the InstanceIDs.
            foreach (var instat in instatresponse.InstanceStatuses)
            {
                indatarequest.InstanceIds.Add(instat.InstanceId);
                indatarequest.InstanceIds.Sort();
            }

            DescribeInstancesResponse DescResult = ec2.DescribeInstances();
           
            int count = instatresponse.InstanceStatuses.Count();

            //Build data dictionary of instances
            Dictionary<String, Instance> Bunchadata = new Dictionary<string, Instance>();
            foreach (var urtburgle in DescResult.Reservations)
            {
                foreach (var instancedata in urtburgle.Instances)
                {
                    try { Bunchadata.Add(instancedata.InstanceId, instancedata); }
                    catch (Exception ex) {
                        var ff ="";//a duplicate??
                    };
                }
            }

            //Go through list of instances...
            foreach (var instat in instatresponse.InstanceStatuses)
            {
                
                string instanceid = instat.InstanceId;
                Instance thisinstance = new Instance();
                try
                {
                    thisinstance = Bunchadata[instanceid];
                }
                catch(Exception ex)
                {

                    continue;
                }
                DataRow thisinstancedatarow = ToReturn.NewRow();
                //Collect the datases
                string instancename = "";
                var status = instat.Status.Status;
                string AZ = instat.AvailabilityZone;
                var istate = instat.InstanceState.Name;

                string profile = aprofile;
                string myregion = Region2Scan;
                int eventnumber = instat.Events.Count();
                List<string> eventlist = new List<string>();
                var reservations = DescResult.Reservations;

                var myinstance = new Reservation();

                var atreq = new DescribeInstanceAttributeRequest();
                atreq.InstanceId = instanceid;
                atreq.Attribute = "disableApiTermination";
                var atresp = ec2.DescribeInstanceAttribute(atreq).InstanceAttribute;
                string TerminationProtection = atresp.DisableApiTermination.ToString();

                List<String> innies = new List<String>();
                foreach (Reservation arez in DescResult.Reservations)
                {
                    var checky = arez.Instances[0].InstanceId;
                    innies.Add(checky);
                    if (arez.Instances[0].InstanceId.Equals(instanceid))
                    {
                        myinstance = arez;
                    }
                }
                innies.Sort();

                List<string> tags = new List<string>();
                var loadtags = thisinstance.Tags.AsEnumerable();
                foreach (var atag in loadtags)
                {
                    tags.Add(atag.Key + ": " + atag.Value);
                    if (atag.Key.Equals("Name")) instancename = atag.Value;
                }

                Dictionary<string, string> taglist = new Dictionary<string, string>();
                foreach (var rekey in loadtags)
                {
                    taglist.Add(rekey.Key, rekey.Value);
                }

                if (eventnumber > 0)
                {
                    foreach (var anevent in instat.Events)
                    {
                        eventlist.Add(anevent.Description);
                    }
                }
                String platform = "";
                try { platform = thisinstance.Platform.Value; }
                catch { platform = "Linux"; }
                if (String.IsNullOrEmpty(platform)) platform = "Linux";


                String Priv_IP = "";
                try { Priv_IP = thisinstance.PrivateIpAddress; }
                catch { }
                if (String.IsNullOrEmpty(Priv_IP))
                {
                    Priv_IP = "?";
                }
                
                String disinstance = thisinstance.InstanceId;

                String publicIP = "";
                try { publicIP = thisinstance.PublicIpAddress; }
                catch { }
                if (String.IsNullOrEmpty(publicIP)) publicIP = "";

                

                String publicDNS = "";
                try { publicDNS = thisinstance.PublicDnsName; }
                catch { }
                if (String.IsNullOrEmpty(publicDNS)) publicDNS = "";

                string myvpcid = "";
                try
                { myvpcid = thisinstance.VpcId; }
                catch { }
                if (String.IsNullOrEmpty(myvpcid)) myvpcid = "";
                

                string mysubnetid = "";
                try { mysubnetid = thisinstance.SubnetId; }
                catch { }
                if (String.IsNullOrEmpty(mysubnetid)) mysubnetid = "";


                //Virtualization type (HVM, Paravirtual)
                string ivirtType = "";
                try
                { ivirtType = thisinstance.VirtualizationType; }
                catch { }
                if (String.IsNullOrEmpty(ivirtType)) ivirtType = "?";

                // InstanceType (m3/Large etc)
                String instancetype = "";
                try
                { instancetype = thisinstance.InstanceType.Value; }
                catch { }
                if (String.IsNullOrEmpty(instancetype)) instancetype = "?";


                //Test section to try to pull out AMI data
                string AMI = "";
                string AMIName = "";
                string AMIDesc = "";
                string AMILocation = "";
                string AMIState = "";
                try { AMI = thisinstance.ImageId; }
                catch { }
                if (string.IsNullOrEmpty(AMI)) AMI = "";
                else
                {
                    DescribeImagesRequest DIR = new DescribeImagesRequest();
                    DIR.ImageIds.Add(AMI);
                    var imresp = ec2.DescribeImages(DIR);
                    var idata = imresp.Images;
                    try {
                        if (idata.Count > 0)
                        {
                            AMIDesc = idata[0].Description;
                            AMIName = idata[0].Name;
                            AMILocation = idata[0].ImageLocation;
                            AMIState = idata[0].State;

                        }
                        else
                        {
                            AMIDesc = "na";
                            AMIName = "na";
                            AMILocation = "na";
                            AMIState = "na";
                        }
                        if (String.IsNullOrEmpty(AMIDesc)) { AMIDesc = ""; }
                        if (String.IsNullOrEmpty(AMIName)) { AMIName = ""; }
                    }
                    catch(Exception ex)
                    {
                        string whyforerror = ex.Message;
                    }
                 
                }

                //
                var SGs = thisinstance.SecurityGroups;
                List<string> SGids = new List<string>();
                List<String> SGNames = new List<string>();
                foreach (var wabbit in SGs)
                {
                    SGids.Add(wabbit.GroupId);
                    SGNames.Add(wabbit.GroupName);
                }



                //Add to table
                if (SGids.Count < 1) SGids.Add("NullOrEmpty");
                if (SGNames.Count < 1) SGNames.Add("");
                if (String.IsNullOrEmpty(SGids[0])) SGids[0] = "NullOrEmpty";
                if (String.IsNullOrEmpty(SGNames[0])) SGNames[0] = "";

                if (String.IsNullOrEmpty(instancename)) instancename = "";


                //EC2DetailsTable.Rows.Add(accountid, profile, myregion, instancename, instanceid, AMI, AMIDesc, AZ, platform, status, eventnumber, eventlist, tags, Priv_IP, publicIP, publicDNS, istate, ivirtType, instancetype, sglist);
                //Is list for Profile and Region, so can key off of InstanceID. In theory InstanceID is unique

                //Build our dictionary of values and keys for this instance  This is dependent on the table created by GetEC2DetailsTable()
                Dictionary<string, string> datafields = new Dictionary<string, string>();
                thisinstancedatarow["AccountID"] = accountid;
                thisinstancedatarow["Profile"] = profile;
                thisinstancedatarow["Region"] = myregion;
                thisinstancedatarow["InstanceName"] = instancename;
                thisinstancedatarow["InstanceID"] = instanceid;
                thisinstancedatarow["TerminationProtection"] = TerminationProtection;
                thisinstancedatarow["AMI"] = AMI;
                thisinstancedatarow["AMIState"] = AMIState;
                thisinstancedatarow["AMILocation"] = AMILocation;
                thisinstancedatarow["AMIDescription"] = AMIDesc;
                thisinstancedatarow["AvailabilityZone"] = AZ;
                thisinstancedatarow["Status"] = status;
                thisinstancedatarow["Events"] = eventnumber.ToString();
                thisinstancedatarow["EventList"] = List2String(eventlist);
                thisinstancedatarow["Tags"] = List2String(tags);
                thisinstancedatarow["PrivateIP"] = Priv_IP;
                thisinstancedatarow["PublicIP"] = publicIP;
                thisinstancedatarow["PublicDNS"] = publicDNS;
                thisinstancedatarow["PublicDNS"] = publicDNS;
                thisinstancedatarow["VPC"] = myvpcid;
                thisinstancedatarow["SubnetID"] = mysubnetid;
                thisinstancedatarow["InstanceState"] = istate.Value;
                thisinstancedatarow["VirtualizationType"] = ivirtType;
                thisinstancedatarow["InstanceType"] = instancetype;
                thisinstancedatarow["SecurityGroups"] = List2String(SGids);
                thisinstancedatarow["SGNames"] = List2String(SGNames);
                //Add this instance to the data returned.
                ToReturn.Rows.Add(thisinstancedatarow);


            }//End for of instances



            return ToReturn;
        }//EndGetEC2
Example #8
0
        private void Reconnect(Instance runningInstance)
        {
            this.Name = runningInstance.Tags.First(x => x.Key == "Name").Value;

            this.PublicIp = runningInstance.PublicIpAddress;
            this.PublicIp = string.IsNullOrWhiteSpace(this.PublicIp) ? null : this.PublicIp;

            this.InstanceState = runningInstance.State.Name;

            var uniqueKey = runningInstance.Tags.FirstOrDefault(x => x.Key == "UniqueKey");
            if (uniqueKey == null)
                this.uniqueKey = new Guid().ToString();
            else
                this.uniqueKey = uniqueKey.Value;

            // TODO: Fetch AMI and spot bid amount. 
            var size = Ec2Connection.InstanceSizes.FirstOrDefault(x => x.Key == runningInstance.InstanceType);
            this.Specification = new InstanceSpecification(null, size, runningInstance.Placement.AvailabilityZone);
            this.bidRequestId = runningInstance.SpotInstanceRequestId;
        }
Example #9
0
        //public Ec2Instance(AmazonEC2Client client, string instanceId)
        //{
        //    this.Client = client;
        //    this.InstanceId = instanceId;

        //    // TODO: Get name from tag (and other specification stuff)
        //    this.Name = "TODO";
        //    this.state = CreationState.CreatedNotSetup;

        //    this.Logger = new StubLogger();
        //}

        public Ec2Instance(AmazonEC2Client client, Config config, Instance runningInstance)
        {
            this.Client = client;
            this.config = config;
            this.InstanceId = runningInstance.InstanceId;

            this.Reconnect(runningInstance);

            this.state = CreationState.IsSetup;

            this.Logger = new StubLogger();
        }
Example #10
0
        private AWSInstance GetAWSInstanceFromInstance(Instance instance, AWSVolume[] volumes, AWSAvailabilityZone[] zones, Pricing pricing)
        {
            var tags = new List<AWSTag>();
            string name = null;
            if (instance.Tags != null)
            {
                foreach (var tag in instance.Tags)
                {
                    if (tag.Key == "Name" && tag.Value != null)
                    {
                        name = tag.Value;
                    }
                    else
                    {
                        tags.Add(new AWSTag { Key = tag.Key, Value = tag.Value });
                    }
                }
            }

            var awsInstanceVolumes = new List<AWSInstanceVolume>();
            foreach (var mapping in instance.BlockDeviceMappings)
            {
                var volume = volumes.SingleOrDefault(_ => _.VolumeId == mapping.Ebs.VolumeId);
                var awsInstanceVolume = new AWSInstanceVolume()
                                    {
                                        DeviceName = mapping.DeviceName,
                                        EbsVolumeId = mapping.Ebs.VolumeId,
                                        EbsStatus = mapping.Ebs.Status.Value,
                                        VolumeSizeInGB = volume != null ? volume.Size : double.NaN,
                                        VolumeType = volume != null ? volume.VolumeType : null,
                                    };
                awsInstanceVolumes.Add(awsInstanceVolume);
            }

            var instanceType = instance.InstanceType.Value;
            var availabilityZone = instance.Placement.AvailabilityZone;
            var region = zones.Single(_ => _.Name.Equals(availabilityZone)).Region;
            var osTypeTag = tags.SingleOrDefault(_ => _.Key == Constants.OSTypes.TAG_NAME);
            var osType = osTypeTag != null ? osTypeTag.Value : Constants.OSTypes.WINDOWS_BASE; // defaulting to windows base b/c that's the common case

            var pricePerHour = pricing != null ? pricing.EC2Pricing.GetPrice(instanceType, osType, region) : double.NaN;
            var pricePerMonth = pricing != null ? pricing.EBSPricing.GetPrice(region, awsInstanceVolumes) : double.NaN;

            var ret = new AWSInstance()
                          {
                              InstanceId = instance.InstanceId,
                              ImageId = instance.ImageId,
                              AvailabilityZone = availabilityZone,
                              Region = region,
                              Platform = AWSInstance.GetPlatformFromString(instance.Platform == null ? null : instance.Platform.Value),
                              OSType = osTypeTag != null ? osTypeTag.Value : "Unknown - costed as Windows Base",
                              Volumes = awsInstanceVolumes.ToArray(),
                              Name = name,
                              IpAddress = instance.PublicIpAddress,
                              PrivateIpAddress = instance.PrivateIpAddress,
                              InstanceState = AWSInstance.GetStateFromString(instance.State.Name),
                              InstanceType = instanceType,
                              PricePerHourRunning = pricePerHour,
                              PricePerMonthStorage = pricePerMonth,
                              Tags = tags.ToArray(),
                          };

            return ret;
        }