阶段十:完成 Go Cmd Tools 注释基线清零
This commit is contained in:
1 parent
393c45a1e3
commit
ea1f2ec430
25 files changed
+694
-4281
No files matched your search
@@ -8,15 +8,21 @@ import (
|
||||
|
||||
// icon.png 是从根目录 icon/windows/icon.png 同步的彩色产品图标,并直接嵌入托盘二进制。
|
||||
//
|
||||
// productIconPNG 保存productIconPNG,供当前处理流程使用
|
||||
//
|
||||
//go:embed icon.png
|
||||
var productIconPNG []byte
|
||||
|
||||
// productIconGrayPNG 保存productIconGrayPNG,供当前处理流程使用
|
||||
//
|
||||
//go:embed icon-gray.png
|
||||
var productIconGrayPNG []byte
|
||||
|
||||
// trayIconBytes 返回当前服务状态对应的图标,避免运行时依赖外部图标文件。
|
||||
// Windows 的 Shell_NotifyIcon 需要 ICO;macOS/Linux 可以直接使用 PNG。
|
||||
// trayIconBytes 负责trayIconBytes相关处理。
|
||||
func trayIconBytes(running bool) []byte {
|
||||
// data 保存数据,供当前处理流程使用
|
||||
data := productIconGrayPNG
|
||||
if running {
|
||||
data = productIconPNG
|
||||
@@ -27,14 +33,19 @@ func trayIconBytes(running bool) []byte {
|
||||
return pngToICO(data, 256)
|
||||
}
|
||||
|
||||
// pngToICO 负责pngToICO相关处理。
|
||||
func pngToICO(data []byte, size int) []byte {
|
||||
// headerSize 保存header数量,供当前处理流程使用
|
||||
const headerSize = 6
|
||||
// entrySize 保存entry数量,供当前处理流程使用
|
||||
const entrySize = 16
|
||||
// result 保存结果,供当前处理流程使用
|
||||
result := make([]byte, headerSize+entrySize+len(data))
|
||||
// ICONDIR: reserved, type=icon, image count=1.
|
||||
binary.LittleEndian.PutUint16(result[0:2], 0)
|
||||
binary.LittleEndian.PutUint16(result[2:4], 1)
|
||||
binary.LittleEndian.PutUint16(result[4:6], 1)
|
||||
// entry 保存entry,供当前处理流程使用
|
||||
entry := result[headerSize : headerSize+entrySize]
|
||||
if size >= 256 {
|
||||
entry[0] = 0
|
||||
|
||||
@@ -10,25 +10,32 @@ import (
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// acquireTrayInstance 负责acquireTrayInstance相关处理。
|
||||
func acquireTrayInstance() (release func(), acquired bool, err error) {
|
||||
// cacheDirectory、err 保存cacheDirectory、err,供当前处理流程使用
|
||||
cacheDirectory, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("获取用户缓存目录失败: %w", err)
|
||||
}
|
||||
// lockDirectory 保存锁Directory,供当前处理流程使用
|
||||
lockDirectory := filepath.Join(cacheDirectory, "YdisksXianyuHelper")
|
||||
if err := os.MkdirAll(lockDirectory, 0o755); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := os.MkdirAll(lockDirectory, 0o755); err != nil {
|
||||
return nil, false, fmt.Errorf("创建托盘锁目录失败: %w", err)
|
||||
}
|
||||
|
||||
return acquireTrayFileLock(filepath.Join(lockDirectory, "tray.lock"))
|
||||
}
|
||||
|
||||
// acquireTrayFileLock 负责acquireTray文件锁相关处理。
|
||||
func acquireTrayFileLock(lockPath string) (release func(), acquired bool, err error) {
|
||||
// lockFile、err 保存锁File、err,供当前处理流程使用
|
||||
lockFile, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0o600)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("打开托盘锁文件失败: %w", err)
|
||||
}
|
||||
if err := unix.Flock(int(lockFile.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := unix.Flock(int(lockFile.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil {
|
||||
_ = lockFile.Close()
|
||||
if err == unix.EWOULDBLOCK || err == unix.EAGAIN {
|
||||
return func() {}, false, nil
|
||||
|
||||
@@ -7,8 +7,11 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestAcquireTrayInstanceRejectsSecondInstance 负责TestAcquireTrayInstanceRejectsSecondInstance相关处理。
|
||||
func TestAcquireTrayInstanceRejectsSecondInstance(t *testing.T) {
|
||||
// lockPath 保存锁路径,供当前处理流程使用
|
||||
lockPath := filepath.Join(t.TempDir(), "tray.lock")
|
||||
// releaseFirst、acquired、err 保存releaseFirst、acquired、err,供当前处理流程使用
|
||||
releaseFirst, acquired, err := acquireTrayFileLock(lockPath)
|
||||
if err != nil {
|
||||
t.Fatalf("acquire first tray instance: %v", err)
|
||||
@@ -18,6 +21,7 @@ func TestAcquireTrayInstanceRejectsSecondInstance(t *testing.T) {
|
||||
}
|
||||
defer releaseFirst()
|
||||
|
||||
// releaseSecond、acquired、err 保存releaseSecond、acquired、err,供当前处理流程使用
|
||||
releaseSecond, acquired, err := acquireTrayFileLock(lockPath)
|
||||
if err != nil {
|
||||
t.Fatalf("acquire second tray instance: %v", err)
|
||||
|
||||
@@ -8,11 +8,14 @@ import (
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// acquireTrayInstance 负责acquireTrayInstance相关处理。
|
||||
func acquireTrayInstance() (release func(), acquired bool, err error) {
|
||||
// mutexName、err 保存mutexName、err,供当前处理流程使用
|
||||
mutexName, err := windows.UTF16PtrFromString(`Local\YdisksXianyuHelperTray`)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("生成托盘互斥锁名称失败: %w", err)
|
||||
}
|
||||
// handle、err 保存handle、err,供当前处理流程使用
|
||||
handle, err := windows.CreateMutex(nil, false, mutexName)
|
||||
if err == windows.ERROR_ALREADY_EXISTS {
|
||||
if handle != 0 {
|
||||
|
||||
+79
-14
@@ -21,6 +21,7 @@ import (
|
||||
"fyne.io/systray"
|
||||
)
|
||||
|
||||
// healthResponse 保存health响应,供当前处理流程使用
|
||||
type healthResponse struct {
|
||||
Status string `json:"status"`
|
||||
Database string `json:"database"`
|
||||
@@ -28,17 +29,22 @@ type healthResponse struct {
|
||||
Commit string `json:"commit"`
|
||||
}
|
||||
|
||||
// serviceURL 保存serviceURL,供当前处理流程使用
|
||||
var serviceURL = strings.TrimRight(envOr("XIANYU_SERVICE_URL", "http://127.0.0.1:59188"), "/")
|
||||
|
||||
// actionMu 保存动作Mu,供当前处理流程使用
|
||||
var (
|
||||
actionMu sync.Mutex
|
||||
transitioning atomic.Bool
|
||||
exitRequested atomic.Bool
|
||||
)
|
||||
|
||||
// main 负责main相关处理。
|
||||
func main() {
|
||||
// closeLog 保存closeLog,供当前处理流程使用
|
||||
closeLog := configureTrayLogger()
|
||||
defer closeLog()
|
||||
// releaseInstance、acquired、err 保存releaseInstance、acquired、err,供当前处理流程使用
|
||||
releaseInstance, acquired, err := acquireTrayInstance()
|
||||
if err != nil {
|
||||
log.Printf("获取托盘单实例锁失败: %v", err)
|
||||
@@ -58,28 +64,35 @@ func main() {
|
||||
// 但实际托盘进程仍然存活。等事件循环真正返回后再处理外部退出。
|
||||
if !exitRequested.Load() {
|
||||
log.Printf("托盘事件循环结束,清理后台服务")
|
||||
if err := quitTray(); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := quitTray(); err != nil {
|
||||
log.Printf("清理后台服务失败: %v", err)
|
||||
} else if err := waitForService(&http.Client{Timeout: 2 * time.Second}, false, 30*time.Second); err != nil {
|
||||
} else if // err 保存err,供当前处理流程使用
|
||||
err := waitForService(&http.Client{Timeout: 2 * time.Second}, false, 30*time.Second); err != nil {
|
||||
log.Printf("等待后台服务退出失败: %v", err)
|
||||
}
|
||||
}
|
||||
log.Printf("托盘退出")
|
||||
}
|
||||
|
||||
// watchTerminationSignals 负责watchTerminationSignals相关处理。
|
||||
func watchTerminationSignals() {
|
||||
// signals 保存signals,供当前处理流程使用
|
||||
signals := make(chan os.Signal, 1)
|
||||
signal.Notify(signals, os.Interrupt, syscall.SIGTERM)
|
||||
go func() {
|
||||
// reason 保存原因,供当前处理流程使用
|
||||
reason := <-signals
|
||||
log.Printf("收到进程终止信号: %s", reason)
|
||||
|
||||
actionMu.Lock()
|
||||
// actionMu 保证不会与菜单动作并发;拿到锁时其它动作已经完成。
|
||||
transitioning.Store(true)
|
||||
if err := quitTray(); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := quitTray(); err != nil {
|
||||
log.Printf("终止前停止后台服务失败: %v", err)
|
||||
} else if err := waitForService(&http.Client{Timeout: 2 * time.Second}, false, 30*time.Second); err != nil {
|
||||
} else if // err 保存err,供当前处理流程使用
|
||||
err := waitForService(&http.Client{Timeout: 2 * time.Second}, false, 30*time.Second); err != nil {
|
||||
log.Printf("终止前等待后台服务退出失败: %v", err)
|
||||
}
|
||||
transitioning.Store(false)
|
||||
@@ -89,21 +102,27 @@ func watchTerminationSignals() {
|
||||
}()
|
||||
}
|
||||
|
||||
// onTrayExit 负责onTrayExit相关处理。
|
||||
func onTrayExit() {
|
||||
// 这里只记录事件。服务清理由 main 在 systray.Run 返回后执行,避免
|
||||
// 阻塞原生托盘事件循环。
|
||||
log.Printf("收到托盘退出事件")
|
||||
}
|
||||
|
||||
// configureTrayLogger 负责configureTrayLogger相关处理。
|
||||
func configureTrayLogger() func() {
|
||||
// directory、err 保存directory、err,供当前处理流程使用
|
||||
directory, err := logDirectoryPath()
|
||||
if err != nil {
|
||||
return func() {}
|
||||
}
|
||||
if err := os.MkdirAll(directory, 0o755); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := os.MkdirAll(directory, 0o755); err != nil {
|
||||
return func() {}
|
||||
}
|
||||
// path 保存路径,供当前处理流程使用
|
||||
path := filepath.Join(directory, "tray.log")
|
||||
// file、err 保存file、err,供当前处理流程使用
|
||||
file, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
|
||||
if err != nil {
|
||||
return func() {}
|
||||
@@ -113,19 +132,27 @@ func configureTrayLogger() func() {
|
||||
return func() { _ = file.Close() }
|
||||
}
|
||||
|
||||
// onReady 负责onReady相关处理。
|
||||
func onReady() {
|
||||
systray.SetTitle("")
|
||||
systray.SetIcon(trayIconBytes(false))
|
||||
systray.SetTooltip("Ydisks闲鱼助手服务")
|
||||
|
||||
// statusItem 保存状态商品,供当前处理流程使用
|
||||
statusItem := systray.AddMenuItem("服务状态:检查中", "读取后台服务状态")
|
||||
// openItem 保存open商品,供当前处理流程使用
|
||||
openItem := systray.AddMenuItem("打开管理页面", "在默认浏览器打开管理页面")
|
||||
// logItem 保存log商品,供当前处理流程使用
|
||||
logItem := systray.AddMenuItem("打开日志目录", "打开后台服务和托盘日志所在目录")
|
||||
systray.AddSeparator()
|
||||
// startItem 保存开始商品,供当前处理流程使用
|
||||
startItem := systray.AddMenuItem("启动服务", "启动后台服务")
|
||||
// stopItem 保存stop商品,供当前处理流程使用
|
||||
stopItem := systray.AddMenuItem("停止服务", "停止后台服务")
|
||||
// restartItem 保存restart商品,供当前处理流程使用
|
||||
restartItem := systray.AddMenuItem("重启服务", "重启后台服务")
|
||||
systray.AddSeparator()
|
||||
// quitItem 保存quit商品,供当前处理流程使用
|
||||
quitItem := systray.AddMenuItem("退出托盘", "停止后台服务并退出菜单栏控制器")
|
||||
|
||||
// 安装脚本只负责注册平台服务。用户再次打开托盘时,托盘本身必须确保
|
||||
@@ -136,41 +163,50 @@ func onReady() {
|
||||
refreshStatus(statusItem)
|
||||
}()
|
||||
go func() {
|
||||
// 局部数据 表示当前遍历过程中的局部数据
|
||||
for range openItem.ClickedCh {
|
||||
_ = openURL(serviceURL)
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
// 局部数据 表示当前遍历过程中的局部数据
|
||||
for range logItem.ClickedCh {
|
||||
if err := openLogDirectory(); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := openLogDirectory(); err != nil {
|
||||
statusItem.SetTitle("日志目录:打开失败")
|
||||
systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:打开日志目录失败:%v", err))
|
||||
}
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
// 局部数据 表示当前遍历过程中的局部数据
|
||||
for range startItem.ClickedCh {
|
||||
runServiceAction(statusItem, "启动服务", "启动中", "start", startItem, stopItem, restartItem, quitItem)
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
// 局部数据 表示当前遍历过程中的局部数据
|
||||
for range stopItem.ClickedCh {
|
||||
runServiceAction(statusItem, "停止服务", "正在停止", "stop", startItem, stopItem, restartItem, quitItem)
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
// 局部数据 表示当前遍历过程中的局部数据
|
||||
for range restartItem.ClickedCh {
|
||||
runServiceAction(statusItem, "重启服务", "正在重启", "restart", startItem, stopItem, restartItem, quitItem)
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
// 局部数据 表示当前遍历过程中的局部数据
|
||||
for range quitItem.ClickedCh {
|
||||
exitTray(statusItem, startItem, stopItem, restartItem, quitItem)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// refreshStatus 负责refresh状态相关处理。
|
||||
func refreshStatus(item *systray.MenuItem) {
|
||||
// client 保存client,供当前处理流程使用
|
||||
client := &http.Client{Timeout: 2 * time.Second}
|
||||
for {
|
||||
// 与菜单动作使用同一把锁,避免一次已经开始的健康检查在“启动中”
|
||||
@@ -184,7 +220,9 @@ func refreshStatus(item *systray.MenuItem) {
|
||||
}
|
||||
}
|
||||
|
||||
// refreshStatusOnce 负责refresh状态Once相关处理。
|
||||
func refreshStatusOnce(item *systray.MenuItem, client *http.Client) {
|
||||
// status、err 保存status、err,供当前处理流程使用
|
||||
status, err := readHealth(client)
|
||||
if err != nil {
|
||||
systray.SetIcon(trayIconBytes(false))
|
||||
@@ -201,6 +239,7 @@ func refreshStatusOnce(item *systray.MenuItem, client *http.Client) {
|
||||
}
|
||||
}
|
||||
|
||||
// runServiceAction 负责运行Service动作相关处理。
|
||||
func runServiceAction(statusItem *systray.MenuItem, actionName, transitionTitle, action string, actionItems ...*systray.MenuItem) {
|
||||
actionMu.Lock()
|
||||
defer actionMu.Unlock()
|
||||
@@ -215,23 +254,28 @@ func runServiceAction(statusItem *systray.MenuItem, actionName, transitionTitle,
|
||||
systray.SetIcon(trayIconBytes(false))
|
||||
statusItem.SetTitle("服务状态:" + transitionTitle)
|
||||
systray.SetTooltip("Ydisks闲鱼助手:" + transitionTitle)
|
||||
// client 保存client,供当前处理流程使用
|
||||
client := &http.Client{Timeout: 2 * time.Second}
|
||||
if action == "start" {
|
||||
if health, err := readHealth(client); err == nil && health.Status == "ok" && health.Database == "ok" {
|
||||
if // health、err 保存health、err,供当前处理流程使用
|
||||
health, err := readHealth(client); err == nil && health.Status == "ok" && health.Database == "ok" {
|
||||
statusItem.SetTitle("服务状态:运行正常")
|
||||
systray.SetIcon(trayIconBytes(true))
|
||||
systray.SetTooltip("Ydisks闲鱼助手:运行正常")
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := serviceAction(action); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := serviceAction(action); err != nil {
|
||||
log.Printf("服务操作失败: %s: %v", actionName, err)
|
||||
statusItem.SetTitle("服务状态:操作失败")
|
||||
systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:%s失败:%v", actionName, err))
|
||||
return
|
||||
}
|
||||
// wantRunning 保存wantRunning,供当前处理流程使用
|
||||
wantRunning := action != "stop"
|
||||
if err := waitForService(client, wantRunning, 30*time.Second); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := waitForService(client, wantRunning, 30*time.Second); err != nil {
|
||||
log.Printf("服务操作状态确认失败: %s: %v", actionName, err)
|
||||
statusItem.SetTitle("服务状态:操作失败")
|
||||
systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:%s后状态确认失败:%v", actionName, err))
|
||||
@@ -248,6 +292,7 @@ func runServiceAction(statusItem *systray.MenuItem, actionName, transitionTitle,
|
||||
log.Printf("服务操作完成: %s", actionName)
|
||||
}
|
||||
|
||||
// exitTray 负责exitTray相关处理。
|
||||
func exitTray(statusItem *systray.MenuItem, actionItems ...*systray.MenuItem) {
|
||||
actionMu.Lock()
|
||||
defer actionMu.Unlock()
|
||||
@@ -261,14 +306,16 @@ func exitTray(statusItem *systray.MenuItem, actionItems ...*systray.MenuItem) {
|
||||
systray.SetIcon(trayIconBytes(false))
|
||||
statusItem.SetTitle("托盘状态:正在退出")
|
||||
systray.SetTooltip("Ydisks闲鱼助手:正在停止后台服务")
|
||||
if err := quitTray(); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := quitTray(); err != nil {
|
||||
log.Printf("退出托盘停止服务失败: %v", err)
|
||||
statusItem.SetTitle("托盘状态:退出失败")
|
||||
systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:后台服务停止失败:%v", err))
|
||||
setMenuItemsDisabled(false, actionItems...)
|
||||
return
|
||||
}
|
||||
if err := waitForService(&http.Client{Timeout: 2 * time.Second}, false, 30*time.Second); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := waitForService(&http.Client{Timeout: 2 * time.Second}, false, 30*time.Second); err != nil {
|
||||
log.Printf("退出托盘等待服务停止失败: %v", err)
|
||||
statusItem.SetTitle("托盘状态:退出失败")
|
||||
systray.SetTooltip(fmt.Sprintf("Ydisks闲鱼助手:后台服务仍未退出:%v", err))
|
||||
@@ -280,7 +327,9 @@ func exitTray(statusItem *systray.MenuItem, actionItems ...*systray.MenuItem) {
|
||||
systray.Quit()
|
||||
}
|
||||
|
||||
// setMenuItemsDisabled 负责setMenu商品列表Disabled相关处理。
|
||||
func setMenuItemsDisabled(disabled bool, items ...*systray.MenuItem) {
|
||||
// item 表示当前遍历过程中的商品
|
||||
for _, item := range items {
|
||||
if disabled {
|
||||
item.Disable()
|
||||
@@ -290,10 +339,14 @@ func setMenuItemsDisabled(disabled bool, items ...*systray.MenuItem) {
|
||||
}
|
||||
}
|
||||
|
||||
// waitForService 负责waitForService相关处理。
|
||||
func waitForService(client *http.Client, wantRunning bool, timeout time.Duration) error {
|
||||
// deadline 保存deadline,供当前处理流程使用
|
||||
deadline := time.Now().Add(timeout)
|
||||
for {
|
||||
// health、reachable、err 保存health、reachable、err,供当前处理流程使用
|
||||
health, reachable, err := probeHealth(client)
|
||||
// running 保存running,供当前处理流程使用
|
||||
running := reachable && err == nil && health.Status == "ok" && health.Database == "ok"
|
||||
if wantRunning && running {
|
||||
return nil
|
||||
@@ -313,12 +366,16 @@ func waitForService(client *http.Client, wantRunning bool, timeout time.Duration
|
||||
}
|
||||
}
|
||||
|
||||
// readHealth 负责readHealth相关处理。
|
||||
func readHealth(client *http.Client) (healthResponse, error) {
|
||||
// health、err 保存health、err,供当前处理流程使用
|
||||
health, _, err := probeHealth(client)
|
||||
return health, err
|
||||
}
|
||||
|
||||
// probeHealth 负责probeHealth相关处理。
|
||||
func probeHealth(client *http.Client) (healthResponse, bool, error) {
|
||||
// resp、err 保存resp、err,供当前处理流程使用
|
||||
resp, err := client.Get(serviceURL + "/health")
|
||||
if err != nil {
|
||||
return healthResponse{}, false, err
|
||||
@@ -327,13 +384,16 @@ func probeHealth(client *http.Client) (healthResponse, bool, error) {
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return healthResponse{}, true, fmt.Errorf("health status %d", resp.StatusCode)
|
||||
}
|
||||
// health 保存health,供当前处理流程使用
|
||||
var health healthResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&health); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := json.NewDecoder(resp.Body).Decode(&health); err != nil {
|
||||
return healthResponse{}, true, err
|
||||
}
|
||||
return health, true, nil
|
||||
}
|
||||
|
||||
// openURL 负责openURL相关处理。
|
||||
func openURL(url string) error {
|
||||
if runtime.GOOS == "windows" {
|
||||
return exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
|
||||
@@ -341,12 +401,15 @@ func openURL(url string) error {
|
||||
return exec.Command("open", url).Start()
|
||||
}
|
||||
|
||||
// openLogDirectory 负责openLogDirectory相关处理。
|
||||
func openLogDirectory() error {
|
||||
// directory、err 保存directory、err,供当前处理流程使用
|
||||
directory, err := logDirectoryPath()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(directory, 0o755); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := os.MkdirAll(directory, 0o755); err != nil {
|
||||
return fmt.Errorf("创建日志目录失败: %w", err)
|
||||
}
|
||||
switch runtime.GOOS {
|
||||
@@ -359,8 +422,10 @@ func openLogDirectory() error {
|
||||
}
|
||||
}
|
||||
|
||||
// envOr 负责envOr相关处理。
|
||||
func envOr(name, fallback string) string {
|
||||
if value := strings.TrimSpace(os.Getenv(name)); value != "" {
|
||||
if // value 保存值,供当前处理流程使用
|
||||
value := strings.TrimSpace(os.Getenv(name)); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
|
||||
+22
-4
@@ -7,60 +7,78 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestWaitForServiceRequiresHealthyResponse 负责TestWaitForServiceRequiresHealthy响应相关处理。
|
||||
func TestWaitForServiceRequiresHealthyResponse(t *testing.T) {
|
||||
// server 保存server,供当前处理流程使用
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"status":"degraded","database":"error"}`))
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
// originalURL 保存originalURL,供当前处理流程使用
|
||||
originalURL := serviceURL
|
||||
serviceURL = server.URL
|
||||
t.Cleanup(func() { serviceURL = originalURL })
|
||||
|
||||
// client 保存client,供当前处理流程使用
|
||||
client := server.Client()
|
||||
if err := waitForService(client, true, 20*time.Millisecond); err == nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := waitForService(client, true, 20*time.Millisecond); err == nil {
|
||||
t.Fatal("degraded health response must not count as running")
|
||||
}
|
||||
}
|
||||
|
||||
// TestWaitForServiceAcceptsHealthyResponse 负责TestWaitForServiceAcceptsHealthy响应相关处理。
|
||||
func TestWaitForServiceAcceptsHealthyResponse(t *testing.T) {
|
||||
// server 保存server,供当前处理流程使用
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"status":"ok","database":"ok"}`))
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
// originalURL 保存originalURL,供当前处理流程使用
|
||||
originalURL := serviceURL
|
||||
serviceURL = server.URL
|
||||
t.Cleanup(func() { serviceURL = originalURL })
|
||||
|
||||
if err := waitForService(server.Client(), true, time.Second); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := waitForService(server.Client(), true, time.Second); err != nil {
|
||||
t.Fatalf("healthy response should count as running: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWaitForServiceDoesNotTreatUnhealthyResponseAsStopped 负责TestWaitForServiceDoesNotTreatUnhealthy响应AsStopped相关处理。
|
||||
func TestWaitForServiceDoesNotTreatUnhealthyResponseAsStopped(t *testing.T) {
|
||||
// server 保存server,供当前处理流程使用
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
// originalURL 保存originalURL,供当前处理流程使用
|
||||
originalURL := serviceURL
|
||||
serviceURL = server.URL
|
||||
t.Cleanup(func() { serviceURL = originalURL })
|
||||
|
||||
if err := waitForService(server.Client(), false, 20*time.Millisecond); err == nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := waitForService(server.Client(), false, 20*time.Millisecond); err == nil {
|
||||
t.Fatal("reachable unhealthy service must not count as stopped")
|
||||
}
|
||||
}
|
||||
|
||||
// TestWaitForServiceAcceptsUnreachableAsStopped 负责TestWaitForServiceAcceptsUnreachableAsStopped相关处理。
|
||||
func TestWaitForServiceAcceptsUnreachableAsStopped(t *testing.T) {
|
||||
// server 保存server,供当前处理流程使用
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
|
||||
// client 保存client,供当前处理流程使用
|
||||
client := server.Client()
|
||||
// originalURL 保存originalURL,供当前处理流程使用
|
||||
originalURL := serviceURL
|
||||
serviceURL = server.URL
|
||||
t.Cleanup(func() { serviceURL = originalURL })
|
||||
server.Close()
|
||||
|
||||
if err := waitForService(client, false, time.Second); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := waitForService(client, false, time.Second); err != nil {
|
||||
t.Fatalf("unreachable service should count as stopped: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -11,47 +11,62 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// serviceAction 负责service动作相关处理。
|
||||
func serviceAction(action string) error {
|
||||
// label 保存label,供当前处理流程使用
|
||||
label := envOr("XIANYU_SERVICE_NAME", "com.ydisks.xianyu-helper.server")
|
||||
// uid 保存uid,供当前处理流程使用
|
||||
uid := fmt.Sprint(os.Getuid())
|
||||
// domain 保存domain,供当前处理流程使用
|
||||
domain := "gui/" + uid
|
||||
// target 保存target,供当前处理流程使用
|
||||
target := domain + "/" + label
|
||||
// home、err 保存home、err,供当前处理流程使用
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return fmt.Errorf("获取用户目录失败: %w", err)
|
||||
}
|
||||
// plistPath 保存plist路径,供当前处理流程使用
|
||||
plistPath := filepath.Join(home, "Library", "LaunchAgents", label+".plist")
|
||||
switch action {
|
||||
case "start":
|
||||
if err := launchctl("print", target); err == nil {
|
||||
if err := launchctl("kickstart", target); err == nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := launchctl("print", target); err == nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := launchctl("kickstart", target); err == nil {
|
||||
return nil
|
||||
}
|
||||
// launchd 可能仍保留一个正在退出的旧 job;先完整卸载,
|
||||
// 等它消失后再 bootstrap,避免第二次启动报 Input/output error。
|
||||
_ = launchctl("bootout", target)
|
||||
if err := waitForLaunchctlGone(target, 10*time.Second); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := waitForLaunchctlGone(target, 10*time.Second); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := launchctl("bootstrap", domain, plistPath); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := launchctl("bootstrap", domain, plistPath); err != nil {
|
||||
return err
|
||||
}
|
||||
return launchctl("kickstart", target)
|
||||
case "stop":
|
||||
if err := launchctl("print", target); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := launchctl("print", target); err != nil {
|
||||
return nil
|
||||
}
|
||||
if err := launchctl("bootout", target); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := launchctl("bootout", target); err != nil {
|
||||
return err
|
||||
}
|
||||
return waitForLaunchctlGone(target, 10*time.Second)
|
||||
case "restart":
|
||||
_ = launchctl("bootout", target)
|
||||
if err := waitForLaunchctlGone(target, 10*time.Second); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := waitForLaunchctlGone(target, 10*time.Second); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := launchctl("bootstrap", domain, plistPath); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := launchctl("bootstrap", domain, plistPath); err != nil {
|
||||
return err
|
||||
}
|
||||
return launchctl("kickstart", target)
|
||||
@@ -60,10 +75,13 @@ func serviceAction(action string) error {
|
||||
}
|
||||
}
|
||||
|
||||
// waitForLaunchctlGone 负责waitForLaunchctlGone相关处理。
|
||||
func waitForLaunchctlGone(target string, timeout time.Duration) error {
|
||||
// deadline 保存deadline,供当前处理流程使用
|
||||
deadline := time.Now().Add(timeout)
|
||||
for {
|
||||
if err := launchctl("print", target); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := launchctl("print", target); err != nil {
|
||||
return nil
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
@@ -73,8 +91,10 @@ func waitForLaunchctlGone(target string, timeout time.Duration) error {
|
||||
}
|
||||
}
|
||||
|
||||
// quitTray 负责quitTray相关处理。
|
||||
func quitTray() error {
|
||||
if err := serviceAction("stop"); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := serviceAction("stop"); err != nil {
|
||||
return fmt.Errorf("停止后台服务失败: %w", err)
|
||||
}
|
||||
// 不要从托盘进程内部 bootout 自己的 LaunchAgent。launchctl 可能会先
|
||||
@@ -83,7 +103,9 @@ func quitTray() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// logDirectoryPath 负责logDirectory路径相关处理。
|
||||
func logDirectoryPath() (string, error) {
|
||||
// home、err 保存home、err,供当前处理流程使用
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("获取用户目录失败: %w", err)
|
||||
@@ -91,10 +113,14 @@ func logDirectoryPath() (string, error) {
|
||||
return filepath.Join(home, "Library", "Logs", "YdisksXianyuHelper"), nil
|
||||
}
|
||||
|
||||
// launchctl 负责launchctl相关处理。
|
||||
func launchctl(args ...string) error {
|
||||
// cmd 保存cmd,供当前处理流程使用
|
||||
cmd := exec.Command("launchctl", args...)
|
||||
// output、err 保存output、err,供当前处理流程使用
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
// message 保存消息,供当前处理流程使用
|
||||
message := strings.TrimSpace(string(output))
|
||||
if message == "" {
|
||||
return fmt.Errorf("launchctl %s 失败: %w", strings.Join(args, " "), err)
|
||||
|
||||
@@ -7,12 +7,15 @@ import (
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// serviceAction 负责service动作相关处理。
|
||||
func serviceAction(action string) error {
|
||||
return fmt.Errorf("当前平台不支持托盘服务操作: %s", action)
|
||||
}
|
||||
|
||||
// quitTray 负责quitTray相关处理。
|
||||
func quitTray() error { return nil }
|
||||
|
||||
// logDirectoryPath 负责logDirectory路径相关处理。
|
||||
func logDirectoryPath() (string, error) {
|
||||
return filepath.Join("/var", "log", "ydisks-xianyu-helper"), nil
|
||||
}
|
||||
@@ -13,8 +13,10 @@ import (
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// windowsServiceAccess 保存windowsServiceAccess,供当前处理流程使用
|
||||
const windowsServiceAccess = windows.SERVICE_QUERY_STATUS | windows.SERVICE_START | windows.SERVICE_STOP
|
||||
|
||||
// windowsServiceController 保存windowsService请求取消控制器,供当前处理流程使用
|
||||
type windowsServiceController interface {
|
||||
state() (uint32, error)
|
||||
start() error
|
||||
@@ -22,16 +24,20 @@ type windowsServiceController interface {
|
||||
close()
|
||||
}
|
||||
|
||||
// nativeWindowsServiceController 保存nativeWindowsService请求取消控制器,供当前处理流程使用
|
||||
type nativeWindowsServiceController struct {
|
||||
handle windows.Handle
|
||||
}
|
||||
|
||||
// serviceAction 负责service动作相关处理。
|
||||
func serviceAction(action string) error {
|
||||
if action != "start" && action != "stop" && action != "restart" {
|
||||
return fmt.Errorf("未知服务操作: %s", action)
|
||||
}
|
||||
|
||||
// name 保存名称,供当前处理流程使用
|
||||
name := envOr("XIANYU_SERVICE_NAME", "YdisksXianyuHelper")
|
||||
// controller、err 保存controller、err,供当前处理流程使用
|
||||
controller, err := openWindowsServiceController(name)
|
||||
if err != nil {
|
||||
if action == "stop" && errors.Is(err, windows.ERROR_SERVICE_DOES_NOT_EXIST) {
|
||||
@@ -50,17 +56,21 @@ func serviceAction(action string) error {
|
||||
return controlWindowsService(controller, action, 30*time.Second, 250*time.Millisecond)
|
||||
}
|
||||
|
||||
// openWindowsServiceController 负责openWindowsService请求取消控制器相关处理。
|
||||
func openWindowsServiceController(name string) (windowsServiceController, error) {
|
||||
// manager、err 保存manager、err,供当前处理流程使用
|
||||
manager, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_CONNECT)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer windows.CloseServiceHandle(manager) //nolint:errcheck
|
||||
|
||||
// namePointer、err 保存名称Pointer、err,供当前处理流程使用
|
||||
namePointer, err := windows.UTF16PtrFromString(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// handle、err 保存handle、err,供当前处理流程使用
|
||||
handle, err := windows.OpenService(manager, namePointer, windowsServiceAccess)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -68,6 +78,7 @@ func openWindowsServiceController(name string) (windowsServiceController, error)
|
||||
return &nativeWindowsServiceController{handle: handle}, nil
|
||||
}
|
||||
|
||||
// controlWindowsService 负责controlWindowsService相关处理。
|
||||
func controlWindowsService(controller windowsServiceController, action string, timeout, pollInterval time.Duration) error {
|
||||
switch action {
|
||||
case "start":
|
||||
@@ -75,7 +86,8 @@ func controlWindowsService(controller windowsServiceController, action string, t
|
||||
case "stop":
|
||||
return ensureWindowsServiceStopped(controller, timeout, pollInterval)
|
||||
case "restart":
|
||||
if err := ensureWindowsServiceStopped(controller, timeout, pollInterval); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := ensureWindowsServiceStopped(controller, timeout, pollInterval); err != nil {
|
||||
return err
|
||||
}
|
||||
return ensureWindowsServiceRunning(controller, timeout, pollInterval)
|
||||
@@ -84,7 +96,9 @@ func controlWindowsService(controller windowsServiceController, action string, t
|
||||
}
|
||||
}
|
||||
|
||||
// ensureWindowsServiceRunning 负责ensureWindowsServiceRunning相关处理。
|
||||
func ensureWindowsServiceRunning(controller windowsServiceController, timeout, pollInterval time.Duration) error {
|
||||
// state、err 保存state、err,供当前处理流程使用
|
||||
state, err := controller.state()
|
||||
if err != nil {
|
||||
return fmt.Errorf("查询 Windows 服务状态失败: %w", err)
|
||||
@@ -95,18 +109,22 @@ func ensureWindowsServiceRunning(controller windowsServiceController, timeout, p
|
||||
case windows.SERVICE_START_PENDING:
|
||||
return waitForWindowsServiceState(controller, windows.SERVICE_RUNNING, timeout, pollInterval)
|
||||
case windows.SERVICE_STOP_PENDING:
|
||||
if err := waitForWindowsServiceState(controller, windows.SERVICE_STOPPED, timeout, pollInterval); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := waitForWindowsServiceState(controller, windows.SERVICE_STOPPED, timeout, pollInterval); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := controller.start(); err != nil && !errors.Is(err, windows.ERROR_SERVICE_ALREADY_RUNNING) {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := controller.start(); err != nil && !errors.Is(err, windows.ERROR_SERVICE_ALREADY_RUNNING) {
|
||||
return fmt.Errorf("启动 Windows 服务失败: %w", err)
|
||||
}
|
||||
return waitForWindowsServiceState(controller, windows.SERVICE_RUNNING, timeout, pollInterval)
|
||||
}
|
||||
|
||||
// ensureWindowsServiceStopped 负责ensureWindowsServiceStopped相关处理。
|
||||
func ensureWindowsServiceStopped(controller windowsServiceController, timeout, pollInterval time.Duration) error {
|
||||
// state、err 保存state、err,供当前处理流程使用
|
||||
state, err := controller.state()
|
||||
if err != nil {
|
||||
return fmt.Errorf("查询 Windows 服务状态失败: %w", err)
|
||||
@@ -117,20 +135,25 @@ func ensureWindowsServiceStopped(controller windowsServiceController, timeout, p
|
||||
case windows.SERVICE_STOP_PENDING:
|
||||
return waitForWindowsServiceState(controller, windows.SERVICE_STOPPED, timeout, pollInterval)
|
||||
case windows.SERVICE_START_PENDING:
|
||||
if err := waitForWindowsServiceState(controller, windows.SERVICE_RUNNING, timeout, pollInterval); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := waitForWindowsServiceState(controller, windows.SERVICE_RUNNING, timeout, pollInterval); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := controller.stop(); err != nil && !errors.Is(err, windows.ERROR_SERVICE_NOT_ACTIVE) {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := controller.stop(); err != nil && !errors.Is(err, windows.ERROR_SERVICE_NOT_ACTIVE) {
|
||||
return fmt.Errorf("停止 Windows 服务失败: %w", err)
|
||||
}
|
||||
return waitForWindowsServiceState(controller, windows.SERVICE_STOPPED, timeout, pollInterval)
|
||||
}
|
||||
|
||||
// waitForWindowsServiceState 负责waitForWindowsService状态相关处理。
|
||||
func waitForWindowsServiceState(controller windowsServiceController, expected uint32, timeout, pollInterval time.Duration) error {
|
||||
// deadline 保存deadline,供当前处理流程使用
|
||||
deadline := time.Now().Add(timeout)
|
||||
for {
|
||||
// state、err 保存state、err,供当前处理流程使用
|
||||
state, err := controller.state()
|
||||
if err != nil {
|
||||
return fmt.Errorf("查询 Windows 服务状态失败: %w", err)
|
||||
@@ -145,37 +168,49 @@ func waitForWindowsServiceState(controller windowsServiceController, expected ui
|
||||
}
|
||||
}
|
||||
|
||||
// state 负责状态相关处理。
|
||||
func (controller *nativeWindowsServiceController) state() (uint32, error) {
|
||||
// status 保存状态,供当前处理流程使用
|
||||
var status windows.SERVICE_STATUS
|
||||
if err := windows.QueryServiceStatus(controller.handle, &status); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := windows.QueryServiceStatus(controller.handle, &status); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return status.CurrentState, nil
|
||||
}
|
||||
|
||||
// start 负责开始相关处理。
|
||||
func (controller *nativeWindowsServiceController) start() error {
|
||||
return windows.StartService(controller.handle, 0, nil)
|
||||
}
|
||||
|
||||
// stop 负责stop相关处理。
|
||||
func (controller *nativeWindowsServiceController) stop() error {
|
||||
// status 保存状态,供当前处理流程使用
|
||||
var status windows.SERVICE_STATUS
|
||||
return windows.ControlService(controller.handle, windows.SERVICE_CONTROL_STOP, &status)
|
||||
}
|
||||
|
||||
// close 负责close相关处理。
|
||||
func (controller *nativeWindowsServiceController) close() {
|
||||
_ = windows.CloseServiceHandle(controller.handle)
|
||||
}
|
||||
|
||||
// quitTray 负责quitTray相关处理。
|
||||
func quitTray() error {
|
||||
if err := serviceAction("stop"); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := serviceAction("stop"); err != nil {
|
||||
return fmt.Errorf("停止后台服务失败: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// logDirectoryPath 负责logDirectory路径相关处理。
|
||||
func logDirectoryPath() (string, error) {
|
||||
// base 保存base,供当前处理流程使用
|
||||
base := strings.TrimSpace(os.Getenv("PROGRAMDATA"))
|
||||
if base == "" {
|
||||
// err 保存err,供当前处理流程使用
|
||||
var err error
|
||||
base, err = os.UserConfigDir()
|
||||
if err != nil {
|
||||
|
||||
@@ -11,15 +11,18 @@ import (
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// fakeWindowsServiceController 保存fakeWindowsService请求取消控制器,供当前处理流程使用
|
||||
type fakeWindowsServiceController struct {
|
||||
states []uint32
|
||||
actions []string
|
||||
}
|
||||
|
||||
// state 负责状态相关处理。
|
||||
func (controller *fakeWindowsServiceController) state() (uint32, error) {
|
||||
if len(controller.states) == 0 {
|
||||
return 0, fmt.Errorf("测试状态序列为空")
|
||||
}
|
||||
// state 保存状态,供当前处理流程使用
|
||||
state := controller.states[0]
|
||||
if len(controller.states) > 1 {
|
||||
controller.states = controller.states[1:]
|
||||
@@ -27,19 +30,24 @@ func (controller *fakeWindowsServiceController) state() (uint32, error) {
|
||||
return state, nil
|
||||
}
|
||||
|
||||
// start 负责开始相关处理。
|
||||
func (controller *fakeWindowsServiceController) start() error {
|
||||
controller.actions = append(controller.actions, "start")
|
||||
return nil
|
||||
}
|
||||
|
||||
// stop 负责stop相关处理。
|
||||
func (controller *fakeWindowsServiceController) stop() error {
|
||||
controller.actions = append(controller.actions, "stop")
|
||||
return nil
|
||||
}
|
||||
|
||||
// close 负责close相关处理。
|
||||
func (controller *fakeWindowsServiceController) close() {}
|
||||
|
||||
// TestWindowsRestartWaitsForStoppedBeforeStarting 负责TestWindowsRestartWaitsForStoppedBeforeStarting相关处理。
|
||||
func TestWindowsRestartWaitsForStoppedBeforeStarting(t *testing.T) {
|
||||
// controller 保存请求取消控制器,供当前处理流程使用
|
||||
controller := &fakeWindowsServiceController{
|
||||
states: []uint32{
|
||||
windows.SERVICE_RUNNING,
|
||||
@@ -50,15 +58,19 @@ func TestWindowsRestartWaitsForStoppedBeforeStarting(t *testing.T) {
|
||||
windows.SERVICE_RUNNING,
|
||||
},
|
||||
}
|
||||
if err := controlWindowsService(controller, "restart", time.Second, time.Millisecond); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := controlWindowsService(controller, "restart", time.Second, time.Millisecond); err != nil {
|
||||
t.Fatalf("restart Windows service: %v", err)
|
||||
}
|
||||
if want := []string{"stop", "start"}; !reflect.DeepEqual(controller.actions, want) {
|
||||
if // want 保存want,供当前处理流程使用
|
||||
want := []string{"stop", "start"}; !reflect.DeepEqual(controller.actions, want) {
|
||||
t.Fatalf("actions = %v, want %v", controller.actions, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWindowsStartWaitsForPreviousStop 负责TestWindows开始WaitsForPreviousStop相关处理。
|
||||
func TestWindowsStartWaitsForPreviousStop(t *testing.T) {
|
||||
// controller 保存请求取消控制器,供当前处理流程使用
|
||||
controller := &fakeWindowsServiceController{
|
||||
states: []uint32{
|
||||
windows.SERVICE_STOP_PENDING,
|
||||
@@ -67,15 +79,19 @@ func TestWindowsStartWaitsForPreviousStop(t *testing.T) {
|
||||
windows.SERVICE_RUNNING,
|
||||
},
|
||||
}
|
||||
if err := controlWindowsService(controller, "start", time.Second, time.Millisecond); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := controlWindowsService(controller, "start", time.Second, time.Millisecond); err != nil {
|
||||
t.Fatalf("start Windows service: %v", err)
|
||||
}
|
||||
if want := []string{"start"}; !reflect.DeepEqual(controller.actions, want) {
|
||||
if // want 保存want,供当前处理流程使用
|
||||
want := []string{"start"}; !reflect.DeepEqual(controller.actions, want) {
|
||||
t.Fatalf("actions = %v, want %v", controller.actions, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWindowsServiceAccessIsLimitedToStatusStartStop 负责TestWindowsServiceAccessIsLimitedTo状态开始Stop相关处理。
|
||||
func TestWindowsServiceAccessIsLimitedToStatusStartStop(t *testing.T) {
|
||||
// want 保存want,供当前处理流程使用
|
||||
want := uint32(windows.SERVICE_QUERY_STATUS | windows.SERVICE_START | windows.SERVICE_STOP)
|
||||
if windowsServiceAccess != want {
|
||||
t.Fatalf("service access = %#x, want %#x", windowsServiceAccess, want)
|
||||
|
||||
Reference in new issue
Block a user