golang实现注册系统服务(Windows、Darwin)

2023-12-20 13:52

本文主要是介绍golang实现注册系统服务(Windows、Darwin),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

golang实现注册系统服务(Windows、Darwin)

仓库地址:https://github.com/ziyifast/yiSystemService

使用第三方包:go get “github.com/kardianos/service”
日志库:go get “github.com/sirupsen/logrus”

  • log “github.com/sirupsen/logrus”

1 初始化日志

util/log.go:

package utilimport (log "github.com/sirupsen/logrus""io""os"
)func InitLog(logPath string) {//设置输出样式,自带的只有两种样式logrus.JSONFormatter{}和logrus.TextFormatter{}log.SetFormatter(&log.TextFormatter{})log.SetOutput(os.Stdout)//设置output,默认为stderr,可以为任何io.Writer,比如文件*os.Filefile, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)writers := []io.Writer{file,os.Stdout}//同时写文件和屏幕fileAndStdoutWriter := io.MultiWriter(writers...)if err == nil {log.SetOutput(fileAndStdoutWriter)} else {log.Info("failed to log to file.")}//设置最低loglevellog.SetLevel(log.InfoLevel)
}

2 导入三方Service库+编写serviceConfig(描述、可执行文件路径等)

2.1 consts

①consts/consts.go:

package constsimport "path"const (ServiceVersion     = "v1.0"ServiceName        = "yiService"ServicePort        = 9999ServiceDisplayName = "yi.service"ServiceDescription = "my test service"
)var LogPath stringfunc init() {LogPath = path.Join(WorkDir, "yiService.log")
}

②consts/consts_darwin.go:

//go:build darwin
// +build darwinpackage constsimport "path/filepath"var (StartupBash  = filepath.Join(WorkDir, "startup.sh")ShutdownBash = filepath.Join(WorkDir, "shutdown.sh")
)const (WorkDir = "/usr/local/yiService"MainExe = "yiService"
)    

③consts/consts_windows.go:

package constsimport "path/filepath"var (StartupBash  = filepath.Join(WorkDir, "startup.bat")ShutdownBash = filepath.Join(WorkDir, "shutdown.bat")
)const (WorkDir    = "c:/yiService"MainExe    = "yiService.exe"
)

2.2 system_service

system_service/system_service.go:

package system_serviceimport ("awesomeProject1/consts""fmt""github.com/kardianos/service"log "github.com/sirupsen/logrus""os""runtime"
)var (logger service.Loggersvc    service.Service
)func init() {svcConfig := &service.Config{Name:             consts.ServiceName,WorkingDirectory: consts.WorkDir,DisplayName:      consts.ServiceDisplayName,Description:      consts.ServiceDescription,Arguments:        []string{"service", "run"}, //服务注册成功之后,由服务去执行yiService.exe service run【运行服务】Executable:       fmt.Sprintf("%s/%s", consts.WorkDir, consts.ServiceName),Option:           service.KeyValue{},}if runtime.GOOS == "windows" {svcConfig.Executable = fmt.Sprintf("%s\\%s.exe", consts.WorkDir, consts.ServiceName)}var err errorprogram := &Program{}svc, err = service.New(program, svcConfig)if err != nil {log.Errorf("create service fail %v\n", err)return}errChan := make(chan error, 5)logger, err = svc.Logger(errChan)if err != nil {log.Errorf("%v\n", err)return}if err != nil {log.Errorf("%v\n", err)return}go func() {log.Info("watching err chan....")for {err := <-errChanif err != nil {log.Fatalf("service err %v", err)}}}()
}func StartSVC() {log.Infof("StartSVC...")serviceControl("install")serviceControl("start")
}func StopSVC() {log.Infof("try to stop service, if already exists.")serviceControl("stop")
}func RunSVC() {fmt.Sprintf("%s service running \n", runtime.GOOS)if err := svc.Run(); err != nil {fmt.Sprintf("%s service running fail %v \n", runtime.GOOS, err)os.Exit(1)}
}func serviceControl(action string) {log.Infof("%s service %s \n", runtime.GOOS, action)if err := service.Control(svc, action); err != nil {log.Infof("%s service: %v \n", action, err)}
}

3 编写服务脚本(startup、shutdown脚本)

3.1 startup脚本

  1. assets/startup.bat.tmpl
@echo off@REM It is recommended to start here.
@REM Modify bash args below.
@REM "name" and "tags" must be alphanumeric sequence: [a-zA-Z-_.]
@REM Chinese chars are not supported here in bash file.
@REM
@REM Example:
@REM
@REM yiService.exe service start ^
@REM
@REM Startup from here
@REM
c:/yiService/yiService.exe service startecho "yiService started!"
echo ""
pause
  1. assets/startup.sh.tmpl
#!/bin/bash# It is recommended to start here.
# Modify bash args below.
# "name" and "tags" must be alphanumeric sequence: [a-zA-Z-_.]
# Chinese chars are not supported here in bash file.
#
# Example:
#
# yiService.exe service start \
#
# Startup from here
#
# launchctl start yiService
./yiService service startecho yiService started!
ps aux |grep yiService
echo ""

3.2 shutdown脚本

  1. assets/shutdown.bat.tmpl
@echo off
@REM This command bash will stop the yiService windows service
@REM And then uninstall this service from operation system
@REM Configurations will be remained in directory c:/yiService/yiService on the disk.
@REM You can restart from those configurations in the near future.
@REM
c:/yiService/yiService.exe service stop
set "$process=yiService.exe"
for %%a in (%$process%) do tasklist /fi "imagename eq %%a"  | find "%%a" && taskkill /f /im %%aecho shutdown yiService successfully!
pause
  1. assets/shutdown.sh.tmpl
#!/bin/bash# This command bash will stop the yiService windows service
# And then uninstall this service from operation system
# Configurations will be remained in directory c:/yiService on the disk.
# You can restart from those configurations in the near future.
#./yiService service stop
PID=$(ps -eaf | grep '/usr/local/yiService' | grep -v grep | awk '{print $2}')
if [[ "" !=  "$PID" ]]; thenecho "killing $PID"kill -9 "$PID"
fiecho shutdown yiService successfully!

4 编写extractFiles(执行exe文件之后,拷贝exe到服务工作目录)

system_service/extract_files.go:

package system_serviceimport ("awesomeProject1/assets""awesomeProject1/consts""fmt"log "github.com/sirupsen/logrus""io""os""runtime"
)func ExtractFiles() {CopyMainExe()//copy startup\shutdownif err := os.WriteFile(consts.StartupBash, assets.StartupBatTmpl, os.ModePerm); err != nil {log.Errorf("create startup bash failed %v", err)}if err := os.WriteFile(consts.ShutdownBash, assets.ShutdownBatTmpl, os.ModePerm); err != nil {log.Errorf("create shutdown bash failed %v", err)}
}func CopyMainExe() {executable, err := os.Executable()log.Infof("install %s to %s", executable, consts.MainExe)if err != nil {log.Errorf("%v", err)}sFile, err := os.Open(executable)if err != nil {log.Errorf("%v", err)}defer sFile.Close()exePath := fmt.Sprintf("%s/%s", consts.WorkDir, consts.MainExe)if runtime.GOOS == "windows" {exePath = fmt.Sprintf("%s\\%s", consts.WorkDir, consts.MainExe)}_, err = os.Stat(exePath)if err == nil {//overwriteif err := os.RemoveAll(exePath); err != nil {log.Errorf("%v", err)}}eFile, err := os.Create(exePath)if err != nil {log.Errorf("%v", err)}defer eFile.Close()if _, err = io.Copy(eFile, sFile); err != nil {log.Errorf("%v", err)}if err = eFile.Sync(); err != nil {log.Errorf("%v", err)}if err = os.Chdir(consts.WorkDir); err != nil {log.Errorf("%v\n", err)}if err = os.Chmod(consts.MainExe, os.FileMode(0777)); err != nil {log.Errorf("%v", err)}
}

5 编写firewall部分+main函数部分(开放端口+由系统服务拉起进程)

firewall部分:以管理员身份运行,开放进程服务端口
cmd/main.go部分:初次运行尝试卸载服务,带os.Args参数运行启动服务

5.1 firewall部分

  1. darwin

system_service/firewall/firewall_darwin.go:

//go:build darwin
// +build darwinpackage firewallimport ("awesomeProject1/consts""bytes""fmt"log "github.com/sirupsen/logrus""os/exec""strconv""strings"
)func OpenPort() {log.Infof("darwin firewall checking\n")cmd0 := exec.Command("/usr/bin/nc", "-z", "127.0.0.1", fmt.Sprintf("%d", consts.ServicePort))log.Warnf("cmd0=%s\n", cmd0)stdout, err := cmd0.CombinedOutput()result := string(stdout)if err != nil {log.Infof("err=%v \n", err)return}if strings.Contains(result, "command not found") {fmt.Println("[warn]:", result)return}if strings.Contains(result, "not running") {fmt.Println("[warn]:", result)return}if strings.Contains(result, strconv.Itoa(consts.ServicePort)) {log.Warnf("%d already opened\n", consts.ServicePort)return}cmd := exec.Command("bash", "-c", fmt.Sprintf("firewall-cmd --zone=public --add-port=%d/tcp --permanent && firewall-cmd --reload", consts.ServicePort))var out bytes.Buffervar stderr bytes.Buffercmd.Stdout = &outcmd.Stderr = &stderrif err := cmd.Run(); err != nil {log.Warnf("%s", stderr.String())log.Warnf("%v", err)}log.Warnf(out.String())
}
  1. Windows
    system_service/firewall/firewall_windows.go
//go:build windows
// +build windowspackage firewallimport ("bytes""fmt"log "github.com/sirupsen/logrus""os/exec""runtime"
)func OpenPort() {log.Infot("windows firewall checking")cmd := exec.Command("cmd", "/c", "netsh advfirewall firewall delete rule name=\"yiService\"")var out bytes.Buffervar stderr bytes.Buffercmd.Stdout = &outcmd.Stderr = &stderrif runtime.GOOS == "windows" {}if err := cmd.Run(); err != nil {log.Errorf("%s", stderr.String())log.Errorf("%v", err)}cmd2 := exec.Command("cmd", "/c",fmt.Sprintf("netsh advfirewall firewall add rule name=\"yiService\" dir=in action=allow protocol=TCP localport=%d",consts.ServicePort,))var out2 bytes.Buffervar stderr2 bytes.Buffercmd2.Stdout = &out2cmd2.Stderr = &stderr2if runtime.GOOS == "windows" {}if err := cmd2.Run(); err != nil {log.Errorf("%s", stderr2.String())log.Errorf("%v", err)}
}

5.2 main函数

cmd/main.go

package mainimport ("awesomeProject1/consts""awesomeProject1/system_service""awesomeProject1/system_service/firewall""awesomeProject1/util"log "github.com/sirupsen/logrus""os"
)func init() {//os.Setenv("dev", "true")util.InitLog(consts.LogPath)
}func main() {if len(os.Getenv("dev")) != 0 {system_service.StopSVC()firewall.OpenPort()system_service.StartSVC()system_service.RunSVC()}log.Errorf("os.Args=%v len=%v \n", os.Args, len(os.Args))if len(os.Args) == 1 {//stop svc if existsystem_service.StopSVC()log.Errorf("install %v \n", consts.ServiceName)if err := os.MkdirAll(consts.WorkDir, os.ModePerm); err != nil {log.Errorf("%v\n", err)}firewall.OpenPort()system_service.ExtractFiles()pwd, err := os.Getwd()if err != nil {log.Errorf("%v\n", err)}log.Infof("install svc, working directory %s", pwd)system_service.StartSVC()log.Infof("yiService installed!")return}os.Chdir(consts.WorkDir)log.Errorf("service %s \n", os.Args[2])switch os.Args[2] {case "start":system_service.StartSVC()returncase "stop":system_service.StopSVC()returndefault:system_service.RunSVC()log.Info("running yiService")}
}

这篇关于golang实现注册系统服务(Windows、Darwin)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/516289

相关文章

golang中reflect包的常用方法

《golang中reflect包的常用方法》Go反射reflect包提供类型和值方法,用于获取类型信息、访问字段、调用方法等,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值... 目录reflect包方法总结类型 (Type) 方法值 (Value) 方法reflect包方法总结

MySQL中查找重复值的实现

《MySQL中查找重复值的实现》查找重复值是一项常见需求,比如在数据清理、数据分析、数据质量检查等场景下,我们常常需要找出表中某列或多列的重复值,具有一定的参考价值,感兴趣的可以了解一下... 目录技术背景实现步骤方法一:使用GROUP BY和HAVING子句方法二:仅返回重复值方法三:返回完整记录方法四:

IDEA中新建/切换Git分支的实现步骤

《IDEA中新建/切换Git分支的实现步骤》本文主要介绍了IDEA中新建/切换Git分支的实现步骤,通过菜单创建新分支并选择是否切换,创建后在Git详情或右键Checkout中切换分支,感兴趣的可以了... 前提:项目已被Git托管1、点击上方栏Git->NewBrancjsh...2、输入新的分支的

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

关于集合与数组转换实现方法

《关于集合与数组转换实现方法》:本文主要介绍关于集合与数组转换实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、Arrays.asList()1.1、方法作用1.2、内部实现1.3、修改元素的影响1.4、注意事项2、list.toArray()2.1、方

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

java实现docker镜像上传到harbor仓库的方式

《java实现docker镜像上传到harbor仓库的方式》:本文主要介绍java实现docker镜像上传到harbor仓库的方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 前 言2. 编写工具类2.1 引入依赖包2.2 使用当前服务器的docker环境推送镜像2.2

C++20管道运算符的实现示例

《C++20管道运算符的实现示例》本文简要介绍C++20管道运算符的使用与实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录标准库的管道运算符使用自己实现类似的管道运算符我们不打算介绍太多,因为它实际属于c++20最为重要的

Java easyExcel实现导入多sheet的Excel

《JavaeasyExcel实现导入多sheet的Excel》这篇文章主要为大家详细介绍了如何使用JavaeasyExcel实现导入多sheet的Excel,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录1.官网2.Excel样式3.代码1.官网easyExcel官网2.Excel样式3.代码

Linux中SSH服务配置的全面指南

《Linux中SSH服务配置的全面指南》作为网络安全工程师,SSH(SecureShell)服务的安全配置是我们日常工作中不可忽视的重要环节,本文将从基础配置到高级安全加固,全面解析SSH服务的各项参... 目录概述基础配置详解端口与监听设置主机密钥配置认证机制强化禁用密码认证禁止root直接登录实现双因素