Пример #1
0
 protected override void OnStop()
 {
     CtxTrace.TraceInformation();
     if (_Service != null)
     {
         _Service.Stop();
     }
 }
 public void Stop()
 {
     CtxTrace.TraceInformation();
     try {
         userDataService.Stop();
     } catch (Exception e) {
         CtxTrace.TraceError(e);
     }
 }
Пример #3
0
 public static void ExecuteProcess(string executable, string args, string workingDirectory)
 {
     try {
         ProcessWrapper process = new ProcessWrapper(executable, args, workingDirectory);
         process.Execute();
     } catch (Exception e) {
         CtxTrace.TraceError(e);
     }
 }
Пример #4
0
 private void process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
 {
     try {
         Err.WriteLine(e.Data);
         Err.Flush();
     } catch (Exception ex) {
         CtxTrace.TraceError(ex);
     }
 }
Пример #5
0
 static void OnUnhandledException(object sender, UnhandledExceptionEventArgs args)
 {
     CtxTrace.TraceInformation();
     try {
         Exception e = args.ExceptionObject as Exception;
         CtxTrace.TraceError(e.Message + "\n" + e.StackTrace);
         AgentService.StopService();
     } catch (Exception ex) {
         CtxTrace.TraceError(ex);
     }
 }
Пример #6
0
 /// <summary>
 /// The main entry point for the application.
 /// </summary>
 static void Main()
 {
     CtxTrace.Initialize("cloudworks-agent", true);
     ErrorHandler.Initialize();
     ServiceBase[] ServicesToRun;
     ServicesToRun = new ServiceBase[]
     {
         new AgentService()
     };
     ServiceBase.Run(ServicesToRun);
 }
Пример #7
0
        private void ProcessUserDataTask(object ignored)
        {
            CtxTrace.TraceInformation();

            // Check sanity of configuration
            if (userDataUrl.Contains(DhcpServerPlaceholder))
            {
                List <IPAddress> dhcpServers = NetworkUtilities.GetDhcpServers();
                if (dhcpServers.Count == 0)
                {
                    CtxTrace.TraceError("Configured to get UserData from DHCP server, but no DHCP server found");
                    stateService.InitialisationComplete = true;
                }
            }

            // UserData may be a little slow to be delivered
            while (!stateService.InitialisationComplete && !stopSignalled)
            {
                string userData = GetUserData();
                if (!string.IsNullOrEmpty(userData))
                {
                    // May be multiple root elements, so wrap for Xml parser
                    string wrappedUserData = string.Format("<dummyRoot>{0}</dummyRoot>", userData);
                    try {
                        XDocument doc    = XDocument.Parse(wrappedUserData);
                        XElement  script = doc.XPathSelectElement("//script");
                        if (script != null)
                        {
                            // Script may initiate a reboot, so mark the processing done once userData read.
                            stateService.InitialisationComplete = true;
                            ExecuteScript(script.Value);
                        }
                        script = doc.XPathSelectElement("//powershell");
                        if (script != null)
                        {
                            // Script may initiate a reboot, so mark the processing done once userData read.
                            stateService.InitialisationComplete = true;
                            ExecutePowerShellScript(script.Value);
                        }
                    } catch (Exception ex) {
                        CtxTrace.TraceError(ex);
                    }
                    break;
                }
                // Sleep a while but ensure timely response to task cancel
                DateTime waitUntil = DateTime.Now + TimeSpan.FromSeconds(5);
                while (!stopSignalled && (DateTime.Now < waitUntil))
                {
                    Thread.Sleep(TimeSpan.FromMilliseconds(1000));
                }
            }
            CtxTrace.TraceInformation("Task exit");
        }
Пример #8
0
 private void ExecuteScript(string contents)
 {
     CtxTrace.TraceInformation();
     try {
         string dir      = CreateWorkingDirectory(cfnFolder);
         string fileName = Path.Combine(dir, "user-data.cmd");
         File.WriteAllText(fileName, contents);
         ScriptUtilities.ExecuteProcess("cmd.exe", "/c " + fileName, dir);
     } catch (Exception e) {
         CtxTrace.TraceError(e);
     }
 }
Пример #9
0
        static void Main(string[] args)
        {
            CtxTrace.Initialize("cloudworks-agent-host", true);
            CloudworksServices svc = new CloudworksServices();

            new UserDataState("C:\\cfn").InitialisationComplete = false;

            svc.Start();
            Console.WriteLine("Agent is running");
            Console.WriteLine("Press any key to stop");
            Console.ReadLine();
            svc.Stop();
            Console.WriteLine("Agent is stopped");
            Console.WriteLine("Press any key to exit");
            Console.ReadLine();
        }
Пример #10
0
        public UserDataService()
        {
            userDataUrl = ConfigurationManager.AppSettings["user-data-url"];
            if (string.IsNullOrEmpty(userDataUrl))
            {
                userDataUrl = DefaultUserDataUrl;
            }

            cfnFolder = ConfigurationManager.AppSettings["cfn-folder"];
            if (string.IsNullOrEmpty(cfnFolder))
            {
                cfnFolder = DefaultCfnFolder;
            }
            stateService = new UserDataState(cfnFolder);
            CtxTrace.TraceVerbose("UserData Url {0}, CFN folder {1}", userDataUrl, cfnFolder);
        }
Пример #11
0
 /// <summary>
 /// Simple "GET" on the specified Url returing the contents as a string. If an error occurs
 /// it is logged and the method returns null
 /// </summary>
 /// <param name="url"></param>
 /// <returns></returns>
 public static string HttpGet(string url)
 {
     CtxTrace.TraceVerbose("url={0}", url);
     try {
         HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
         request.Method = "GET";
         using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) {
             using (Stream responseStream = response.GetResponseStream()) {
                 using (StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8)) {
                     return(streamReader.ReadToEnd());
                 }
             }
         }
     } catch (Exception e) {
         CtxTrace.TraceError(e);
         return(null);
     }
 }
Пример #12
0
        private void ExecutePowerShellScript(string contents)
        {
            CtxTrace.TraceInformation();
            string oldPolicy = null;

            try {
                oldPolicy = ScriptUtilities.SetPowerShellExectionPolicy("Unrestricted");
                string dir      = CreateWorkingDirectory(cfnFolder);
                string fileName = Path.Combine(dir, "user-data.ps1");
                File.WriteAllText(fileName, contents);
                ScriptUtilities.ExecuteProcess("powershell.exe", String.Format("-F {0}", fileName), dir);
            } catch (Exception e) {
                CtxTrace.TraceError(e);
            } finally {
                if (oldPolicy != null)
                {
                    ScriptUtilities.SetPowerShellExectionPolicy(oldPolicy);
                }
            }
        }
Пример #13
0
        public void Execute()
        {
            CtxTrace.TraceInformation("Executable = {0}", startInfo.FileName);
            try {
                using (var process = new Process()) {
                    process.StartInfo           = this.startInfo;
                    process.OutputDataReceived += process_OutputDataReceived;
                    process.ErrorDataReceived  += process_ErrorDataReceived;
                    process.Start();
                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();

                    process.WaitForExit();
                    CtxTrace.TraceInformation("Child process has exited");
                }
            } catch (Exception e) {
                CtxTrace.TraceError(e);
            } finally {
                Out.Close();
                Err.Close();
            }
        }
Пример #14
0
 protected override void OnStart(string[] args)
 {
     CtxTrace.TraceInformation();
     _Service = new CloudworksServices();
     _Service.Start();
 }
Пример #15
0
 public void Stop()
 {
     CtxTrace.TraceInformation();
     stopSignalled = true;
 }
Пример #16
0
 public void Start()
 {
     CtxTrace.TraceInformation();
     stopSignalled = false;
     ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessUserDataTask));
 }