Пример #1
0
        async Task <String> FunctionHandler(Model input, ILambdaContext context)
        {
            try
            {
                String region     = input.region;
                var    endpoint   = RegionEndpoint.GetBySystemName(region);
                String instanceid = input.instanceid;
                var    ec2Client  = new AmazonEC2Client(endpoint);
                if (input.state == "ON")
                {
                    StartInstancesRequest start = new StartInstancesRequest();
                    start.InstanceIds.Add(instanceid);
                    await ec2Client.StartInstancesAsync(start);

                    return("Ec2 Started");
                }
                else if (input.state == "OFF")
                {
                    StopInstancesRequest stop = new StopInstancesRequest();
                    stop.InstanceIds.Add(instanceid);
                    await ec2Client.StopInstancesAsync(stop);

                    return("Ec2 Stopped");
                }
            }
            catch (Exception e)
            {
                Console.Out.WriteLine(e.StackTrace);
            }
            return("done");
        }
Пример #2
0
        public void StartInstance(ref bool actionSucceeded, ref string actionMessage)
        {
            if (InstanceRequestObj.InstanceState.ToLower() != "stopped")
            {
                actionSucceeded = false;
                actionMessage   = $"The instance {InstanceRequestObj.InstanceName} is currently in {InstanceRequestObj.InstanceState} state , and cannot be started at this time.";
                return;
            }
            var request = new StartInstancesRequest
            {
                InstanceIds = new List <string>()
                {
                    InstanceRequestObj.InstanceID
                }
            };

            try
            {
                StartInstancesResponse response = Ec2Client.StartInstancesAsync(request).GetAwaiter().GetResult();
                foreach (InstanceStateChange item in response.StartingInstances)
                {
                    Console.WriteLine("Started instance: " + item.InstanceId);
                    Console.WriteLine("Instance state: " + item.CurrentState.Name);
                }
                actionSucceeded = true;
                actionMessage   = $"The instance {InstanceRequestObj.InstanceName} is being started. Please check the AWS Console to verify.";
            }
            catch (Exception ex)
            {
                context.Logger.LogLine($"ServerOperationsHelper::StopInstance {ex.Message}");
                context.Logger.LogLine($"ServerOperationsHelper::StopInstance {ex.StackTrace}");
                actionSucceeded = false;
                actionMessage   = $"Could not start {InstanceRequestObj.InstanceName} . Please contact your administrator.";
            }
        }
Пример #3
0
        /// <summary>
        /// Starts an EC2 instance
        /// </summary>
        /// <param name="instanceId"></param>
        /// <returns></returns>
        public static EC2Instance StartInstance(string instanceId)
        {
            var instance = new EC2Instance()
            {
                InstanceId = instanceId
            };
            var request = new StartInstancesRequest();

            request.InstanceId = new List <string>();
            request.InstanceId.Add(instanceId);
            try
            {
                var response        = EC2.Provider.StartInstances(request);
                var stateChanges    = response.StartInstancesResult.StartingInstances;
                var runningInstance = (from i in stateChanges
                                       where i.InstanceId == instanceId
                                       select i).FirstOrDefault();
                if (runningInstance != null)
                {
                    instance.CurrentStateName = runningInstance.CurrentState.Name;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("Error calling AWS.StartInstances: {0}", ex.Message));
            }
            return(instance);
        }
Пример #4
0
        /// <summary>
        /// Starts an Amazon EBS-backed AMI that you've previously stopped. Instances that use Amazon EBS volumes as their root devices can be quickly stopped
        /// and started. When an instance is stopped, the compute resources are released and you are not billed for hourly instance usage. However, your root partition
        /// Amazon EBS volume remains, continues to persist your data, and you are charged for Amazon EBS volume usage. You can restart your instance at any time. Each
        ///  time you transition an instance from stopped to started, Amazon EC2 charges a full instance hour, even if transitions happen multiple times within a single hour.
        /// </summary>
        /// <param name="instances">A list of instance IDs to be started.</param>
        /// <param name="settings">The <see cref="EC2Settings"/> used during the request to AWS.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public async Task <bool> StartInstances(IList <string> instances, EC2Settings settings, CancellationToken cancellationToken = default(CancellationToken))
        {
            if ((instances == null) || (instances.Count == 0))
            {
                throw new ArgumentNullException("instances");
            }



            //Create Request
            AmazonEC2Client       client  = this.CreateClient(settings);
            StartInstancesRequest request = new StartInstancesRequest();

            foreach (string instance in instances)
            {
                request.InstanceIds.Add(instance);
            }



            //Check Response
            StartInstancesResponse response = await client.StartInstancesAsync(request, cancellationToken);

            if (response.HttpStatusCode == HttpStatusCode.OK)
            {
                _Log.Verbose("Successfully started instances '{0}'", string.Join(",", instances));
                return(true);
            }
            else
            {
                _Log.Error("Failed to start instances '{0}'", string.Join(",", instances));
                return(false);
            }
        }
Пример #5
0
    protected void InsertButton_Click(object sender, EventArgs e)
    {
        Auth.CheckPermission("STARTAWS", "START");

        // Crea i parametri di lancio
        var myRegion  = RegionEndpoint.GetBySystemName(ConfigurationManager.AppSettings["AWS_REGION"]); // non funziona in appsettings.json...
        var ec2Client = new AmazonEC2Client(new BasicAWSCredentials(ConfigurationManager.AppSettings["AWS_ACCESSKEY"], ConfigurationManager.AppSettings["AWS_SECRETKEY"]), myRegion);
        var req       = new DescribeInstancesRequest {
            InstanceIds = { ConfigurationManager.AppSettings["AWS_INSTANCEID"] }
        };

        // Recupera lo stato dell'instanza
        DescribeInstancesResponse res = ec2Client.DescribeInstances(req);

        if (res.Reservations[0].Instances[0].State.Code != 80)
        {
            return; // non fa niente
        }

        StartInstancesRequest launchRequest = new StartInstancesRequest {
            InstanceIds = { ConfigurationManager.AppSettings["AWS_INSTANCEID"] }
        };
        StartInstancesResponse launchResponse = ec2Client.StartInstances(launchRequest);

        SetPageData(); // refresh pagina
    }
Пример #6
0
        internal static async Task <StartInstancesResponse> StartEc2InstanceAsync(IConfiguration Configuration, string User, string AccountName, string InstanceId)
        {
            try
            {
                var accountKey    = LoadAwsAccounts(Configuration).SingleOrDefault(x => x.AccountName == AccountName);
                var accountRegion = RegionEndpoint.GetBySystemName(accountKey.Region);
                var stsClient     = new AmazonSecurityTokenServiceClient();
                var sessionName   = string.Format(ResourceStrings.StartAction, User, accountKey.AccountName, DateTime.Now.Ticks.ToString());
                sessionName = sessionName.Length > 63 ? sessionName.Substring(0, 63) : sessionName;
                var assumeRoleRequest = new AssumeRoleRequest
                {
                    RoleArn         = accountKey.RoleArn,
                    RoleSessionName = sessionName,
                    DurationSeconds = 900
                };
                var stsResponse = await stsClient.AssumeRoleAsync(assumeRoleRequest);

                var instanceIdAsList = new List <string> {
                    InstanceId
                };
                var startRequest = new StartInstancesRequest(instanceIdAsList);
                var ec2Client    = new AmazonEC2Client(stsResponse.Credentials, accountRegion);
                var response     = ec2Client.StartInstancesAsync(startRequest);
                ec2Client.Dispose();
                stsClient.Dispose();
                return(await response);
            }
            catch (Exception e)
            {
                throw new Exception(string.Format(ErrorStrings.StartEc2InstanceError, InstanceId, e.Message), e.InnerException);
            }
        }
        public bool StartVM(string instanceId)
        {
            try
            {
                string[]       id     = instanceId.Split(',');
                AWSAuthDetails detail = SqlHelper.GetAWSAuth(id[0], "VM");
                var            region = RegionEndpoint.GetBySystemName(detail.Region);
                // Amazon.Runtime.AWSCredentials credentials = new Amazon.Runtime.StoredProfileAWSCredentials(detail.ProfileName);
                AmazonEC2Client        ec2          = new AmazonEC2Client(detail.AccessKey, detail.SecretKey, region);
                StartInstancesRequest  startRequest = new StartInstancesRequest();
                StartInstancesResponse startResponse;
                foreach (var instance in id)
                {
                    startRequest.InstanceIds.Add(instance);
                }
                startResponse = ec2.StartInstances(startRequest);
                string response = startResponse.HttpStatusCode.ToString();
                if (response == "OK")
                {
                    SqlHelper.UpdateInstanceStatus(id, "starting");;
                    return(true);
                }

                return(false);
            }
            catch (Exception e)
            {
                this.log.Error(e);
                return(false);
            }
        }
Пример #8
0
        /// <summary>
        /// Initializes the Amazon EC2 client object and uses it to call the
        /// StartInstancesAsync method to start the listed Amazon EC2 instances.
        /// </summary>
        public static async Task Main()
        {
            string ec2InstanceId = "i-0123456789abcdef0";

            // If your EC2 instances are not in the same AWS Region as
            // the default users on your system, you need to supply
            // the AWS Region as a parameter to the client constructor.
            var client = new AmazonEC2Client();

            var request = new StartInstancesRequest
            {
                InstanceIds = new List <string> {
                    ec2InstanceId
                },
            };

            var response = await client.StartInstancesAsync(request);

            if (response.StartingInstances.Count > 0)
            {
                var instances = response.StartingInstances;
                instances.ForEach(i =>
                {
                    Console.WriteLine($"Successfully started the EC2 Instance with InstanceID: {i.InstanceId}.");
                });
            }
        }
Пример #9
0
        private void StartInstances()
        {
            var request  = new StartInstancesRequest(instances);
            var response = client.StartInstances(request);

            response.StartingInstances.ForEach(x => Console.WriteLine($"STARTING INSTANCE ID:{x.InstanceId}"));
        }
Пример #10
0
        public void StartInstances(List <string> instanceIds)
        {
            var request = new StartInstancesRequest {
                InstanceIds = instanceIds
            };

            _ec2Client.StartInstances(request);
        }
Пример #11
0
        public void StartInstance(string InstanceID)
        {
            var mStartInstancesRequest = new StartInstancesRequest();

            mStartInstancesRequest.InstanceIds = new List <string> {
                InstanceID
            };
            ec2Client.StartInstances(mStartInstancesRequest);
        }
 public static async Task StartInstance(AmazonEC2Client ec2Client, string instanceId)
 {
     var request = new StartInstancesRequest {
         InstanceIds = new List <string> {
             instanceId
         }
     };
     var response = await ec2Client.StartInstancesAsync(request);
 }
Пример #13
0
 InstanceState Start(RunningInstance instance)
 {
     using (var client = CreateClient())
     {
         var request = new StartInstancesRequest();
         request.InstanceId.Add(instance.InstanceId);
         var response = client.StartInstances(request);
         return(response.StartInstancesResult.StartingInstances[0].CurrentState);
     }
 }
Пример #14
0
        public void Start(string bootstrapId)
        {
            Logger.Info("Starting instances");
            StartInstancesRequest startRequest = new StartInstancesRequest();
            IEnumerable <string>  instanceIds  = FindInstanceIdsFromBootstrapId(bootstrapId);

            startRequest.InstanceIds.AddRange(instanceIds);

            _client.StartInstances(startRequest);
            Logger.WithLogSection("Waiting for instances to start running", () => WaitForInstancesToRun(instanceIds));
        }
Пример #15
0
        private void StartInstance(List <string> ids)
        {
            if (ids.Count <= 0)
            {
                return;
            }
            var sir = new StartInstancesRequest
            {
                InstanceIds = ids
            };

            ec2Client.StartInstances(sir);
        }
        public async Task <StartInstancesResponse> StartAsync(StartInstancesRequest request)
        {
            using (var ec2 = new AmazonEC2Client(_config))
            {
                var response = await ec2.StartInstancesAsync(request);

                if (response.HttpStatusCode != HttpStatusCode.OK)
                {
                    throw new AwsResponseException <StartInstancesRequest, StartInstancesResponse>(request, response);
                }
                return(response);
            }
        }
Пример #17
0
        /// <summary>
        /// Start's instances - these should be EBS block storage instances.
        /// </summary>
        /// <param name="instanceIds">The instance Id of an EC2 instance</param>
        /// <remarks>This uses EBS storage EC2 instances which can be stopped and started.  The instance should be stopped.</remarks>
        public void StartInstances(IEnumerable <string> instanceIds)
        {
            var request = new StartInstancesRequest {
                InstanceId = new List <string>(instanceIds)
            };
            StartInstancesResponse resonse = Client.StartInstances(request);

            if (resonse.IsSetStartInstancesResult())
            {
                foreach (InstanceStateChange instanceStateChange in resonse.StartInstancesResult.StartingInstances)
                {
                    Trace.WriteLine(string.Format("Starting instance {0}", instanceStateChange.InstanceId));
                }
            }
        }
Пример #18
0
        public async Task StartEc2Instances(List <string> InstanceIds, string region = null)
        {
            if (region != null)
            {
                client = new AmazonEC2Client(
                    CredentiaslManager.GetCredential(profile),
                    AwsCommon.GetRetionEndpoint(region));
            }

            var request = new StartInstancesRequest()
            {
                InstanceIds = InstanceIds
            };
            await client.StartInstancesAsync(request);
        }
Пример #19
0
        /// <summary>
        /// 本接口(StartInstances)用于启动一个或多个实例。
        ///
        /// * 只有状态为 STOPPED 的实例才可以进行此操作。
        /// * 接口调用成功时,实例会进入 STARTING 状态;启动实例成功时,实例会进入 RUNNING 状态。
        /// * 支持批量操作。每次请求批量实例的上限为 100。
        /// * 本接口为异步接口,请求发送成功后会返回一个 RequestId,此时操作并未立即完成。实例操作结果可以通过调用 DescribeInstances 接口查询,如果实例的最新操作状态(LatestOperationState)为“SUCCESS”,则代表操作成功。
        /// </summary>
        /// <param name="req"><see cref="StartInstancesRequest"/></param>
        /// <returns><see cref="StartInstancesResponse"/></returns>
        public StartInstancesResponse StartInstancesSync(StartInstancesRequest req)
        {
            JsonResponseModel <StartInstancesResponse> rsp = null;

            try
            {
                var strResp = this.InternalRequestSync(req, "StartInstances");
                rsp = JsonConvert.DeserializeObject <JsonResponseModel <StartInstancesResponse> >(strResp);
            }
            catch (JsonSerializationException e)
            {
                throw new TencentCloudSDKException(e.Message);
            }
            return(rsp.Response);
        }
Пример #20
0
 public void StartAutomatedTestingEC2()
 {
     try
     {
         List <string> instanceIds = new List <string>()
         {
             _configuration.GetConnectionString("EC2ID")
         };
         StartInstancesRequest  startInstanceRequest = new StartInstancesRequest(instanceIds);
         StartInstancesResponse x = _ec2Client.StartInstancesAsync(startInstanceRequest).Result;
     }
     catch (Exception e)
     {
         _logger.LogError(e.Message, e);
     }
 }
Пример #21
0
        public static void StartInstance(string instanceId, string regionName, string profileName)
        {
            if (string.IsNullOrWhiteSpace(instanceId))
            {
                throw new Exception("Instance id is not specified.");
            }

            AWSCredentials creds = GetAWSCredentials(profileName);

            if (creds == null)
            {
                throw new Exception("AWS credentials are not specified");
            }

            RegionEndpoint endpoint = RegionEndpoint.GetBySystemName(regionName);

            if (endpoint.DisplayName.Contains("Unknown"))
            {
                throw new Exception("AWS region endpoint is not valid.");
            }

            try
            {
                using (AmazonEC2Client client = new AmazonEC2Client(creds, endpoint))
                {
                    StartInstancesRequest req = new StartInstancesRequest
                    {
                        InstanceIds = new List <string>()
                        {
                            instanceId
                        }
                    };
                    client.StartInstances(req);
                }
            }
            catch (AmazonEC2Exception ex)
            {
                // Check the ErrorCode to see if the instance does not exist.
                if ("InvalidInstanceID.NotFound" == ex.ErrorCode)
                {
                    throw new Exception($"EC2 instance {instanceId} does not exist.");
                }

                // The exception was thrown for another reason, so re-throw the exception.
                throw;
            }
        }
Пример #22
0
        static void Main(string[] args)
        {
            try
            {
                var argsDic = GetArgsDic(args);

                var itemsList = argsDic["--instances"];

                if (itemsList.StartsWith("\"") && itemsList.EndsWith("\""))
                {
                    itemsList = itemsList.Substring(1, itemsList.Length - 2);
                }

                var items = itemsList.Split(',');

                var action = argsDic["--action"];

                using (var client = AwsUtil.CreateClient(AwsUtil.Region))
                {
                    if (action == "start")
                    {
                        var request = new StartInstancesRequest();
                        request.InstanceId.AddRange(items);
                        client.StartInstances(request);
                    }
                    else if (action == "stop")
                    {
                        var request = new StopInstancesRequest();
                        request.InstanceId.AddRange(items);
                        client.StopInstances(request);
                    }
                }
            }
            catch (ApplicationException exc)
            {
                Console.WriteLine(exc.Message);
            }
            catch (AmazonEC2Exception exc)
            {
                Console.WriteLine(exc.Message);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc);
            }
        }
Пример #23
0
        private static void LaunchInstance()
        {
            try
            {
                AmazonEC2 ec2 = AWSClientFactory.CreateAmazonEC2Client(_awsKey, _awsSecretKey);

                StartInstancesRequest request = new StartInstancesRequest();
                request.WithInstanceId(new string[] { _instanceId });

                ec2.StartInstances(request);
                Mail(string.Format("Successfully started EC2 instance {0}", _instanceId));
            }
            catch (Exception e)
            {
                MailError("Error launching instance", e);
            }
        }
Пример #24
0
        public async Task StartServer()
        {
            Console.WriteLine("Starting server.");
            IsWorking = true;
            await Embeds.EditMessage(Embeds.ServerStarting());

            var request = new StartInstancesRequest();

            request.InstanceIds = new List <string>()
            {
                BotConfig.GetCachedConfig().Aws.EC2InstanceId
            };
            var response = await client.StartInstancesAsync(request);

            bool suc = await AwaitServerStart();

            if (suc)
            {
                while (true)
                {
                    await Task.Delay((int)BotConfig.GetCachedConfig().PollingDelay);

                    try
                    {
                        MineStat ms = new MineStat(BotConfig.GetCachedConfig().Minecraft.MinecraftServerIP, BotConfig.GetCachedConfig().Minecraft.MinecraftServerPort);
                        if (ms.ServerUp)
                        {
                            Console.WriteLine("MC Server up.");
                            break;
                        }
                        Console.WriteLine("MC Server is not up.");
                    }
                    catch
                    {
                        Console.WriteLine("Polling Minecraft server to see if it is online.. resulted in error.");
                    }
                }
                await Embeds.EditMessage(Embeds.ServerStarted());
                await StopServer();
            }
            else
            {
                Console.WriteLine("Server start failed due to maxing out maxInstanceStartAttempts.");
                return;
            }
        }
Пример #25
0
    public IDictionary <string, string> StartInstance(List <string> instancesIds)
    {
        IDictionary <string, string> result;

        // Inicia uma instância.
        try
        {
            StartInstancesRequest  startRequest  = new StartInstancesRequest(instancesIds);
            StartInstancesResponse startResponse = Ec2.StartInstances(startRequest);
            result = startResponse.ResponseMetadata.Metadata;
            result.Add("STATUS_CODE", startResponse.HttpStatusCode.ToString());
            result.Add("RESPONSE", startResponse.ToString());
        }
        catch (AmazonEC2Exception ex)
        {
            throw new AwsException(ex);
        }

        return(result);
    }
Пример #26
0
        public async Task <OperationDetails> StartEC2InstancesByInstanceIds(List <string> instanceIds)
        {
            OperationDetails operationDetails = new OperationDetails();

            try
            {
                using (AmazonEC2Client ec2Client = new AmazonEC2Client())
                {
                    StartInstancesRequest startRequest = new StartInstancesRequest(instanceIds);

                    StartInstancesResponse startResponse = await ec2Client.StartInstancesAsync(startRequest);

                    operationDetails.StatusMessage = startResponse != null?startResponse.HttpStatusCode.ToString() : "null response";
                }
            }
            catch (Exception ex)
            {
                operationDetails.StatusMessage = ex.Message;
            }

            return(operationDetails);
        }
Пример #27
0
//####################################################################################

        public string StartInstance(IAmazonEC2 ec2, string instidstr)
        //start ec2 instance
        {
            // ec2.StartInstances.StartInstance.
            StartInstancesRequest  startreq;
            StartInstancesResponse startInstancesResponse = null;

            try {
                startreq = new StartInstancesRequest {
                    InstanceIds = new List <string>()
                    {
                        instidstr
                    }
                };

                startInstancesResponse = ec2.StartInstances(startreq);
                return("Done");
            }
            catch (Exception ex)
            {
                return(ex.Message + "\n" + ex.StackTrace);
            }
        }
        static async Task <string> StartInstanceAsync()
        {
            string response           = String.Empty;
            StartInstancesRequest req = new StartInstancesRequest
            {
                InstanceIds = _InstanceId
            };
            StartInstancesResponse res = await _Client.StartInstancesAsync(req);

            // We take 5 seconds to wait for public dns be provisioned on the running servers.
            Thread.Sleep(5000);
            // Iterate through the response to obtain values that would be used to sent an email.
            if (res.StartingInstances.Count > -1)
            {
                var serverstatus = await DescribeInstanceAsync();

                foreach (var item in serverstatus.Reservations)
                {
                    response += $"<br />Instance Name:{item.Instances[0].Tags.FirstOrDefault(t=>t.Key=="Name").Value} - Public DNS:{item.Instances[0].PublicDnsName}";
                    LambdaLogger.Log($"Instance Name:{item.Instances[0].Tags.FirstOrDefault(t => t.Key == "Name").Value} - Public DNS:{item.Instances[0].PublicDnsName}");
                }
            }
            return(response);
        }
Пример #29
0
 /// <summary>
 /// Starts instances
 /// </summary>
 /// <param name="request"></param>
 /// <returns></returns>
 public StartInstancesResponse StartInstances(StartInstancesRequest request)
 {
     return(EC2.StartInstances(request));
 }
Пример #30
0
 public StartInstancesResponse StartInstances(StartInstancesRequest request)
 {
     throw new NotImplementedException();
 }