mirror of
https://github.com/actions/runner.git
synced 2025-12-18 00:07:08 +00:00
GitHub Actions Runner
This commit is contained in:
6
src/Runner.Service/Windows/App.config
Normal file
6
src/Runner.Service/Windows/App.config
Normal file
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<configuration>
|
||||
<startup>
|
||||
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
|
||||
</startup>
|
||||
</configuration>
|
||||
BIN
src/Runner.Service/Windows/FinalPublicKey.snk
Normal file
BIN
src/Runner.Service/Windows/FinalPublicKey.snk
Normal file
Binary file not shown.
55
src/Runner.Service/Windows/Program.cs
Normal file
55
src/Runner.Service/Windows/Program.cs
Normal file
@@ -0,0 +1,55 @@
|
||||
using System;
|
||||
using System.ServiceProcess;
|
||||
using System.Diagnostics;
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace RunnerService
|
||||
{
|
||||
static class Program
|
||||
{
|
||||
/// <summary>
|
||||
/// The main entry point for the application.
|
||||
/// </summary>
|
||||
static int Main(String[] args)
|
||||
{
|
||||
if (args != null && args.Length == 1 && args[0].Equals("init", StringComparison.InvariantCultureIgnoreCase))
|
||||
{
|
||||
// TODO: LOC all strings.
|
||||
if (!EventLog.Exists("Application"))
|
||||
{
|
||||
Console.WriteLine("[ERROR] Application event log doesn't exist on current machine.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
EventLog applicationLog = new EventLog("Application");
|
||||
if (applicationLog.OverflowAction == OverflowAction.DoNotOverwrite)
|
||||
{
|
||||
Console.WriteLine("[WARNING] The retention policy for Application event log is set to \"Do not overwrite events\".");
|
||||
Console.WriteLine("[WARNING] Make sure manually clear logs as needed, otherwise RunnerService will stop writing output to event log.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
EventLog.WriteEntry(RunnerService.EventSourceName, "create event log trace source for actions-runner service", EventLogEntryType.Information, 100);
|
||||
return 0;
|
||||
}
|
||||
catch (Win32Exception ex)
|
||||
{
|
||||
Console.WriteLine("[ERROR] Unable to create '{0}' event source under 'Application' event log.", RunnerService.EventSourceName);
|
||||
Console.WriteLine("[ERROR] {0}",ex.Message);
|
||||
Console.WriteLine("[ERROR] Error Code: {0}", ex.ErrorCode);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
ServiceBase[] ServicesToRun;
|
||||
ServicesToRun = new ServiceBase[]
|
||||
{
|
||||
new RunnerService(args.Length > 0 ? args[0] : "ActionsRunnerService")
|
||||
};
|
||||
ServiceBase.Run(ServicesToRun);
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
36
src/Runner.Service/Windows/Properties/AssemblyInfo.cs
Normal file
36
src/Runner.Service/Windows/Properties/AssemblyInfo.cs
Normal file
@@ -0,0 +1,36 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("AgentService")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("AgentService")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2016")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||
[assembly: Guid("d12ebd71-0464-46d0-8394-40bcfba0a6f2")]
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// by using the '*' as shown below:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
||||
144
src/Runner.Service/Windows/Resource.Designer.cs
generated
Normal file
144
src/Runner.Service/Windows/Resource.Designer.cs
generated
Normal file
@@ -0,0 +1,144 @@
|
||||
//------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// This code was generated by a tool.
|
||||
// Runtime Version:4.0.30319.42000
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
// </auto-generated>
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
namespace RunnerService {
|
||||
using System;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// A strongly-typed resource class, for looking up localized strings, etc.
|
||||
/// </summary>
|
||||
// This class was auto-generated by the StronglyTypedResourceBuilder
|
||||
// class via a tool like ResGen or Visual Studio.
|
||||
// To add or remove a member, edit your .ResX file then rerun ResGen
|
||||
// with the /str option, or rebuild your VS project.
|
||||
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
|
||||
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
|
||||
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
|
||||
internal class Resource {
|
||||
|
||||
private static global::System.Resources.ResourceManager resourceMan;
|
||||
|
||||
private static global::System.Globalization.CultureInfo resourceCulture;
|
||||
|
||||
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
|
||||
internal Resource() {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the cached ResourceManager instance used by this class.
|
||||
/// </summary>
|
||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
||||
internal static global::System.Resources.ResourceManager ResourceManager {
|
||||
get {
|
||||
if (object.ReferenceEquals(resourceMan, null)) {
|
||||
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("RunnerService.Resource", typeof(Resource).Assembly);
|
||||
resourceMan = temp;
|
||||
}
|
||||
return resourceMan;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Overrides the current thread's CurrentUICulture property for all
|
||||
/// resource lookups using this strongly typed resource class.
|
||||
/// </summary>
|
||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
||||
internal static global::System.Globalization.CultureInfo Culture {
|
||||
get {
|
||||
return resourceCulture;
|
||||
}
|
||||
set {
|
||||
resourceCulture = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Runner listener exit with retryable error, re-launch runner in 5 seconds..
|
||||
/// </summary>
|
||||
internal static string RunnerExitWithError {
|
||||
get {
|
||||
return ResourceManager.GetString("RunnerExitWithError", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Runner listener exit with 0 return code, stop the service, no retry needed..
|
||||
/// </summary>
|
||||
internal static string RunnerExitWithoutError {
|
||||
get {
|
||||
return ResourceManager.GetString("RunnerExitWithoutError", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Runner listener exit with terminated error, stop the service, no retry needed..
|
||||
/// </summary>
|
||||
internal static string RunnerExitWithTerminatedError {
|
||||
get {
|
||||
return ResourceManager.GetString("RunnerExitWithTerminatedError", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Runner listener exit with undefined return code, re-launch runner in 5 seconds..
|
||||
/// </summary>
|
||||
internal static string RunnerExitWithUndefinedReturnCode {
|
||||
get {
|
||||
return ResourceManager.GetString("RunnerExitWithUndefinedReturnCode", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Runner listener update failed, stop the service..
|
||||
/// </summary>
|
||||
internal static string RunnerUpdateFailed {
|
||||
get {
|
||||
return ResourceManager.GetString("RunnerUpdateFailed", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Runner listener exit because of updating, re-launch runner in 5 seconds..
|
||||
/// </summary>
|
||||
internal static string RunnerUpdateInProcess {
|
||||
get {
|
||||
return ResourceManager.GetString("RunnerUpdateInProcess", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Runner listener has been updated to latest, restart the service to update the servicehost itself..
|
||||
/// </summary>
|
||||
internal static string RunnerUpdateRestartNeeded {
|
||||
get {
|
||||
return ResourceManager.GetString("RunnerUpdateRestartNeeded", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Runner listener has been updated to latest, re-launch runner in 5 seconds..
|
||||
/// </summary>
|
||||
internal static string RunnerUpdateSucceed {
|
||||
get {
|
||||
return ResourceManager.GetString("RunnerUpdateSucceed", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Crash servicehost to trigger SCM restart the serivce..
|
||||
/// </summary>
|
||||
internal static string CrashServiceHost {
|
||||
get {
|
||||
return ResourceManager.GetString("CrashServiceHost", resourceCulture);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
147
src/Runner.Service/Windows/Resource.resx
Normal file
147
src/Runner.Service/Windows/Resource.resx
Normal file
@@ -0,0 +1,147 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name="resmimetype">text/microsoft-resx</resheader>
|
||||
<resheader name="version">2.0</resheader>
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
|
||||
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
|
||||
<comment>This is a comment</comment>
|
||||
</data>
|
||||
|
||||
There are any number of "resheader" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used for serialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="RunnerExitWithoutError" xml:space="preserve">
|
||||
<value>Runner listener exit with 0 return code, stop the service, no retry needed.</value>
|
||||
</data>
|
||||
<data name="RunnerExitWithTerminatedError" xml:space="preserve">
|
||||
<value>Runner listener exit with terminated error, stop the service, no retry needed.</value>
|
||||
</data>
|
||||
<data name="RunnerExitWithError" xml:space="preserve">
|
||||
<value>Runner listener exit with retryable error, re-launch runner in 5 seconds.</value>
|
||||
</data>
|
||||
<data name="RunnerUpdateInProcess" xml:space="preserve">
|
||||
<value>Runner listener exit because of updating, re-launch runner in 5 seconds.</value>
|
||||
</data>
|
||||
<data name="RunnerUpdateSucceed" xml:space="preserve">
|
||||
<value>Runner listener has been updated to latest, re-launch runner in 5 seconds.</value>
|
||||
</data>
|
||||
<data name="RunnerUpdateFailed" xml:space="preserve">
|
||||
<value>Runner listener update failed, stop the service.</value>
|
||||
</data>
|
||||
<data name="RunnerUpdateRestartNeeded" xml:space="preserve">
|
||||
<value>Runner listener has been updated to latest, restart the service to update the servicehost itself.</value>
|
||||
</data>
|
||||
<data name="CrashServiceHost" xml:space="preserve">
|
||||
<value>Crash servicehost to trigger SCM restart the serivce.</value>
|
||||
</data>
|
||||
<data name="RunnerExitWithUndefinedReturnCode" xml:space="preserve">
|
||||
<value>Runner listener exit with undefined return code, re-launch runner in 5 seconds.</value>
|
||||
</data>
|
||||
</root>
|
||||
37
src/Runner.Service/Windows/RunnerService.Designer.cs
generated
Normal file
37
src/Runner.Service/Windows/RunnerService.Designer.cs
generated
Normal file
@@ -0,0 +1,37 @@
|
||||
namespace RunnerService
|
||||
{
|
||||
partial class RunnerService
|
||||
{
|
||||
/// <summary>
|
||||
/// Required designer variable.
|
||||
/// </summary>
|
||||
private System.ComponentModel.IContainer components = null;
|
||||
|
||||
/// <summary>
|
||||
/// Clean up any resources being used.
|
||||
/// </summary>
|
||||
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing && (components != null))
|
||||
{
|
||||
components.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
#region Component Designer generated code
|
||||
|
||||
/// <summary>
|
||||
/// Required method for Designer support - do not modify
|
||||
/// the contents of this method with the code editor.
|
||||
/// </summary>
|
||||
private void InitializeComponent()
|
||||
{
|
||||
components = new System.ComponentModel.Container();
|
||||
this.ServiceName = "Service1";
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
354
src/Runner.Service/Windows/RunnerService.cs
Normal file
354
src/Runner.Service/Windows/RunnerService.cs
Normal file
@@ -0,0 +1,354 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.ServiceProcess;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace RunnerService
|
||||
{
|
||||
public partial class RunnerService : ServiceBase
|
||||
{
|
||||
public const string EventSourceName = "ActionsRunnerService";
|
||||
private const int CTRL_C_EVENT = 0;
|
||||
private const int CTRL_BREAK_EVENT = 1;
|
||||
private bool _restart = false;
|
||||
private Process RunnerListener { get; set; }
|
||||
private bool Stopping { get; set; }
|
||||
private object ServiceLock { get; set; }
|
||||
private Task RunningLoop { get; set; }
|
||||
|
||||
public RunnerService(string serviceName)
|
||||
{
|
||||
ServiceLock = new Object();
|
||||
InitializeComponent();
|
||||
base.ServiceName = serviceName;
|
||||
}
|
||||
|
||||
protected override void OnStart(string[] args)
|
||||
{
|
||||
RunningLoop = Task.Run(
|
||||
() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
bool stopping;
|
||||
WriteInfo("Starting Actions Runner Service");
|
||||
TimeSpan timeBetweenRetries = TimeSpan.FromSeconds(5);
|
||||
|
||||
lock (ServiceLock)
|
||||
{
|
||||
stopping = Stopping;
|
||||
}
|
||||
|
||||
while (!stopping)
|
||||
{
|
||||
WriteInfo("Starting Actions Runner listener");
|
||||
lock (ServiceLock)
|
||||
{
|
||||
RunnerListener = CreateRunnerListener();
|
||||
RunnerListener.OutputDataReceived += RunnerListener_OutputDataReceived;
|
||||
RunnerListener.ErrorDataReceived += RunnerListener_ErrorDataReceived;
|
||||
RunnerListener.Start();
|
||||
RunnerListener.BeginOutputReadLine();
|
||||
RunnerListener.BeginErrorReadLine();
|
||||
}
|
||||
|
||||
RunnerListener.WaitForExit();
|
||||
int exitCode = RunnerListener.ExitCode;
|
||||
|
||||
// exit code 0 and 1 need stop service
|
||||
// exit code 2 and 3 need restart runner
|
||||
switch (exitCode)
|
||||
{
|
||||
case 0:
|
||||
Stopping = true;
|
||||
WriteInfo(Resource.RunnerExitWithoutError);
|
||||
break;
|
||||
case 1:
|
||||
Stopping = true;
|
||||
WriteInfo(Resource.RunnerExitWithTerminatedError);
|
||||
break;
|
||||
case 2:
|
||||
WriteInfo(Resource.RunnerExitWithError);
|
||||
break;
|
||||
case 3:
|
||||
WriteInfo(Resource.RunnerUpdateInProcess);
|
||||
var updateResult = HandleRunnerUpdate();
|
||||
if (updateResult == RunnerUpdateResult.Succeed)
|
||||
{
|
||||
WriteInfo(Resource.RunnerUpdateSucceed);
|
||||
}
|
||||
else if (updateResult == RunnerUpdateResult.Failed)
|
||||
{
|
||||
WriteInfo(Resource.RunnerUpdateFailed);
|
||||
Stopping = true;
|
||||
}
|
||||
else if (updateResult == RunnerUpdateResult.SucceedNeedRestart)
|
||||
{
|
||||
WriteInfo(Resource.RunnerUpdateRestartNeeded);
|
||||
_restart = true;
|
||||
ExitCode = int.MaxValue;
|
||||
Stop();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
WriteInfo(Resource.RunnerExitWithUndefinedReturnCode);
|
||||
break;
|
||||
}
|
||||
|
||||
if (Stopping)
|
||||
{
|
||||
ExitCode = exitCode;
|
||||
Stop();
|
||||
}
|
||||
else
|
||||
{
|
||||
// wait for few seconds before restarting the process
|
||||
Thread.Sleep(timeBetweenRetries);
|
||||
}
|
||||
|
||||
lock (ServiceLock)
|
||||
{
|
||||
RunnerListener.OutputDataReceived -= RunnerListener_OutputDataReceived;
|
||||
RunnerListener.ErrorDataReceived -= RunnerListener_ErrorDataReceived;
|
||||
RunnerListener.Dispose();
|
||||
RunnerListener = null;
|
||||
stopping = Stopping;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
WriteException(exception);
|
||||
ExitCode = 99;
|
||||
Stop();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void RunnerListener_ErrorDataReceived(object sender, DataReceivedEventArgs e)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(e.Data))
|
||||
{
|
||||
WriteToEventLog(e.Data, EventLogEntryType.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private void RunnerListener_OutputDataReceived(object sender, DataReceivedEventArgs e)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(e.Data))
|
||||
{
|
||||
WriteToEventLog(e.Data, EventLogEntryType.Information);
|
||||
}
|
||||
}
|
||||
|
||||
private Process CreateRunnerListener()
|
||||
{
|
||||
string exeLocation = Assembly.GetEntryAssembly().Location;
|
||||
string runnerExeLocation = Path.Combine(Path.GetDirectoryName(exeLocation), "Runner.Listener.exe");
|
||||
Process newProcess = new Process();
|
||||
newProcess.StartInfo = new ProcessStartInfo(runnerExeLocation, "run --startuptype service");
|
||||
newProcess.StartInfo.CreateNoWindow = true;
|
||||
newProcess.StartInfo.UseShellExecute = false;
|
||||
newProcess.StartInfo.RedirectStandardInput = true;
|
||||
newProcess.StartInfo.RedirectStandardOutput = true;
|
||||
newProcess.StartInfo.RedirectStandardError = true;
|
||||
return newProcess;
|
||||
}
|
||||
|
||||
protected override void OnShutdown()
|
||||
{
|
||||
SendCtrlSignalToRunnerListener(CTRL_BREAK_EVENT);
|
||||
base.OnShutdown();
|
||||
}
|
||||
|
||||
protected override void OnStop()
|
||||
{
|
||||
lock (ServiceLock)
|
||||
{
|
||||
Stopping = true;
|
||||
|
||||
// throw exception during OnStop() will make SCM think the service crash and trigger recovery option.
|
||||
// in this way we can self-update the service host.
|
||||
if (_restart)
|
||||
{
|
||||
throw new Exception(Resource.CrashServiceHost);
|
||||
}
|
||||
|
||||
SendCtrlSignalToRunnerListener(CTRL_C_EVENT);
|
||||
}
|
||||
}
|
||||
|
||||
// this will send either Ctrl-C or Ctrl-Break to runner.listener
|
||||
// Ctrl-C will be used for OnStop()
|
||||
// Ctrl-Break will be used for OnShutdown()
|
||||
private void SendCtrlSignalToRunnerListener(uint signal)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (RunnerListener != null && !RunnerListener.HasExited)
|
||||
{
|
||||
// Try to let the runner process know that we are stopping
|
||||
//Attach service process to console of Runner.Listener process. This is needed,
|
||||
//because windows service doesn't use its own console.
|
||||
if (AttachConsole((uint)RunnerListener.Id))
|
||||
{
|
||||
//Prevent main service process from stopping because of Ctrl + C event with SetConsoleCtrlHandler
|
||||
SetConsoleCtrlHandler(null, true);
|
||||
try
|
||||
{
|
||||
//Generate console event for current console with GenerateConsoleCtrlEvent (processGroupId should be zero)
|
||||
GenerateConsoleCtrlEvent(signal, 0);
|
||||
//Wait for the process to finish (give it up to 30 seconds)
|
||||
RunnerListener.WaitForExit(30000);
|
||||
}
|
||||
finally
|
||||
{
|
||||
//Disconnect from console and restore Ctrl+C handling by main process
|
||||
FreeConsole();
|
||||
SetConsoleCtrlHandler(null, false);
|
||||
}
|
||||
}
|
||||
|
||||
// if runner is still running, kill it
|
||||
if (!RunnerListener.HasExited)
|
||||
{
|
||||
RunnerListener.Kill();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
// InvalidOperationException is thrown when there is no process associated to the process object.
|
||||
// There is no process to kill, Log the exception and shutdown the service.
|
||||
// If we don't handle this here, the service get into a state where it can neither be stoped nor restarted (Error 1061)
|
||||
WriteException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
private RunnerUpdateResult HandleRunnerUpdate()
|
||||
{
|
||||
// sleep 5 seconds wait for upgrade script to finish
|
||||
Thread.Sleep(5000);
|
||||
|
||||
// looking update result record under _diag folder (the log file itself will indicate the result)
|
||||
// SelfUpdate-20160711-160300.log.succeed or SelfUpdate-20160711-160300.log.fail
|
||||
// Find the latest upgrade log, make sure the log is created less than 15 seconds.
|
||||
// When log file named as SelfUpdate-20160711-160300.log.succeedneedrestart, Exit(int.max), during Exit() throw Exception, this will trigger SCM to recovery the service by restart it
|
||||
// since SCM cache the ServiceHost in memory, sometime we need update the servicehost as well, in this way we can upgrade the ServiceHost as well.
|
||||
|
||||
DirectoryInfo dirInfo = new DirectoryInfo(GetDiagnosticFolderPath());
|
||||
FileInfo[] updateLogs = dirInfo.GetFiles("SelfUpdate-*-*.log.*") ?? new FileInfo[0];
|
||||
if (updateLogs.Length == 0)
|
||||
{
|
||||
// totally wrong, we are not even get a update log.
|
||||
return RunnerUpdateResult.Failed;
|
||||
}
|
||||
else
|
||||
{
|
||||
FileInfo latestLogFile = null;
|
||||
DateTime latestLogTimestamp = DateTime.MinValue;
|
||||
foreach (var logFile in updateLogs)
|
||||
{
|
||||
int timestampStartIndex = logFile.Name.IndexOf("-") + 1;
|
||||
int timestampEndIndex = logFile.Name.LastIndexOf(".log") - 1;
|
||||
string timestamp = logFile.Name.Substring(timestampStartIndex, timestampEndIndex - timestampStartIndex + 1);
|
||||
DateTime updateTime;
|
||||
if (DateTime.TryParseExact(timestamp, "yyyyMMdd-HHmmss", null, DateTimeStyles.None, out updateTime) &&
|
||||
updateTime > latestLogTimestamp)
|
||||
{
|
||||
latestLogFile = logFile;
|
||||
latestLogTimestamp = updateTime;
|
||||
}
|
||||
}
|
||||
|
||||
if (latestLogFile == null || latestLogTimestamp == DateTime.MinValue)
|
||||
{
|
||||
// we can't find update log with expected naming convention.
|
||||
return RunnerUpdateResult.Failed;
|
||||
}
|
||||
|
||||
latestLogFile.Refresh();
|
||||
if (DateTime.UtcNow - latestLogFile.LastWriteTimeUtc > TimeSpan.FromSeconds(15))
|
||||
{
|
||||
// the latest update log we find is more than 15 sec old, the update process is busted.
|
||||
return RunnerUpdateResult.Failed;
|
||||
}
|
||||
else
|
||||
{
|
||||
string resultString = Path.GetExtension(latestLogFile.Name).TrimStart('.');
|
||||
RunnerUpdateResult result;
|
||||
if (Enum.TryParse<RunnerUpdateResult>(resultString, true, out result))
|
||||
{
|
||||
// return the result indicated by the update log.
|
||||
return result;
|
||||
}
|
||||
else
|
||||
{
|
||||
// can't convert the result string, return failed to stop the service.
|
||||
return RunnerUpdateResult.Failed;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void WriteToEventLog(string eventText, EventLogEntryType entryType)
|
||||
{
|
||||
EventLog.WriteEntry(EventSourceName, eventText, entryType, 100);
|
||||
}
|
||||
|
||||
private string GetDiagnosticFolderPath()
|
||||
{
|
||||
return Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)), "_diag");
|
||||
}
|
||||
|
||||
private void WriteError(int exitCode)
|
||||
{
|
||||
String diagFolder = GetDiagnosticFolderPath();
|
||||
String eventText = String.Format(
|
||||
CultureInfo.InvariantCulture,
|
||||
"The Runner.Listener process failed to start successfully. It exited with code {0}. Check the latest Runner log files in {1} for more information.",
|
||||
exitCode,
|
||||
diagFolder);
|
||||
|
||||
WriteToEventLog(eventText, EventLogEntryType.Error);
|
||||
}
|
||||
|
||||
private void WriteInfo(string message)
|
||||
{
|
||||
WriteToEventLog(message, EventLogEntryType.Information);
|
||||
}
|
||||
|
||||
private void WriteException(Exception exception)
|
||||
{
|
||||
WriteToEventLog(exception.ToString(), EventLogEntryType.Error);
|
||||
}
|
||||
|
||||
private enum RunnerUpdateResult
|
||||
{
|
||||
Succeed,
|
||||
Failed,
|
||||
SucceedNeedRestart,
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern bool GenerateConsoleCtrlEvent(uint dwCtrlEvent, uint dwProcessGroupId);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern bool AttachConsole(uint dwProcessId);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
|
||||
private static extern bool FreeConsole();
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate HandlerRoutine, bool Add);
|
||||
|
||||
// Delegate type to be used as the Handler Routine for SetConsoleCtrlHandler
|
||||
delegate Boolean ConsoleCtrlDelegate(uint CtrlType);
|
||||
}
|
||||
}
|
||||
83
src/Runner.Service/Windows/RunnerService.csproj
Normal file
83
src/Runner.Service/Windows/RunnerService.csproj
Normal file
@@ -0,0 +1,83 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{D12EBD71-0464-46D0-8394-40BCFBA0A6F2}</ProjectGuid>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>RunnerService</RootNamespace>
|
||||
<AssemblyName>RunnerService</AssemblyName>
|
||||
<SignAssembly>true</SignAssembly>
|
||||
<AssemblyOriginatorKeyFile>FinalPublicKey.snk</AssemblyOriginatorKeyFile>
|
||||
<DelaySign>true</DelaySign>
|
||||
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<UseVSHostingProcess>false</UseVSHostingProcess>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Net.Http" />
|
||||
<Reference Include="System.ServiceProcess" />
|
||||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="RunnerService.cs">
|
||||
<SubType>Component</SubType>
|
||||
</Compile>
|
||||
<Compile Include="RunnerService.Designer.cs">
|
||||
<DependentUpon>RunnerService.cs</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Include="Program.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="Resource.Designer.cs">
|
||||
<AutoGen>True</AutoGen>
|
||||
<DesignTime>True</DesignTime>
|
||||
<DependentUpon>Resource.resx</DependentUpon>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="App.config" />
|
||||
<None Include="FinalPublicKey.snk" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Resource.resx">
|
||||
<Generator>ResXFileCodeGenerator</Generator>
|
||||
<LastGenOutput>Resource.Designer.cs</LastGenOutput>
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
||||
Reference in New Issue
Block a user