018. 工具篇(日志/ssh连接/配置文件路径)

git地址

前几天因为公司的云主机连接外网突然故障,导致几台服务器无法提供服务,为了定时的探测网络状态,写了一个小工具,其中里面可以复用到的工具代码在这里整理下,方便日后查阅。

配置文件路径问题

编译好的二进制文件在执行的之后要读取配置文件,配置文件的位置要定好。

config.yml
我的配置文件和编译后的可执行文件在同级目录下。

config:
  mobileList: 18576780468
  outsideWeb: baidu.com
  msgAPI: http://smsapi.pt.com/relay.php
  nodeList:
    - neo-ingress01.ksru
    - neo-ingress02.ksru
    - neo-master001.ksru
    - neo-master002.ksru

parse_config.go
加载yaml配置文件到结构体中。

package conf

import (
    "errors"
    "gopkg.in/yaml.v2"
    "io/ioutil"
    "os"
    "path"
    "path/filepath"
)

/*
解析配置文件
*/

//存储配置的byte切片
var configFile []byte

//用于加载yaml的结构体(``中的内容为yaml中的key名称)
type Configuration struct {
    Config Config `yaml:"config"`
}

type Config struct {
    NodeList   []string `yaml:"nodeList"`
    OutsideWeb string   `yaml:"outsideWeb"`
    MobileList string   `yaml:"mobileList"`
    MsgAPI     string   `yaml:"msgAPI"`
}

//将配置文件的内容加载到byte切片中
func getConfigFileFromExecutable(fileName string) ([]byte, error) {
    //获取可执行文件的绝对路径
    dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
    if err != nil {
        return nil, errors.New("Can not get executable file path ")
    }
    //读取配置到byte切片
    byteSlice, err := ioutil.ReadFile(path.Join(dir, fileName))
    if err != nil {
        return nil, errors.New("Can not get config file config.yml in directory " + dir)
    }
    return byteSlice, nil
}

//程序加载的时候会自动执行(读取配置文件)
func init() {
    var err error
    configFile, err = getConfigFileFromExecutable("config.yml")
    if err != nil {
        panic(err)
    }
}

//将byte[]切片中的数据加载到结构体中
func GetConfig() (conf *Configuration, err error) {
    err = yaml.Unmarshal(configFile, &conf)
    return conf, err
}

日志

程序中记录日志是非常频繁的行为,不能每个函数都初始化一次日志,我们的日志最好采用单例模式,全局统一(或者根据不用的日志级别,返回不同的单例)
logging.go

  • 所有级别的日志路径为access.log, 且会按照日期切割切割后的格式为access.log.年-月-日, 单例模式
  • 同包下直接使用Log变量就可以,不同包用NewLoggerWithRotate()方法返回Log

logging .go

package logging

import (
    "get_outside/utils/pathutils"
    rotatelogs "github.com/lestrrat-go/file-rotatelogs"
    "github.com/rifflock/lfshook"
    "github.com/sirupsen/logrus"
    "os"
    "path"
    "time"
)

//指针类型
var Log *logrus.Logger

//NewLoggerWithRotate 返回日志对象, 日志路径为access.log, 且会按照日期切割, 单例模式
func NewLoggerWithRotate() (*logrus.Logger, error) {
    if Log != nil {
        return Log, nil
    }

    dir, err := pathutils.ProjectAbsPath()
    if err != nil {
        return nil, err
    }
    logPath := path.Join(dir, "access.log")
    writer, _ := rotatelogs.New(
        logPath+".%Y-%m-%d",
        rotatelogs.WithLinkName(logPath),             // 生成软链,指向最新日志文件
        rotatelogs.WithMaxAge(24*3600*time.Second),   // 文件最大保存时间
        rotatelogs.WithRotationTime(600*time.Second), // 日志切割时间间隔
    )

    levels := logrus.AllLevels
    pathMap := lfshook.WriterMap{}
    for _, level := range levels {
        pathMap[level] = writer
    }

    Log = logrus.New()
    Log.SetOutput(os.Stdout)
    Log.Hooks.Add(lfshook.NewHook(
        pathMap,
        &logrus.JSONFormatter{},
    ))
    return Log, nil
}

ssh连接

有时需要登录到远程主机上去执行命令,首先要获取远程主机的连接。
getssh.go

package sshutils

import (
    "errors"
    "fmt"
    "go_learn/017.utils/logging"
    "golang.org/x/crypto/ssh"
    "io/ioutil"
    "os"
    "path"
    "path/filepath"
    "time"
)

var log, _ = logging.NewLoggerWithRotate()

//GetSSHConnection 获取远程主机的ssh连接, 需要id_rsa私钥文件
func GetSSHConnection(user, host string, port int) (*ssh.Client, error) {
    var (
        addr         string
        clientConfig *ssh.ClientConfig
        client       *ssh.Client
        err          error
    )

    dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
    if err != nil {
        return nil, errors.New("Can not get executable file path ")
    }
    //获取私钥文件
    key, err := ioutil.ReadFile(path.Join(dir, "id_rsa"))
    if err != nil {
        return nil, err
    }
    signer, err := ssh.ParsePrivateKey(key)
    if err != nil {
        return nil, err
    }

    //配置客户端
    clientConfig = &ssh.ClientConfig{
        User: user,
        Auth: []ssh.AuthMethod{
            ssh.PublicKeys(signer),
        },
        Timeout:         5 * time.Second,
        HostKeyCallback: ssh.InsecureIgnoreHostKey(),
    }

    // connet to ssh
    addr = fmt.Sprintf("%s:%d", host, port)

    if client, err = ssh.Dial("tcp", addr, clientConfig); err != nil {
        return nil, err
    }
    log.Infof("获取 " + user + "@" + addr + " ssh连接成功")
    return client, nil
}

调用示例

cmd := "ls /opt"
client, err := sshutils.GetSSHConnection("root", "bigdata-1", 22)
session, err := client.NewSession()
ret, err := session.CombinedOutput(cmd)
client.Close()
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容