Files
sunhpc-go/cmd/root.go
2026-02-18 17:09:52 +08:00

72 lines
1.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package cmd
import (
initcmd "sunhpc/cmd/init"
"sunhpc/cmd/soft"
"sunhpc/cmd/tmpl"
"sunhpc/internal/auth"
"sunhpc/internal/db"
"sunhpc/internal/log"
"github.com/spf13/cobra"
)
var (
cfgFile string
verbose bool
noColor bool
)
var rootCmd = &cobra.Command{
Use: "sunhpc",
Short: "SunHPC - HPC集群一体化运维工具",
PersistentPreRun: func(cmd *cobra.Command, args []string) {
// 初始化日志verbose=false 不显示调试信息)
log.Init(verbose)
// 是否禁用颜色
log.EnableColor(!noColor)
log.Debugf("当前命令 Annotations: %+v", cmd.Annotations)
_, err := db.CheckDB()
if err != nil {
log.Warnf("数据库检查失败: %v", err)
}
// 需要 root 权限
if cmd.Annotations["require-root"] == "true" {
if err := auth.RequireRoot(); err != nil {
log.Fatalf("需要 root 权限: %v", err)
}
}
log.Debugf("当前命令: %s", cmd.Name())
log.Debugf("详细模式: %v", verbose)
log.Debugf("禁用颜色: %v", noColor)
},
PersistentPostRun: func(cmd *cobra.Command, args []string) {
// 同步日志
log.Sync()
log.Close()
},
Run: func(cmd *cobra.Command, args []string) {
cmd.Help()
},
}
func Execute() error {
return rootCmd.Execute()
}
func init() {
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "配置文件路径 (默认为 /etc/sunhpc/sunhpc.yaml)")
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "启用详细日志输出")
rootCmd.PersistentFlags().BoolVar(&noColor, "no-color", false, "禁用彩色输出")
// 注册一级子命令下的子命令树
rootCmd.AddCommand(initcmd.Cmd)
rootCmd.AddCommand(soft.Cmd)
rootCmd.AddCommand(tmpl.Cmd)
}