太阳当空照-Windows服务化方式Winsw应用

本篇文章主要讲解,在Windows上,实现服务化的一种方式,使用Winsw作为服务化的注册外壳,实现对程序的三方控制

ggcy-blog-service-sc-header

工具介绍

以下是官方解释,大概意思是,在有权限许可情况下,作为Windows服务的可执行容器,能够运行任何可执行程序,[传送门]https://github.com/winsw/winsw

A wrapper executable that can run any executable as a Windows service, in a permissive license

用户能够通过配置文件,将目标程序根据实际情况,通过Winsw实现系统中服务注册和运行使用,相比Instsrv.exeSrvany.exe从操作上会更偏向与配置,而不是直接操作系统注册表,减低繁琐度,但是同时也引入了,对于配置文件的操作复杂度,使用者需要为每一个目标服务程序,进行个性化配置

环境要求

WinSW 3 can run on Windows platforms with .NET Framework 4.6.1 or later versions installed. For systems without .NET Framework, the project provides native 64-bit and 32-bit executables based on .NET Core

Winsw.exe能够运行在安装有.Net Fx 4.6.1及其以上版本的系统中,对于没有.NET Fx的系统,该项目提供基于 .Net Core的本地 64 位32 位可执行程序

工具下载

下载链接:https://github.com/winsw/winsw/releases

目前最新版本v2.11.0

WinSW-x64.exe

https://github.com/winsw/winsw/releases/download/v2.11.0/WinSW-x64.exe

下载配置文件:

sample-allOptions.xml

https://github.com/winsw/winsw/releases/download/v2.11.0/sample-allOptions.xml

sample-minimal.xml】https://github.com/winsw/winsw/releases/download/v2.11.0/sample-minimal.xml

如果访问不到Github可以评论私信留言笔者获取资源

应用说明

由于Winsw.exe是由配置文件进行管理,运行对应的目标程序,都需要配置对应的配置文件xxxx.xml,一个配置文件对应着一个需要实现服务化的应用程序,以下是来自官方的安装参考内容:

Use WinSW as a global tool

  1. Take WinSW.exe or WinSW.zip from the distribution.
  2. Write myapp.xml (see the XML config file specification and samples for more details).
  3. Run winsw install myapp.xml [options\] to install the service.
  4. Run winsw start myapp.xml to start the service.
  5. Run winsw status myapp.xml to see if your service is up and running.

Use WinSW as a bundled tool

  1. Take WinSW.exe or WinSW.zip from the distribution, and rename the .exe to your taste (such as myapp.exe).
  2. Write myapp.xml (see the XML config file specification and samples for more details).
  3. Place those two files side by side, because that’s how WinSW discovers its co-related configuration.
  4. Run myapp.exe install [options\] to install the service.
  5. Run myapp.exe start to start the service.

由上述的内容可以知道Winsw.exe的使用分为两种类型,一种是将Winsw.exe作为全局指令使用,每次注册服务和启动服务通过配置文件进行逻辑处理

捆绑模式[通用]

下载程序后,依据实际需求,将winsw.exe放到特定目录下,并重命名,名称尽量与目标程序名称较为关联,例如,目标程序为nginx.exe,则可以重命名winsw.exenginxservice.exe,同时与nginxservice.exe同目录,设置对应配置文件,与nginxservice.exe名称保持一致,只是文件类型不同,之后对nginxservice.xml进行配置,最后进行相关的服务注册和操作,进行捆绑模式,一个启动程序对应一个服务启动配置实例

> [servicename.exe] install [options\]
> [servicename.exe] start
> [servicename.exe] status
> [servicename.exe] uninstall

全局模式[3.x版本]-目前不可用

Winsw.exe下载之后,放到一个系统环境变量相关的检索目录下,便于在当前系统的任意地方执行Winsw相关指令都能够实现相关程序的注册和启动,安装时指定对应的服务程序配置程序配置文件

> winsw isntall appname.xml [options\]
> winsw start appname.xml
> winsw status appname.xml
> winsw uninstall appname.xml

相关配置

参考笔者的另一篇文章太阳当空照-Windows服务化方式Winsw基本配置,服务化常用配置如下:

<service>
	<id>服务唯一标识</id>
    <name>服务简称</name>
    <description>服务描述</description>
    <startmode>服务启动模式</startmode>
    <executable>执行指令</executable>
    <startarguments>执行参数</startarguments>
    <workingdirectory>工作路径</workingdirectory>
    <logpath>日志输出路径,默认与配置文件同目录</logpath>
    <log mode="输出模式">
    	<sizeThreshold>10240</sizeThreshold>
		<pattern>yyyyMMdd</pattern>
    	<autoRollAtTime>00:00:00</autoRollAtTime>
    </log>
    <serviceaccount>
    	<username>服务启动账户,默认为本地系统账户</username>
    </serviceaccount>
</service>

相关指令

参考链接:https://github.com/winsw/winsw/tree/master

install to install the service to Windows Service Controller. This command requires some preliminary steps described in the Installation guide

安装windows服务控制器,命令的细节步骤可查看,安装细节引导:https://github.com/winsw/winsw/blob/master/doc/installation.md

uninstall to uninstall the service. The opposite operation of above

卸载服务,与安装指令用途相反

start to start the service. The service must have already been installed

在服务已经安装的前提下,启动服务

stop to stop the service

停止服务

stopwait to stop the service and wait until it’s actually stopped

等待停止,直到服务结束运行,实现服务停止

restart to restart the service. If the service is not currently running, this command acts like start

重启服务,如果服务未运行,效果与启动服务相似

status to check the current status of the service

This command prints one line to the console.

  • NonExistent indicates the service is not currently installed
  • Started to indicate the service is currently running
  • Stopped to indicate that the service is installed but not currently running

查看当前服务状态

执行以上命令需要以管理员身份进行执行

案例实践

控制台程序

此处基于.Net Core3创建了一个控制台,主要内容如下,启动后,循环每隔一秒写入时间到特定文件中,

static void Main(string[] args)
{
    while (true)
    {
        string datestr = DateTime.Now.ToString("HH:mm:ss");
        Thread.Sleep(1000);
        LogMsg(datestr);
    }
}

private static void LogMsg(string msg)
{
    //System.AppDomain.CurrentDomain.BaseDirectory
    //获取程序集目录:C:\Windows\Temp\.net\sctest

    //System.Environment.CurrentDirectory
    //获取该进程从中启动的目录:C:\Windows\system32

    //System.IO.Directory.GetCurrentDirectory()
    //获取当前应用工作路径:C:\Windows\system32

    //获取当前进程所属的执行exe文件名称
    string filename = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
    string dictoryPath = Path.GetDirectoryName(filename);
    string path = System.IO.Path.Combine(dictoryPath, $"{DateTime.Now.ToString("yyyy-MM-dd")}.log");
    using (var writer = File.AppendText(path))
    {
        writer.WriteLine($"当前时间:{msg}");
    }
}

配置服务

手动创建目录logs用于存储日志文件,配置文件可以参考官方案例

[sample-allOptions.xml]https://github.com/winsw/winsw/releases/download/v2.11.0/sample-allOptions.xml

[sample-minimal.xml]https://github.com/winsw/winsw/releases/download/v2.11.0/sample-minimal.xml

创建配置文件名称为test.xml,内容如下:

<service>
	<id>winswtest</id>
    <name>winsw测试服务</name>
    <description>当前用于测试winsw的服务化操作</description>
    <startmode>Automatic</startmode>
    <executable>winswtest.exe</executable>
    <startarguments></startarguments>
    <workingdirectory>%BASE%</workingdirectory>
    <logpath>%BASE%\logs</logpath>
    <log mode="roll-by-size-time">
    	<sizeThreshold>10240</sizeThreshold>
		<pattern>yyyyMMdd</pattern>
    	<autoRollAtTime>00:00:00</autoRollAtTime>
    </log>
    <serviceaccount>
    	<username>LocalSystem</username>
    </serviceaccount>
</service>

文件目录结构如下,当前目录为E:\Study\Servers\winswtest,读者按实际需求进行更改

blog-jrz-winsw-dir

直接运行winswtest.exe时,能够在当前目录下生成对应的.log文本,内容为时间读秒

blog-jrz-winsw-winswtest-run

注册服务

注册依据模式的不同而方式不同

捆绑模式[通用]

将下载的Winsw-x64.exe放到与winswtest.exe同目录下,并重命名为test.exe,并添加配置文件test.xml,保证服务程序和配置文件同名,以管理权限运行cmd,切换目录到test.exe所在目录下,执行服务安装指令

>cd /d E:\Study\Servers\winswtest
>test.exe install
2021-08-01 22:27:22,831 INFO  - Installing service 'winsw测试服务 (winswtest)'...
2021-08-01 22:27:22,859 INFO  - Service 'winsw测试服务 (winswtest)' was installed successfully.
>>test.exe status
Stopped

表示当前服务注册成功,同时也可以直接查看对应的系统服务列表,可以发现和上述注册安装服务时,基本信息一致,需要注意的是服务在【任务管理器】-【服务】中并不会显示出来,需要去到服务列表中进行查看

blog-jrz-winsw-winswtest-install

全局模式[3.x]-目前不可用

将下载的Winsw-x64.exe放到一个认为合适的文件目录下,并重命名为winsw.exe,配置环境变量WINSW_HOME,路径为存放winsw.exe所在目录,此处为D:\Program Files\Winsw

添加环境变量WINSW_HOME

blog-jrz-winsw-winswhome

新建后,将环境变量添加到Pathpath中,便于在系统任意位置能够访问到winsw.exe,便于指令的执行

blog-jrz-winsw-savepath

确认无误后,点击各级确定

打开cmd命令提示符窗口,输入winsw,查看是否收到指令提示,由于winsw本身无参数时无法任何结果反馈,此处随意输入一个参数,出现如下异常,则表示,全局环境配置成功

>winsw -h
2021-08-01 12:43:29,318 FATAL - Unhandled exception
System.IO.FileNotFoundException: Unable to locate winsw.[xml|yml] file within executable directory
   at WinSW.Program.LoadConfigAndInitLoggers(Boolean inConsoleMode)
   at WinSW.Program.Run(String[] argsArray, IServiceConfig config)
   at WinSW.Program.Main(String[] args)

出现'winsw' 不是内部或外部命令,也不是可运行的程序 或批处理文件。

常见原因有两个:

一个是环境变量配置错误,配置路径不正确,只是配置了WINSW_HOME,并没有将环境变量添加到path/Path中,实现全局可访问

一个是当前执行的cmd命令提示窗口,在配置环境变量前就已经打开,所以造成当前窗口,环境配置无效

启动服务

捆绑模式[通用]

test.exe所在目录中,直接服务启动指令

>test.exe start
2021-08-01 23:37:07,146 INFO  - Starting service 'winsw测试服务 (winswtest)'...
2021-08-01 23:37:07,626 INFO  - Service 'winsw测试服务 (winswtest)' started successfully.
>test.exe status
Started

服务启动成功后,当前目录下,生成输出文件

blog-jrz-winsw-winswtest-start

全局模式[3.x]

目前官方稳定最新版本为2.x版本,所有目前无法正常使用

停止服务

捆绑模式[通用]

执行指令stop

>test.exe stop
2021-08-01 23:42:08,123 INFO  - Stopping service 'winsw测试服务 (winswtest)'...
2021-08-01 23:42:08,131 INFO  - Service 'winsw测试服务 (winswtest)' stopped successfully.
>test.exe status
Stopped
全局模式[3.x]

目前官方稳定最新版本为2.x版本,所有目前无法正常使用

卸载服务

捆绑模式[通用]

执行指令uninstall

>test.exe uninstall
2021-08-01 23:43:49,221 INFO  - Uninstalling service 'winsw测试服务 (winswtest)'...
2021-08-01 23:43:49,227 INFO  - Service 'winsw测试服务 (winswtest)' was uninstalled successfully
全局模式[3.x]

目前官方稳定最新版本为2.x版本,所有目前无法正常使用

总结

对于winsw进行了依据官方文档,进行了细化的常规操作说明,实现一个简单的应用程序,作为服务化的的服务子进程的基本操作,比较遗憾的是,全局模式并未实现成功,通过查阅,发现目前版本为2.x版本,不包含3.x的全局模式,官方最新版本master分支当前为WinSW v2.11.0,后续如果官方更新到3.x笔者将再调整文档中的内容,如果还想关系其他服务化的操作方式,可留言评论,关注笔者或者私信

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值