Пример #1
0
        /// <summary>
        /// Actions on service start
        /// </summary>
        private static void OnStartEvent()
        {
            try
            {
                List <RunningInstance> instances = ServersWatcher.Instances;

                EC2Helper       ec2Helper = EC2Helper.Make();
                RunningInstance instance  = ec2Helper.GetCurrentInstance(instances);

                if (instance == null)
                {
                    return;
                }

                // Assign elastic IP if it is free and tag exists
                var tag = ec2Helper.GetElasticIpTag(instance);
                if (tag != null)
                {
                    ec2Helper.AssignElasticIpByTag(instance, tag);
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex.Message, EventLogEntryType.Error);
                throw new Exception(ex.Message, ex);
            }
        }
Пример #2
0
        private static RunningInstance WaitForInstanceToStartUp(AmazonEC2 ec2Client, string instanceId)
        {
            var describeRequest = new DescribeInstancesRequest()
            {
                InstanceId = new List <string>()
                {
                    instanceId
                }
            };

            for (int tries = 0; tries < 40; tries++)
            {
                Thread.Sleep(10 * 1000);

                var result = ec2Client.DescribeInstances(describeRequest).DescribeInstancesResult;
                if (result.Reservation.Count != 1 && result.Reservation[0].RunningInstance.Count != 1)
                {
                    return(null);
                }

                RunningInstance instance = result.Reservation[0].RunningInstance[0];

                // Return the updated instance object if we're out of pending
                if (!instance.InstanceState.Name.Equals("pending"))
                {
                    return(instance);
                }
            }

            return(null);
        }
Пример #3
0
        private void StartRaisingEvents()
        {
            // If we're called when "Initializing" is true, set enabled to true
            if (IsSuspended())
            {
                _enabled = true;
                return;
            }

            // Don't start another instance if one is already runnings
            if (_cancellation != null)
            {
                return;
            }

            try
            {
                CancellationTokenSource cancellation = new CancellationTokenSource();
                RunningInstance         instance     = new RunningInstance(this, _directory, _includeSubdirectories, TranslateFlags(_notifyFilters), cancellation.Token);
                _enabled      = true;
                _cancellation = cancellation;
                instance.Start();
            }
            catch
            {
                _enabled      = false;
                _cancellation = null;
                throw;
            }
        }
Пример #4
0
        private static void ConsoleStartTest()
        {
            try
            {
                List <RunningInstance> instances = ServersWatcher.Instances;

                EC2Helper       ec2Helper = EC2Helper.Make();
                RunningInstance instance  = ec2Helper.GetCurrentInstance(instances);

                if (instance == null)
                {
                    return;
                }

                Console.WriteLine("Instance: {0}", ServersWatcher.GetInstanceName(instance));

                // Assign elastic IP if it is free and tag exists
                var tag = ec2Helper.GetElasticIpTag(instance);
                if (tag != null)
                {
                    Console.WriteLine("Tag value: {0}", tag.Value);
                    ec2Helper.AssignElasticIpByTag(instance, tag);
                }
                else
                {
                    Console.WriteLine("Tag not found");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Пример #5
0
        public static RunningInstance rebootInstance(this API_AmazonEC2 amazonEC2, RunningInstance runningInstance)
        {
            "Rebooting instance with ID: {0}".info(runningInstance.InstanceId);
            var ec2Client = amazonEC2.getEC2Client(runningInstance.Placement.AvailabilityZone.removeLastChar());
            var result    = ec2Client.RebootInstances(new RebootInstancesRequest()
                                                      .WithInstanceId(runningInstance.InstanceId));

            return(runningInstance);
        }
Пример #6
0
        /// <summary>
        /// Get list of running instances in region for
        /// web service URL in application config
        /// </summary>
        /// <returns></returns>
        static private List <RunningInstance> GetRunningInstances()
        {
            AppConfig.Refresh();
            AmazonEC2Config config = new AmazonEC2Config();

            config.ServiceURL = AppConfig.AWSServiceURL;

            AmazonEC2 ec2 = AWSClientFactory.CreateAmazonEC2Client(
                AppConfig.AWSAccessKey,
                AppConfig.AWSSecretKey,
                config
                );


            //list of running instances
            List <RunningInstance>  runningInstancesList = new List <RunningInstance>();
            DescribeInstancesResult serviceResult;

            if (!string.IsNullOrEmpty(AppConfig.FilterByTag))
            {
                RunningInstance currentInstance           = GetCurrentInstance(ec2);
                String          currentInstancegroupvalue = GetCurrentInstanceGroupValue(currentInstance);
                // ask service for descriptions
                serviceResult =
                    ec2.DescribeInstances(new DescribeInstancesRequest().WithFilter(new Filter().WithName("tag:" + AppConfig.FilterByTag).WithValue(currentInstancegroupvalue))).DescribeInstancesResult;
            }
            else
            {
                serviceResult =
                    ec2.DescribeInstances(new DescribeInstancesRequest()).DescribeInstancesResult;
            }

            if (serviceResult.IsSetReservation())
            {
                //reservation is a group of instances launched from the same console
                List <Reservation> reservationList = serviceResult.Reservation;
                foreach (Reservation reservation in reservationList)
                {
                    if (reservation.IsSetRunningInstance())
                    {
                        //with all instances in reservation
                        //This list contains not only running instances
                        List <RunningInstance> instancesList = reservation.RunningInstance;
                        foreach (RunningInstance instance in instancesList)
                        { //include in result only really running ones
                            if (RUNNING_STATE == instance.InstanceState.Code)
                            {
                                runningInstancesList.Add(instance);
                            }
                        }
                    }
                }
            }

            return(runningInstancesList);
        }
Пример #7
0
        private void StartInstances(AwsClientDetails clientDetails)
        {
            using (var helper = new EC2Helper(clientDetails))
            {
                RunningInstance instance = helper.DescribeInstance(InstanceId);
                Log.LogMessage(MessageImportance.Normal, "Got Instance {0} details", InstanceId);

                SetOutputProperties(instance);
            }
        }
Пример #8
0
 /// <summary>
 /// Retrieves current Amazon instance, check tags for ElasticIP and try to assign if it is possible.
 /// </summary>
 public void AssignElasticIpByTag(RunningInstance instance, Tag tag)
 {
     if (instance != null && tag != null)
     {
         if (IsElasticIpFree(tag.Value))
         {
             SetElasticIpToInstance(instance.InstanceId, tag.Value);
         }
     }
 }
Пример #9
0
 InstanceState Stop(RunningInstance instance)
 {
     using (var client = CreateClient())
     {
         var request = new StopInstancesRequest();
         request.InstanceId.Add(instance.InstanceId);
         var response = client.StopInstances(request);
         return(response.StopInstancesResult.StoppingInstances[0].CurrentState);
     }
 }
Пример #10
0
        public static RunningInstance showConsoleOut(this API_AmazonEC2 amazonEC2, RunningInstance runningInstance)
        {
            "Getting Console out instance with ID: {0}".info(runningInstance.InstanceId);
            var ec2Client        = amazonEC2.getEC2Client(runningInstance.Placement.AvailabilityZone.removeLastChar());
            var consoleOutResult = ec2Client.GetConsoleOutput(new GetConsoleOutputRequest()
                                                              .WithInstanceId(runningInstance.InstanceId));
            var consoleOut = consoleOutResult.GetConsoleOutputResult.ConsoleOutput.Output.base64Decode();

            consoleOut.showInCodeViewer(".bat");
            return(runningInstance);
        }
Пример #11
0
 /// <summary>
 /// 重启程序
 /// </summary>
 public static void RestartApplication()
 {
     try
     {
         RunningInstance.ReleaseMutex();//释放
         Process.Start(Application.ExecutablePath);
         Environment.Exit(-1);
     }
     catch (Exception)
     { }
 }
Пример #12
0
        /// <summary>
        /// Gets instance tag Groupvalue or NULL id if no tag found.
        /// </summary>
        /// <param name="instance">Amazon instance</param>
        /// <returns>Group Tag value or NULL</returns>

        public static String GetCurrentInstanceGroupValue(RunningInstance instance)
        {
            foreach (Tag tag in instance.Tag)
            {
                if (tag.Key.Equals(AppConfig.FilterByTag, StringComparison.OrdinalIgnoreCase))
                {
                    return(tag.Value);
                }
            }

            return(null);
        }
Пример #13
0
        /// <summary>
        /// Gets instance tag name or instance id if no tag found.
        /// </summary>
        /// <param name="instance">Amazon instance</param>
        /// <returns>Instance name</returns>
        public String GetInstanceName(RunningInstance instance)
        {
            foreach (Tag tag in instance.Tag)
            {
                if (tag.Key.Equals(TAG_INSTANCE_NAME, StringComparison.OrdinalIgnoreCase))
                {
                    return(tag.Value);
                }
            }

            return(instance.InstanceId);
        }
Пример #14
0
        /// <summary>
        /// Gets instance tag ElasticIP or NULL id if no tag found.
        /// </summary>
        /// <param name="instance">Amazon instance</param>
        /// <returns>ElasticIP or NULL</returns>
        public String GetElasticIpTagValue(RunningInstance instance)
        {
            foreach (Tag tag in instance.Tag)
            {
                if (tag.Key.Equals(TAG_ELASTIC_IP, StringComparison.OrdinalIgnoreCase))
                {
                    return(tag.Value);
                }
            }

            return(null);
        }
Пример #15
0
        /// <summary>
        /// Get value of Name tag or instance id if no Name tag found
        /// </summary>
        /// <param name="instance">Instance referance</param>
        /// <returns>value of Name tag or instance id if no Name tag found</returns>
        public static string GetInstanceName(RunningInstance instance)
        {
            foreach (Tag tag in instance.Tag)
            {
                if (tag.Key.Equals(TAG_INSTANCE_NAME))
                {
                    return(tag.Value);
                }
            }

            return(instance.InstanceId);
        }
        public static string GetInstanceFriendlyName(RunningInstance ins)
        {
            Tag nameTag = ins.Tag.Where(tag => tag.Key.ToLower() == "name").FirstOrDefault();

            if (nameTag != null)
            {
                return(nameTag.Value);
            }
            else
            {
                return(ins.InstanceId);
            }
        }
Пример #17
0
        /// <summary>
        /// Gets tag witn ElasticIP key or null
        /// </summary>
        /// <param name="instance">Instance to search in</param>
        /// <returns>ElasticIP tag or null if not found</returns>
        public Tag GetElasticIpTag(RunningInstance instance)
        {
            if (null != instance)
            {
                foreach (Tag tag in instance.Tag)
                {
                    if (tag.Key == TAG_ELASTIC_IP)
                    {
                        return(tag);
                    }
                }
            }

            return(null);
        }
Пример #18
0
        public static string getPassword(this API_AmazonEC2 amazonEC2, RunningInstance runningInstance, string pathToPemFile)
        {
            "Tests on  instance with ID: {0}".info(runningInstance.InstanceId);
            var ec2Client        = amazonEC2.getEC2Client(runningInstance.Placement.AvailabilityZone.removeLastChar());
            var passwordResponse = ec2Client.GetPasswordData(new GetPasswordDataRequest().WithInstanceId(runningInstance.InstanceId));

            "raw password data : {0}".info(passwordResponse.GetPasswordDataResult.ToXML());
            if (amazonEC2.ApiRsa.isNull())
            {
                amazonEC2.ApiRsa = new API_RSA(pathToPemFile);
            }
            var decryptedPassword = amazonEC2.ApiRsa.decryptPasswordUsingPem(passwordResponse.GetPasswordDataResult.PasswordData.Data);

            "decrypted password: {0}".info(decryptedPassword);
            return(decryptedPassword);
        }
Пример #19
0
 /// <summary>
 /// Checks if elastic IP is assigned
 /// </summary>
 /// <param name="instance">Amazon instance</param>
 /// <returns>True if ElasticIP is assigned to the current instance.</returns>
 public bool IsElasticIpAssigned(RunningInstance instance)
 {
     if (null != instance)
     {
         DescribeAddressesResult describeAddressesResult =
             _ec2.DescribeAddresses(new DescribeAddressesRequest()).DescribeAddressesResult;
         foreach (Address address in describeAddressesResult.Address)
         {
             if (instance.InstanceId.Equals(address.InstanceId, StringComparison.OrdinalIgnoreCase))
             {
                 return(true);
             }
         }
     }
     return(false);
 }
Пример #20
0
        /// <summary>
        /// Actions on timer event
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private static void OnTimerEvent(object source, ElapsedEventArgs e)
        {
            try
            {
                List <RunningInstance> instances = ServersWatcher.Instances;

                // Write running instances to hosts file
                HostsManager hostsMgr = new HostsManager();
                hostsMgr.OpenHostsFile();
                foreach (RunningInstance inst in instances)
                {
                    hostsMgr.AddRecord(inst.PrivateIpAddress, ServersWatcher.GetInstanceName(inst));
                }
                hostsMgr.CommitHostsFile();

                //Apply ElasticIP for current host:
                EC2Helper ec2Helper = EC2Helper.Make();

                RunningInstance instance = ec2Helper.GetCurrentInstance(instances);
                if (instance == null)
                {
                    return;
                }

                if (ec2Helper.IsElasticIpAssigned(instance))
                {
                    // ElasticIP assigned to instance, update tags
                    Tag tag = new Tag().WithKey(EC2Helper.TAG_ELASTIC_IP).WithValue(instance.IpAddress);
                    ec2Helper.AddTagToInstance(instance.InstanceId, tag);
                }
                else
                {
                    var tag = ec2Helper.GetElasticIpTag(instance);

                    // Delete tag if exists
                    if (tag != null)
                    {
                        ec2Helper.DeleteTag(instance.InstanceId, tag);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex.Message, EventLogEntryType.Error);
                throw new Exception(ex.Message, ex);
            }
        }
Пример #21
0
        private static void ConsoleInstanceTest()
        {
            try
            {
                List <RunningInstance> instances = ServersWatcher.Instances;

                //Apply ElasticIP for current host:
                EC2Helper ec2Helper = EC2Helper.Make();

                RunningInstance instance = ec2Helper.GetCurrentInstance(instances);
                if (instance == null)
                {
                    return;
                }

                Console.WriteLine("Instance: {0}", ServersWatcher.GetInstanceName(instance));

                if (ec2Helper.IsElasticIpAssigned(instance))
                {
                    Console.WriteLine("ElasticIP assigned to instance: {0}", instance.IpAddress);

                    // ElasticIP assigned to instance update tags
                    Tag tag = new Tag().WithKey(EC2Helper.TAG_ELASTIC_IP).WithValue(instance.IpAddress);
                    ec2Helper.AddTagToInstance(instance.InstanceId, tag);
                }
                else
                {
                    var tag = ec2Helper.GetElasticIpTag(instance);

                    // Delete tag if exists
                    if (tag != null)
                    {
                        Console.WriteLine("Deleting tad value: {0}", tag.Value);
                        ec2Helper.DeleteTag(instance.InstanceId, tag);
                    }
                    else
                    {
                        Console.WriteLine("Tag not found");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Пример #22
0
 private void SetOutputProperties(RunningInstance instance)
 {
     AmiLaunchIndex    = instance.AmiLaunchIndex;
     Architecture      = instance.Architecture;
     ImageId           = instance.ImageId;
     InstanceLifecycle = instance.InstanceLifecycle;
     if (instance.InstanceState != null)
     {
         InstanceStateCode = instance.InstanceState.Code;
         InstanceStateName = instance.InstanceState.Name;
     }
     InstanceType = instance.InstanceType;
     IpAddress    = instance.IpAddress;
     KernelId     = instance.KernelId;
     KeyName      = instance.KeyName;
     LaunchTime   = instance.LaunchTime;
     if (instance.Monitoring != null)
     {
         MonitoringState = instance.Monitoring.MonitoringState;
     }
     if (instance.Placement != null)
     {
         AvailabilityZone = instance.Placement.AvailabilityZone;
     }
     Platform              = instance.Platform;
     PrivateDnsName        = instance.PrivateDnsName;
     PublicDnsName         = instance.PublicDnsName;
     RamdiskId             = instance.RamdiskId;
     RootDeviceName        = instance.RootDeviceName;
     RootDeviceType        = instance.RootDeviceType;
     SpotInstanceRequestId = instance.SpotInstanceRequestId;
     if (instance.StateReason != null)
     {
         StateReason = instance.StateReason.Message;
     }
     StateTransitionReason = instance.StateTransitionReason;
     SubnetId = instance.SubnetId;
     VpcId    = instance.VpcId;
 }
Пример #23
0
        /// <summary>
        ///  Get running instances from Amazon for configured region.
        /// </summary>
        /// <returns>List of running instances</returns>
        public List <RunningInstance> GetRunningInstances()
        {
            // list running instances
            List <RunningInstance> runningInstances = new List <RunningInstance>();

            // ask service for descriptions
            DescribeInstancesResult serviceResult;

            if (!string.IsNullOrEmpty(AppConfig.FilterByTag))
            {
                RunningInstance currentInstance           = GetCurrentInstance();
                String          currentInstancegroupvalue = GetCurrentInstanceGroupValue(currentInstance);
                // ask service for descriptions
                serviceResult =
                    _ec2.DescribeInstances(new DescribeInstancesRequest().WithFilter(new Filter().WithName("tag:" + AppConfig.FilterByTag).WithValue(currentInstancegroupvalue))).DescribeInstancesResult;
            }
            else
            {
                serviceResult =
                    _ec2.DescribeInstances(new DescribeInstancesRequest()).DescribeInstancesResult;
            }

            // with all reservations
            // reservation is a group of instances launched with the same command
            foreach (Reservation reservation in serviceResult.Reservation)
            {
                // these are not only really running ones...
                foreach (RunningInstance instance in reservation.RunningInstance)
                {
                    // deal only with really running instances
                    if (instance.InstanceState.Code == RUNNING_STATE)
                    {
                        runningInstances.Add(instance);
                    }
                }
            }
            return(runningInstances);
        }
Пример #24
0
 static bool IsRunning(RunningInstance instance)
 {
     return(!string.Equals(instance.InstanceState.Name, "stopped", StringComparison.OrdinalIgnoreCase));
 }
Пример #25
0
 public static string getPassword(this API_AmazonEC2 amazonEC2, RunningInstance runningInstance)
 {
     return(amazonEC2.getPassword(runningInstance, null));
 }
Пример #26
0
        /// <summary>
        /// Retrieves current Amazon instance, check tags for ElasticIP and try to assign if it is possible.
        /// </summary>
        public void AssignElasticIpByTag(RunningInstance instance)
        {
            var tag = GetElasticIpTag(instance);

            AssignElasticIpByTag(instance, tag);
        }
        /// <summary>Starts a new watch operation if one is not currently running.</summary>
        private void StartRaisingEvents()
        {
            // If we already have a cancellation object, we're already running.
            if (_cancellation != null)
            {
                return;
            }

            // Open an inotify file descriptor. Ideally this would be a constrained execution region, but we don't have access to 
            // PrepareConstrainedRegions. We still use a finally block to house the code that opens the handle and stores it in 
            // hopes of making it as non-interruptable as possible.  Ideally the SafeFileHandle would be allocated before the block, 
            // but SetHandle is protected and SafeFileHandle is sealed, so we're stuck doing the allocation here.
            SafeFileHandle handle;
            try { } finally
            {
                handle = Interop.Sys.INotifyInit();
                if (handle.IsInvalid)
                {
                    Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo();
                    switch (error.Error)
                    {
                        case Interop.Error.EMFILE:
                            string maxValue = ReadMaxUserLimit(MaxUserInstancesPath);
                            string message = !string.IsNullOrEmpty(maxValue) ?
                                SR.Format(SR.IOException_INotifyInstanceUserLimitExceeded_Value, maxValue) :
                                SR.IOException_INotifyInstanceUserLimitExceeded;
                            throw new IOException(message, error.RawErrno);
                        case Interop.Error.ENFILE:
                            throw new IOException(SR.IOException_INotifyInstanceSystemLimitExceeded, error.RawErrno);
                        default:
                            throw Interop.GetExceptionForIoErrno(error);
                    }
                }
            }

            try
            {
                // Create the cancellation object that will be used by this FileSystemWatcher to cancel the new watch operation
                CancellationTokenSource cancellation = new CancellationTokenSource();

                // Start running.  All state associated with the watch operation is stored in a separate object; this is done
                // to avoid race conditions that could result if the users quickly starts/stops/starts/stops/etc. causing multiple
                // active operations to all be outstanding at the same time.
                var runner = new RunningInstance(
                    this, handle, _directory,
                    IncludeSubdirectories, TranslateFilters(NotifyFilter), cancellation.Token);

                // Now that we've created the runner, store the cancellation object and mark the instance
                // as running.  We wait to do this so that if there was a failure, StartRaisingEvents
                // may be called to try again without first having to call StopRaisingEvents.
                _cancellation = cancellation;
                _enabled = true;

                // Start the runner
                runner.Start();
            }
            catch
            {
                // If we fail to actually start the watching even though we've opened the 
                // inotify handle, close the inotify handle proactively rather than waiting for it 
                // to be finalized.
                handle.Dispose();
                throw;
            }
        }
Пример #28
0
/*		public static string getPassword(this API_AmazonEC2 amazonEC2, RunningInstance runningInstance)
 *              {
 *                      return amazonEC2.getPassword(runningInstance,null);
 *              }
 *              public static string getPassword(this API_AmazonEC2 amazonEC2, RunningInstance runningInstance, string pathToPemFile)
 *              {
 *                      "Tests on  instance with ID: {0}".info(runningInstance.InstanceId);
 *                      var ec2Client = amazonEC2.getEC2Client(runningInstance.Placement.AvailabilityZone.removeLastChar());
 *                      var passwordResponse = ec2Client.GetPasswordData(new GetPasswordDataRequest().WithInstanceId(runningInstance.InstanceId));
 *                      "raw password data : {0}".info(passwordResponse.GetPasswordDataResult.ToXML());
 *                      if (amazonEC2.ApiRsa.isNull())
 *                              amazonEC2.ApiRsa = new API_RSA(pathToPemFile);
 *                      var decryptedPassword = amazonEC2.ApiRsa.decryptPasswordUsingPem(passwordResponse.GetPasswordDataResult.PasswordData.Data);
 *                      "decrypted password: {0}".info(decryptedPassword);
 *                      return decryptedPassword;
 *              }*/


        public static string getRunningInstanceSignature(this API_AmazonEC2 amazonEC2, RunningInstance runningInstance)
        {
            var signature = "{0}  -  {1}  -  {2}  -  {3}  -  {4} ".format(
                runningInstance.InstanceId,
                runningInstance.InstanceType,
                runningInstance.IpAddress,
                runningInstance.Placement.AvailabilityZone,
                runningInstance.InstanceState.Name);

            foreach (var tag in runningInstance.Tag)
            {
                //signature = "{0}= {1}  -  {2}".format(tag.Key, tag.Value, signature);
                signature = "{1}  -  {2}".format(tag.Key, tag.Value, signature);
            }
            return(signature);
        }