浅谈如何使用 github.com/kardianos/service

打印 上一主题 下一主题

主题 995|帖子 995|积分 2985

在实际开发过程中,有时候会遇到如何编写Go开机自启服务的需求,在linux中我们可以使用systemd来进行托管,windows下可以通过注册表来实现,mac下可以通过launchd来实现,上面的方式对于开发者来说,并不是什么困难的事情,但是对于使用者而言,是并不希望通过这么复杂的方式来达到开机自启的功能的。这个时候,作为开发者,就需要使用其他的方式来实现开机自启的功能,下面讲一个Go中,借助这个库 github.com/kardianos/service 来简化如何实现开机自启功能。
1、github.com/kardianos/service 基础介绍

1.1 kardianos/service 简介

我们先来看一看  github.com/kardianos/service  上面的自我介绍:Run go programs as a service on major platforms.
如何理解上面这句话呢,上面这句话翻译出来的意思是:"在主要平台上将Go程序作为服务运行"。
这意味着我们可以将Go编写的程序以服务的形式在主要操作系统上运行,例如Windows、Linux、macOS等。这意味着程序可以在后台持续运行,而不需要用户手动启动或停止它们。这种方式可以提高程序的可靠性和稳定性,同时也方便了程序的管理和监控。
那该如何理解服务呢?
服务(Service)是指在计算机系统中,为用户或其他程序提供某种功能的程序或进程。服务通常在后台运行,可以长时间运行,不需要用户交互,可以自动启动和停止。服务可以提供各种功能,如网络服务、数据库服务、文件共享服务等。在操作系统中,服务通常以服务进程的形式运行,可以通过系统管理工具进行管理和配置。
有了上面的了解过后,再来看看官方自己的描述。service will install / un-install, start / stop, and run a program as a service (daemon). Currently supports Windows XP+, Linux/(systemd | Upstart | SysV), and OSX/Launchd. 如何理解上面这句话呢,我说说自己的理解。
我们可以将编写好的代码打包成二进制文件后,通过二进制文件名 + install / un-install, start / stop来运行我们的服务,程序将作为服务(守护进程)运行。目前支持Windows XP+、Linux/(systemd|Upstart|SysV)和OSX/Launchd。
Windows controls services by setting up callbacks that is non-trivial. This is very different then other systems. This package provides the same API despite the substantial differences. It also can be used to detect how a program is called, from an interactive terminal or from a service manager. 下面是我的理解:
Windows 通过设置回调来控制服务,这与其他系统非常不同。这个包提供了相同的API,尽管存在很大差异。它还可以用于检测程序是从交互式终端还是从服务管理器调用的。
看到这里的时候,我其他不太理解最后一句话,什么叫从服务管理器调用。将在 2.2 章节中介绍。
1.2 kardianos/service 安装

安装 github.com/kardianos/service 的方式和其他方式一样。
  1. go get github.com/kardianos/service
  2. 指定版本方式
  3. go get github.com/kardianos/service@v1.2.2
复制代码
2、kardianos/service 使用方式

以下介绍都是基于 github.com/kardianos/service@v1.2.2 进行讲解的。
2.1 kardianos/service 简单的使用

我们先来看一个简单的例子,代码如下:
  1. package main
  2. import (
  3.         "fmt"
  4.         "github.com/kardianos/service"
  5.         "os"
  6. )
  7. type SystemService struct {}
  8. func (ss *SystemService) Start(s service.Service) error {
  9.         fmt.Println("coming Start.......")
  10.         go ss.run()
  11.         return nil
  12. }
  13. func (ss *SystemService) run()  {
  14.         fmt.Println("coming run.......")
  15. }
  16. func (ss *SystemService) Stop(s service.Service) error {
  17.         fmt.Println("coming Stop.......")
  18.         return nil
  19. }
  20. func main()  {
  21.         fmt.Println("service.Interactive()---->", service.Interactive())
  22.         svcConfig := &service.Config{
  23.                 Name: "custom-service",
  24.                 DisplayName: "custom service",
  25.                 Description: "this is github.com/kardianos/service test case",
  26.         }
  27.         ss := &SystemService{}
  28.         s, err := service.New(ss, svcConfig)
  29.         if err != nil {
  30.                 fmt.Printf("service New failed, err: %v\n", err)
  31.                 os.Exit(1)
  32.         }
  33.         if len(os.Args) > 1 {
  34.                 err = service.Control(s, os.Args[1])
  35.                 if err != nil {
  36.                         fmt.Printf("service Control 111 failed, err: %v\n", err)
  37.                         os.Exit(1)
  38.                 }
  39.     return
  40.         }
  41.         // 默认 运行 Run
  42.         err = s.Run()
  43.         if err != nil {
  44.                 fmt.Printf("service Control 222 failed, err: %v\n", err)
  45.                 os.Exit(1)
  46.         }
  47. }
复制代码
通过go run main.go得到如下结果,注意:程序并不会终止,而是阻塞住了。
  1. service.Interactive()----> true
  2. coming Start.......
  3. coming run.......
复制代码
实际上,kardianos/service为我们提供了下面的参数使用,我们可以通过go build -o main main.go编译得到二进制文件,然后使用下面的命令来运行服务。
  1. # 生成开机自启服务所需要的文件,文件位置根据操作系统的不同而不用,linux在 /etc/systemd/system 或者 /lib/systemd/system 下
  2. ./main install
  3. # 删除上面生成的文件
  4. ./main uninstall
  5. # 开启服务
  6. ./main start
  7. # 重启服务
  8. ./main restart
  9. # 停止服务
  10. ./main stop
复制代码
2.2 kardianos/service 如何做开机自启服务

接下来以 Linux 为例,进行讲解。其他系统大家可自行尝试。
具体的步骤如下:
1、第一步是编写代码,编写完成后,编译成二进制文件。
代码就以 2.1 中的为例。首先编译成二进制文件。
  1. go build -o main main.go
复制代码
2、运行 可执行文件。
  1. # 这将在 /etc/systemd/system 或者 /lib/systemd/system 中生成 custom-service.service 文件
  2. # 我这里测试的时候是在 /etc/systemd/system 中生成的
  3. ./main install
复制代码
看到这里,用过systemd的朋友应该可以猜到 kardianos/service 背后是通过什么来实现开机自启的。就是通过systemd来管理的。
3、将 custom-service.service 服务设置为开机自启.
运行下面命令将我们编写的程序设置为开机自启服务。
  1. # 设置服务开机自启动
  2. systemctl enable test-service.service
  3. # 启动
  4. systemctl start test-service.service
复制代码
下面是systemctl常用的命令。
  1. # 启动
  2. systemctl start test-service.service
  3. # 停止
  4. systemctl stop test-service.service
  5. # 设置服务开机自启动
  6. systemctl enable test-service.service
  7. # 查询是否自启动服务
  8. systemctl is-enabled test-service.service
  9. # 取消服务器开机自启动
  10. systemctl disable test-service.service
  11. # 列出正在运行的服务
  12. systemctl list-units --type=service
复制代码
接下来我们看看服务管理器是什么意思?
1、./main install

2、查看custom-service.service文件

3、执行systemctl start custom-service.service后,查看服务运行过程

这里就是上面 服务管理器 的作用,也就是说,如何服务是手动运行的,那么 service.Interactive()返回 true,比如:./main start。如何是系统管理器运行的,则返回 false,比如:systemctl start custom-service.service。
2.3 结合 cli 使用

通过上面的例子,我们大概知道了如何使用  github.com/kardianos/service 。实际使用中,一般的服务都可以通过-h来查看帮助文档,但是我们我们通过./main -h会报错,所以需要完善下代码,使我们的程序更容易使用。下面,我们一起看看,借助 github.com/urfave/cli/v2 来完成上面的需求。
  1. package main
  2. import (
  3.         "fmt"
  4.         "github.com/kardianos/service"
  5.         "github.com/urfave/cli/v2"
  6.         "os"
  7. )
  8. type SystemService struct {}
  9. func (ss *SystemService) Start(s service.Service) error {
  10.         fmt.Println("coming Start.......")
  11.         go ss.run()
  12.         return nil
  13. }
  14. func (ss *SystemService) run()  {
  15.         fmt.Println("coming run.......")
  16. }
  17. func (ss *SystemService) Stop(s service.Service) error {
  18.         fmt.Println("coming Stop.......")
  19.         return nil
  20. }
  21. func main()  {
  22.         app := cli.NewApp()
  23.         app.Name = "custom-service"
  24.         app.Usage = "how to use custom service"
  25.         app.Commands = []*cli.Command{
  26.                 {
  27.                         Name: "install",
  28.                         Action: ctrlAction,
  29.                 },
  30.                 {
  31.                         Name: "uninstall",
  32.                         Action: ctrlAction,
  33.                 },
  34.                 {
  35.                         Name: "start",
  36.                         Action: ctrlAction,
  37.                 },
  38.                 {
  39.                         Name: "restart",
  40.                         Action: ctrlAction,
  41.                 },
  42.                 {
  43.                         Name: "stop",
  44.                         Action: ctrlAction,
  45.                 },
  46.         }
  47.         app.Flags = []cli.Flag{
  48.                 &cli.StringFlag{
  49.                         Name: "install",
  50.                         Value: "install",
  51.                         Usage: "Write the files required for startup",
  52.                 },
  53.                 &cli.StringFlag{
  54.                         Name: "uninstall",
  55.                         Value: "uninstall",
  56.                         Usage: "Delete startup files",
  57.                 },
  58.                 &cli.StringFlag{
  59.                         Name: "start",
  60.                         Value: "start",
  61.                         Usage: "start the service",
  62.                 },
  63.                 &cli.StringFlag{
  64.                         Name: "stop",
  65.                         Value: "stop",
  66.                         Usage: "stop the service",
  67.                 },
  68.                 &cli.StringFlag{
  69.                         Name: "restart",
  70.                         Value: "restart",
  71.                         Usage: "restart the service",
  72.                 },
  73.         }
  74.         app.Action = startAction
  75.         app.Run(os.Args)
  76. }
  77. func createSystemService() (service.Service, error) {
  78.   fmt.Println("service.Interactive()---->", service.Interactive())
  79.         svcConfig := &service.Config{
  80.                 Name: "custom-service",
  81.                 DisplayName: "custom service",
  82.                 Description: "this is github.com/kardianos/service test case",
  83.         }
  84.         ss := &SystemService{}
  85.         s, err := service.New(ss, svcConfig)
  86.         if err != nil {
  87.                 return nil, fmt.Errorf("service New failed, err: %v\n", err)
  88.         }
  89.         return s, nil
  90. }
  91. func ctrlAction(c *cli.Context) error  {
  92.         s, err := createSystemService()
  93.         if err != nil {
  94.                 fmt.Printf("createSystemService failed, err: %v\n", err)
  95.                 return err
  96.         }
  97.         err = service.Control(s, c.Command.Name)
  98.         if err != nil {
  99.                 fmt.Printf("service Run 222 failed, err: %v\n", err)
  100.                 return err
  101.         }
  102.         return nil
  103. }
  104. func startAction(c *cli.Context) error  {
  105.         s, err := createSystemService()
  106.         if err != nil {
  107.                 fmt.Printf("createSystemService failed, err: %v\n", err)
  108.                 return err
  109.         }
  110.         // 默认 运行 Run
  111.         err = s.Run()
  112.         if err != nil {
  113.                 fmt.Printf("service Run failed, err: %v\n", err)
  114.                 return err
  115.         }
  116.         return nil
  117. }
复制代码
大家可以根据自己的需求进行开发,这里只是讲一个简单的案例而已。
编译:
  1. go build -o main main.go
复制代码
运行:
  1. ./main -h
  2. NAME:
  3.    custom-service - how to use custom service
  4. USAGE:
  5.    custom-service [global options] command [command options] [arguments...]
  6. COMMANDS:
  7.    install   
  8.    uninstall  
  9.    start      
  10.    restart   
  11.    stop      
  12.    help, h    Shows a list of commands or help for one command
  13. GLOBAL OPTIONS:
  14.    --install value    Write the files required for startup (default: "install")
  15.    --uninstall value  Delete startup files (default: "uninstall")
  16.    --start value      start the service (default: "start")
  17.    --stop value       stop the service (default: "stop")
  18.    --restart value    restart the service (default: "restart")
  19.    --help, -h         show help
复制代码
3、浅谈 service 的执行过程

这里以 mac 为例,通过 goland 来查看调用的链路方便些。
使用   github.com/kardianos/service  的步骤大概是这样的:
1、定义 service.Config
2、通过 service.New 创建 service
3、通过 service.Control 来运行上面 生成好的 service。
第一步没啥好说的,注意 service.Config 中的 Name 是必须的,且生成的开机自启文件名就是以他命名的。
重点看看第二步,service.New源码入下:
  1. // New creates a new service based on a service interface and configuration.
  2. func New(i Interface, c *Config) (Service, error) {
  3.         //这就是为啥 Name 是必填的原因
  4.         if len(c.Name) == 0 {
  5.                 return nil, ErrNameFieldRequired
  6.         }
  7.         // 注意看这里,system 在使用到时候就已经初始化了,但是我们使用的时候,并没有做初始化 system 的动作。
  8.         // 那么什么时候初始化的 system 呢?
  9.         // 这个时候就会想到 init() 这个函数,这个函数在 import 时就会自动运行。
  10.         if system == nil {
  11.                 return nil, ErrNoServiceSystemDetected
  12.         }
  13.         return system.New(i, c)
  14. }
复制代码
System 接口如下:
  1. var (
  2.         system         System
  3.         systemRegistry []System
  4. )
  5. // System represents the service manager that is available.
  6. type System interface {
  7.         // String returns a description of the system.
  8.         String() string
  9.         // Detect returns true if the system is available to use.
  10.         Detect() bool
  11.         // Interactive returns false if running under the system service manager
  12.         // and true otherwise.
  13.         Interactive() bool
  14.         // New creates a new service for this system.
  15.         New(i Interface, c *Config) (Service, error)
  16. }
复制代码
以 mac 的系统为例, 讲讲system.New(i, c)
  1. type darwinSystem struct{}
  2. func (darwinSystem) String() string {
  3.         return version
  4. }
  5. func (darwinSystem) Detect() bool {
  6.         return true
  7. }
  8. func (darwinSystem) Interactive() bool {
  9.         return interactive
  10. }
  11. func (darwinSystem) New(i Interface, c *Config) (Service, error) {
  12.         s := &darwinLaunchdService{
  13.                 i:      i,
  14.                 Config: c,
  15.                 userService: c.Option.bool(optionUserService, optionUserServiceDefault),
  16.         }
  17.         return s, nil
  18. }
  19. func init() {
  20.   //这里就是给 system 变量赋值
  21.   //这里赋值有点不同,是在编译阶段由编译器根据系统的不同,初始化不同的 结构体。
  22.   //这个我也不敢确定,希望知道的朋友不吝赐教,感谢感谢!
  23.         ChooseSystem(darwinSystem{})
  24. }
  25. // ChooseSystem chooses a system from the given system services.
  26. // SystemServices are considered in the order they are suggested.
  27. // Calling this may change what Interactive and Platform return.
  28. func ChooseSystem(a ...System) {
  29.         systemRegistry = a
  30.         system = newSystem()
  31. }
复制代码
darwinLaunchdService实现了 Service interface 定义的方法。这里就不复制源代码了,有兴趣可以看看源代码。

以上就是我对  github.com/kardianos/service 的理解,有不对的地方,请不吝赐教。谢谢!

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

勿忘初心做自己

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表