feat: 新增工具模块 iperf

This commit is contained in:
TsMask
2024-10-09 17:38:32 +08:00
parent 7aae060f2e
commit e3b55c38e5
10 changed files with 221 additions and 0 deletions

View File

@@ -0,0 +1,110 @@
package service
import (
"fmt"
"io"
"strings"
"be.ems/src/framework/config"
neService "be.ems/src/modules/network_element/service"
)
// 实例化服务层 IPerf 结构体
var NewIPerf = &IPerf{
neInfoService: neService.NewNeInfoImpl,
}
// IPerf 网络性能测试工具 服务层处理
type IPerf struct {
// 网元信息服务
neInfoService neService.INeInfo
}
// Version 查询版本信息
func (s *IPerf) Version(meType, neId string) (string, error) {
// 网元主机的SSH客户端
sshClient, err := s.neInfoService.NeRunSSHClient(meType, neId)
if err != nil {
return "", err
}
defer sshClient.Close()
// 检查是否安装iperf3
output, err := sshClient.RunCMD("iperf3 --version")
if err != nil {
return "", fmt.Errorf("iperf3 not installed")
}
return strings.TrimSpace(output), err
}
// Install 安装iperf3
func (s *IPerf) Install(meType, neId string) error {
// 网元主机的SSH客户端
sshClient, err := s.neInfoService.NeRunSSHClient(meType, neId)
if err != nil {
return err
}
defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP()
if err != nil {
return err
}
defer sftpClient.Close()
nePath := "/tmp"
depPkg := "sudo dpkg -i"
depDir := "assets/dependency/iperf3/deb"
// 检查平台类型
if _, err := sshClient.RunCMD("sudo dpkg --version"); err == nil {
depPkg = "sudo dpkg -i"
depDir = "assets/dependency/iperf3/deb"
// sudo apt remove iperf3 libiperf0 libsctp1 libsctp-dev lksctp-tools
} else if _, err := sshClient.RunCMD("sudo yum --version"); err == nil {
depPkg = "sudo rpm -Uvh --force"
depDir = "assets/dependency/iperf3/rpm"
// yum remove iperf3 iperf3-help.noarch
}
// 从 embed.FS 中读取默认配置文件内容
assetsDir := config.GetAssetsDirFS()
fsDirEntrys, err := assetsDir.ReadDir(depDir)
if err != nil {
return err
}
neFilePaths := []string{}
for _, d := range fsDirEntrys {
// 打开本地文件
localFile, err := assetsDir.Open(fmt.Sprintf("%s/%s", depDir, d.Name()))
if err != nil {
return fmt.Errorf("iperf3 file local error")
}
defer localFile.Close()
// 创建远程文件
remotePath := fmt.Sprintf("%s/%s", nePath, d.Name())
remoteFile, err := sftpClient.Client.Create(remotePath)
if err != nil {
return fmt.Errorf("iperf3 file remote error")
}
defer remoteFile.Close()
// 使用 io.Copy 将嵌入的文件内容复制到目标文件
if _, err := io.Copy(remoteFile, localFile); err != nil {
return fmt.Errorf("iperf3 file copy error")
}
neFilePaths = append(neFilePaths, remotePath)
}
// 删除软件包
defer func() {
pkgRemove := fmt.Sprintf("sudo rm %s", strings.Join(neFilePaths, " "))
sshClient.RunCMD(pkgRemove)
}()
// 安装软件包
pkgInstall := fmt.Sprintf("%s %s", depPkg, strings.Join(neFilePaths, " "))
if _, err := sshClient.RunCMD(pkgInstall); err != nil {
return fmt.Errorf("iperf3 install error")
}
return err
}