123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143 |
- package middleware
- import (
- "fmt"
- "os"
- "path/filepath"
- "regexp"
- "sort"
- "xg_dba/internal/models"
- "github.com/mitchellh/mapstructure"
- "github.com/spf13/viper"
- )
- func InitCache(folderPath string) {
- packageModels := make(map[string]models.Cache)
- err := filepath.Walk(folderPath, func(path string, info os.FileInfo, err error) error {
- if err != nil {
- return err
- }
- if info.IsDir() {
- listenFilePath := filepath.Join(path, "listen.toml")
- var connectInfo models.ConnectInfo
- var systemMetaInfo models.SystemMetaInfo
-
- if fileExists(listenFilePath) {
- if err := parseTomlFile(listenFilePath, &connectInfo); err != nil {
- return err
- }
- }
-
- latestOsInfoFilePath, err := getLatestOsInfoFile(path)
- if err != nil {
- return err
- }
-
- if latestOsInfoFilePath != "" {
- if err := parseTomlFile(latestOsInfoFilePath, &systemMetaInfo); err != nil {
- return err
- }
- }
-
- host := connectInfo.Ssh.Host
- if host != "" {
- packageModels[host] = models.Cache{
- ConnectInfo: connectInfo,
- SystemMetaInfo: systemMetaInfo,
- }
- }
- }
- return nil
- })
- if err != nil {
- fmt.Printf("遍历路径 %q 时出错: %v\n", folderPath, err)
- return
- }
-
- for host, cache := range packageModels {
- fmt.Printf("主机: %s, 缓存: %+v\n", host, cache)
- }
- }
- func fileExists(filename string) bool {
- info, err := os.Stat(filename)
- if os.IsNotExist(err) {
- return false
- }
- return !info.IsDir()
- }
- func parseTomlFile(filePath string, v interface{}) error {
-
- vp := viper.New()
- vp.SetConfigFile(filePath)
- vp.SetConfigType("toml")
- if err := vp.ReadInConfig(); err != nil {
- return err
- }
-
- settings := vp.AllSettings()
- if err := decodeSettings(settings, v); err != nil {
- return err
- }
- return nil
- }
- func decodeSettings(settings map[string]interface{}, v interface{}) error {
- decoderConfig := &mapstructure.DecoderConfig{
- Result: v,
- TagName: "toml",
- WeaklyTypedInput: true,
- }
- decoder, err := mapstructure.NewDecoder(decoderConfig)
- if err != nil {
- return err
- }
- return decoder.Decode(settings)
- }
- func getLatestOsInfoFile(dirPath string) (string, error) {
- pattern := regexp.MustCompile(`^os_info(?:_\d{8}_\d{6})?\.toml$`)
- files, err := os.ReadDir(dirPath)
- if err != nil {
- return "", err
- }
- var matchingFiles []string
- for _, file := range files {
- if !file.IsDir() && pattern.MatchString(file.Name()) {
- matchingFiles = append(matchingFiles, filepath.Join(dirPath, file.Name()))
- }
- }
-
- if len(matchingFiles) == 0 {
- return "", nil
- }
-
- sort.Slice(matchingFiles, func(i, j int) bool {
- return matchingFiles[i] > matchingFiles[j]
- })
- return matchingFiles[0], nil
- }
|