parent
636d5c6046
commit
cc93391796
@ -1,117 +0,0 @@
|
||||
package mageutil
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// StopBinaries iterates over all binary files and terminates their corresponding processes.
|
||||
func StopBinaries() {
|
||||
for binary := range serviceBinaries {
|
||||
fullPath := GetBinFullPath(binary)
|
||||
KillExistBinary(fullPath)
|
||||
}
|
||||
}
|
||||
|
||||
// StartBinaries Start all binary services.
|
||||
func StartBinaries() error {
|
||||
for binary, count := range serviceBinaries {
|
||||
binFullPath := filepath.Join(OpenIMOutputHostBin, binary)
|
||||
for i := 0; i < count; i++ {
|
||||
args := []string{"-i", strconv.Itoa(i), "-c", OpenIMOutputConfig}
|
||||
cmd := exec.Command(binFullPath, args...)
|
||||
fmt.Printf("Starting %s\n", cmd.String())
|
||||
cmd.Dir = OpenIMOutputHostBin
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
if err := cmd.Start(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Failed to start %s with args %v: %v\n", binFullPath, args, err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// StartTools starts all tool binaries.
|
||||
func StartTools() error {
|
||||
for _, tool := range toolBinaries {
|
||||
toolFullPath := GetToolFullPath(tool)
|
||||
cmd := exec.Command(toolFullPath, "-c", OpenIMOutputConfig)
|
||||
fmt.Printf("Starting %s\n", cmd.String())
|
||||
cmd.Dir = OpenIMOutputHostBinTools
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
fmt.Printf("Failed to start %s with error: %v\n", toolFullPath, err)
|
||||
return err
|
||||
}
|
||||
|
||||
if err := cmd.Wait(); err != nil {
|
||||
fmt.Printf("Failed to execute %s with exit code: %v\n", toolFullPath, err)
|
||||
return err
|
||||
}
|
||||
fmt.Printf("Starting %s successfully \n", cmd.String())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// KillExistBinaries iterates over all binary files and kills their corresponding processes.
|
||||
func KillExistBinaries() {
|
||||
for binary := range serviceBinaries {
|
||||
fullPath := GetBinFullPath(binary)
|
||||
KillExistBinary(fullPath)
|
||||
}
|
||||
}
|
||||
|
||||
// CheckBinariesStop checks if all binary files have stopped and returns an error if there are any binaries still running.
|
||||
func CheckBinariesStop() error {
|
||||
var runningBinaries []string
|
||||
|
||||
for binary := range serviceBinaries {
|
||||
fullPath := GetBinFullPath(binary)
|
||||
if CheckProcessNamesExist(fullPath) {
|
||||
runningBinaries = append(runningBinaries, binary)
|
||||
}
|
||||
}
|
||||
|
||||
if len(runningBinaries) > 0 {
|
||||
return fmt.Errorf("the following binaries are still running: %s", strings.Join(runningBinaries, ", "))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CheckBinariesRunning checks if all binary files are running as expected and returns any errors encountered.
|
||||
func CheckBinariesRunning() error {
|
||||
var errorMessages []string
|
||||
|
||||
for binary, expectedCount := range serviceBinaries {
|
||||
fullPath := GetBinFullPath(binary)
|
||||
err := CheckProcessNames(fullPath, expectedCount)
|
||||
if err != nil {
|
||||
errorMessages = append(errorMessages, fmt.Sprintf("binary %s is not running as expected: %v", binary, err))
|
||||
}
|
||||
}
|
||||
|
||||
if len(errorMessages) > 0 {
|
||||
return fmt.Errorf(strings.Join(errorMessages, "\n"))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// PrintListenedPortsByBinaries iterates over all binary files and prints the ports they are listening on.
|
||||
func PrintListenedPortsByBinaries() {
|
||||
for binary, _ := range serviceBinaries {
|
||||
basePath := GetBinFullPath(binary)
|
||||
fullPath := basePath
|
||||
PrintBinaryPorts(fullPath)
|
||||
}
|
||||
}
|
@ -1,235 +0,0 @@
|
||||
package mageutil
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/magefile/mage/sh"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// CheckAndReportBinariesStatus checks the running status of all binary files and reports it.
|
||||
func CheckAndReportBinariesStatus() {
|
||||
InitForSSC()
|
||||
err := CheckBinariesRunning()
|
||||
if err != nil {
|
||||
PrintRed("Some programs are not running properly:")
|
||||
PrintRedNoTimeStamp(err.Error())
|
||||
return
|
||||
}
|
||||
PrintGreen("All services are running normally.")
|
||||
PrintBlue("Display details of the ports listened to by the service:")
|
||||
PrintListenedPortsByBinaries()
|
||||
}
|
||||
|
||||
// StopAndCheckBinaries stops all binary processes and checks if they have all stopped.
|
||||
func StopAndCheckBinaries() {
|
||||
InitForSSC()
|
||||
KillExistBinaries()
|
||||
err := CheckBinariesStop()
|
||||
if err != nil {
|
||||
PrintRed("Some services have not been stopped, details are as follows:" + err.Error())
|
||||
return
|
||||
}
|
||||
PrintGreen("All services have been stopped")
|
||||
}
|
||||
|
||||
// StartToolsAndServices starts the process for tools and services.
|
||||
func StartToolsAndServices() {
|
||||
InitForSSC()
|
||||
PrintBlue("Starting tools primarily involves component verification and other preparatory tasks.")
|
||||
if err := StartTools(); err != nil {
|
||||
PrintRed("Some tools failed to start, details are as follows, abort start")
|
||||
PrintRedNoTimeStamp(err.Error())
|
||||
return
|
||||
}
|
||||
PrintGreen("All tools executed successfully")
|
||||
|
||||
KillExistBinaries()
|
||||
err := CheckBinariesStop()
|
||||
if err != nil {
|
||||
PrintRed("Some services running, details are as follows, abort start " + err.Error())
|
||||
return
|
||||
}
|
||||
PrintBlue("Starting services involves multiple RPCs and APIs and may take some time. Please be patient")
|
||||
err = StartBinaries()
|
||||
if err != nil {
|
||||
PrintRed("Failed to start all binaries")
|
||||
PrintRedNoTimeStamp(err.Error())
|
||||
return
|
||||
}
|
||||
CheckAndReportBinariesStatus()
|
||||
}
|
||||
|
||||
// CompileForPlatform Main compile function
|
||||
func CompileForPlatform(platform string) {
|
||||
|
||||
PrintBlue(fmt.Sprintf("Compiling cmd for %s...", platform))
|
||||
|
||||
cmdCompiledDirs := compileDir(filepath.Join(rootDirPath, "cmd"), platformsOutputBase, platform)
|
||||
|
||||
PrintBlue(fmt.Sprintf("Compiling tools for %s...", platform))
|
||||
toolsCompiledDirs := compileDir(filepath.Join(rootDirPath, "tools"), toolsOutputBase, platform)
|
||||
createStartConfigYML(cmdCompiledDirs, toolsCompiledDirs)
|
||||
|
||||
}
|
||||
|
||||
func createStartConfigYML(cmdDirs, toolsDirs []string) {
|
||||
configPath := filepath.Join(rootDirPath, "start-config.yml")
|
||||
|
||||
if _, err := os.Stat(configPath); !os.IsNotExist(err) {
|
||||
PrintBlue("start-config.yml already exists, skipping creation.")
|
||||
return
|
||||
}
|
||||
|
||||
var content strings.Builder
|
||||
content.WriteString("serviceBinaries:\n")
|
||||
for _, dir := range cmdDirs {
|
||||
content.WriteString(fmt.Sprintf(" %s: 1\n", dir))
|
||||
}
|
||||
content.WriteString("toolBinaries:\n")
|
||||
for _, dir := range toolsDirs {
|
||||
content.WriteString(fmt.Sprintf(" - %s\n", dir))
|
||||
}
|
||||
content.WriteString("maxFileDescriptors: 10000\n")
|
||||
|
||||
err := ioutil.WriteFile(configPath, []byte(content.String()), 0644)
|
||||
if err != nil {
|
||||
PrintRed("Failed to create start-config.yml: " + err.Error())
|
||||
return
|
||||
}
|
||||
PrintGreen("start-config.yml created successfully.")
|
||||
}
|
||||
|
||||
func compileDir(sourceDir, outputBase, platform string) []string {
|
||||
var compiledDirs []string
|
||||
var mu sync.Mutex
|
||||
targetOS, targetArch := strings.Split(platform, "_")[0], strings.Split(platform, "_")[1]
|
||||
outputDir := filepath.Join(outputBase, targetOS, targetArch)
|
||||
|
||||
if err := os.MkdirAll(outputDir, 0755); err != nil {
|
||||
fmt.Printf("Failed to create directory %s: %v\n", outputDir, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
errors := make(chan error, 1)
|
||||
sem := make(chan struct{}, 4)
|
||||
|
||||
err := filepath.Walk(sourceDir, func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if info.IsDir() || filepath.Base(path) != "main.go" {
|
||||
return nil
|
||||
}
|
||||
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
sem <- struct{}{}
|
||||
defer wg.Done()
|
||||
defer func() { <-sem }()
|
||||
|
||||
dir := filepath.Dir(path)
|
||||
dirName := filepath.Base(dir)
|
||||
outputFileName := dirName
|
||||
if targetOS == "windows" {
|
||||
outputFileName += ".exe"
|
||||
}
|
||||
|
||||
PrintBlue(fmt.Sprintf("Compiling dir: %s for platform: %s binary: %s ...", dirName, platform, outputFileName))
|
||||
err := sh.RunWith(map[string]string{"GOOS": targetOS, "GOARCH": targetArch}, "go", "build", "-o", filepath.Join(outputDir, outputFileName), filepath.Join(dir, "main.go"))
|
||||
if err != nil {
|
||||
errors <- fmt.Errorf("failed to compile %s for %s: %v", dirName, platform, err)
|
||||
PrintRed("Compilation aborted. " + fmt.Sprintf("failed to compile %s for %s: %v", dirName, platform, err))
|
||||
os.Exit(1)
|
||||
return
|
||||
}
|
||||
PrintGreen(fmt.Sprintf("Successfully compiled. dir: %s for platform: %s binary: %s", dirName, platform, outputFileName))
|
||||
mu.Lock()
|
||||
compiledDirs = append(compiledDirs, dirName)
|
||||
mu.Unlock()
|
||||
}()
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
fmt.Println("Error walking through directories:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
close(errors)
|
||||
|
||||
// Check for errors
|
||||
if err, ok := <-errors; ok {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return compiledDirs
|
||||
}
|
||||
|
||||
// compileDir compiles Go programs in a specified directory, appending .exe extension for output files on Windows platform
|
||||
//func compileDir(sourceDir, outputBase, platform string) {
|
||||
// targetOS, targetArch := strings.Split(platform, "_")[0], strings.Split(platform, "_")[1]
|
||||
// outputDir := filepath.Join(outputBase, targetOS, targetArch)
|
||||
//
|
||||
// if err := os.MkdirAll(outputDir, 0755); err != nil {
|
||||
// fmt.Printf("Failed to create directory %s: %v\n", outputDir, err)
|
||||
// os.Exit(1)
|
||||
// }
|
||||
//
|
||||
// var wg sync.WaitGroup
|
||||
// errors := make(chan error, 1)
|
||||
//
|
||||
// err := filepath.Walk(sourceDir, func(path string, info os.FileInfo, err error) error {
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// if info.IsDir() || filepath.Base(path) != "main.go" {
|
||||
// return nil
|
||||
// }
|
||||
//
|
||||
// wg.Add(1)
|
||||
// go func() {
|
||||
// defer wg.Done()
|
||||
//
|
||||
// dir := filepath.Dir(path)
|
||||
// dirName := filepath.Base(dir)
|
||||
// outputFileName := dirName
|
||||
// if targetOS == "windows" {
|
||||
// outputFileName += ".exe"
|
||||
// }
|
||||
//
|
||||
// PrintBlue(fmt.Sprintf("Compiling dir: %s for platform: %s binary: %s ...", dirName, platform, outputFileName))
|
||||
// err := sh.RunWith(map[string]string{"GOOS": targetOS, "GOARCH": targetArch}, "go", "build", "-o", filepath.Join(outputDir, outputFileName), filepath.Join(dir, "main.go"))
|
||||
// if err != nil {
|
||||
// errors <- fmt.Errorf("failed to compile %s for %s: %v", dirName, platform, err)
|
||||
// PrintRed("Compilation aborted. " + fmt.Sprintf("failed to compile %s for %s: %v", dirName, platform, err))
|
||||
// os.Exit(1)
|
||||
// return
|
||||
// }
|
||||
// PrintGreen(fmt.Sprintf("Compiling dir: %s for platform: %s binary: %s ...", dirName, platform, outputFileName))
|
||||
// }()
|
||||
//
|
||||
// return nil
|
||||
// })
|
||||
//
|
||||
// if err != nil {
|
||||
// fmt.Println("Error walking through directories:", err)
|
||||
// os.Exit(1)
|
||||
// }
|
||||
//
|
||||
// wg.Wait()
|
||||
// close(errors)
|
||||
//
|
||||
// // Check for errors
|
||||
// if err, ok := <-errors; ok {
|
||||
// fmt.Println(err)
|
||||
// fmt.Println("Compilation aborted.")
|
||||
// os.Exit(1)
|
||||
// }
|
||||
//}
|
@ -1,45 +0,0 @@
|
||||
package mageutil
|
||||
|
||||
import (
|
||||
"gopkg.in/yaml.v3"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
var (
|
||||
serviceBinaries map[string]int
|
||||
toolBinaries []string
|
||||
MaxFileDescriptors int
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
ServiceBinaries map[string]int `yaml:"serviceBinaries"`
|
||||
ToolBinaries []string `yaml:"toolBinaries"`
|
||||
MaxFileDescriptors int `yaml:"maxFileDescriptors"`
|
||||
}
|
||||
|
||||
func InitForSSC() {
|
||||
yamlFile, err := ioutil.ReadFile("start-config.yml")
|
||||
if err != nil {
|
||||
log.Fatalf("error reading YAML file: %v", err)
|
||||
}
|
||||
|
||||
var config Config
|
||||
err = yaml.Unmarshal(yamlFile, &config)
|
||||
if err != nil {
|
||||
log.Fatalf("error unmarshalling YAML: %v", err)
|
||||
}
|
||||
|
||||
adjustedBinaries := make(map[string]int)
|
||||
for binary, count := range config.ServiceBinaries {
|
||||
if runtime.GOOS == "windows" {
|
||||
binary += ".exe"
|
||||
}
|
||||
adjustedBinaries[binary] = count
|
||||
}
|
||||
|
||||
serviceBinaries = adjustedBinaries
|
||||
toolBinaries = config.ToolBinaries
|
||||
MaxFileDescriptors = config.MaxFileDescriptors
|
||||
}
|
@ -1,56 +0,0 @@
|
||||
package mageutil
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
ColorBlue = "\033[0;34m"
|
||||
ColorGreen = "\033[0;32m"
|
||||
ColorRed = "\033[0;31m"
|
||||
ColorReset = "\033[0m"
|
||||
)
|
||||
|
||||
func PrintBlueTwoLine(message string) {
|
||||
currentTime := time.Now().Format("[2006-01-02 15:04:05 MST]")
|
||||
fmt.Println(currentTime)
|
||||
fmt.Printf("%s%s%s\n", ColorBlue, message, ColorReset)
|
||||
}
|
||||
|
||||
func PrintBlue(message string) {
|
||||
currentTime := time.Now().Format("[2006-01-02 15:04:05 MST]")
|
||||
fmt.Printf("%s %s%s%s\n", currentTime, ColorBlue, message, ColorReset)
|
||||
}
|
||||
|
||||
func PrintGreenTwoLine(message string) {
|
||||
currentTime := time.Now().Format("[2006-01-02 15:04:05 MST]")
|
||||
fmt.Println(currentTime)
|
||||
fmt.Printf("%s%s%s\n", ColorGreen, message, ColorReset)
|
||||
}
|
||||
|
||||
func PrintGreen(message string) {
|
||||
currentTime := time.Now().Format("[2006-01-02 15:04:05 MST]")
|
||||
fmt.Printf("%s %s%s%s\n", currentTime, ColorGreen, message, ColorReset)
|
||||
}
|
||||
|
||||
func PrintRed(message string) {
|
||||
currentTime := time.Now().Format("[2006-01-02 15:04:05 MST]")
|
||||
fmt.Printf("%s %s%s%s\n", currentTime, ColorRed, message, ColorReset)
|
||||
}
|
||||
|
||||
func PrintRedNoTimeStamp(message string) {
|
||||
fmt.Printf("%s%s%s\n", ColorRed, message, ColorReset)
|
||||
}
|
||||
|
||||
func PrintGreenNoTimeStamp(message string) {
|
||||
fmt.Printf("%s%s%s\n", ColorGreen, message, ColorReset)
|
||||
}
|
||||
|
||||
func PrintRedToStdErr(a ...interface{}) (n int, err error) {
|
||||
return fmt.Fprint(os.Stderr, "\033[31m", fmt.Sprint(a...), "\033[0m")
|
||||
}
|
||||
func PrintGreenToStdOut(a ...interface{}) (n int, err error) {
|
||||
return fmt.Fprint(os.Stdout, "\033[32m", fmt.Sprint(a...), "\033[0m")
|
||||
}
|
@ -1,85 +0,0 @@
|
||||
package mageutil
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
var (
|
||||
OpenIMRoot string
|
||||
OpenIMOutputConfig string
|
||||
OpenIMOutput string
|
||||
OpenIMOutputTools string
|
||||
OpenIMOutputTmp string
|
||||
OpenIMOutputLogs string
|
||||
OpenIMOutputBin string
|
||||
OpenIMOutputBinPath string
|
||||
OpenIMOutputBinToolPath string
|
||||
OpenIMInitErrLogFile string
|
||||
OpenIMInitLogFile string
|
||||
OpenIMOutputHostBin string
|
||||
OpenIMOutputHostBinTools string
|
||||
)
|
||||
|
||||
func init() {
|
||||
currentDir, err := os.Getwd()
|
||||
if err != nil {
|
||||
panic("Error getting current directory: " + err.Error())
|
||||
}
|
||||
|
||||
OpenIMRoot = currentDir
|
||||
|
||||
OpenIMOutputConfig = filepath.Join(OpenIMRoot, "config") + string(filepath.Separator)
|
||||
OpenIMOutput = filepath.Join(OpenIMRoot, "_output") + string(filepath.Separator)
|
||||
|
||||
OpenIMOutputTools = filepath.Join(OpenIMOutput, "tools") + string(filepath.Separator)
|
||||
OpenIMOutputTmp = filepath.Join(OpenIMOutput, "tmp") + string(filepath.Separator)
|
||||
OpenIMOutputLogs = filepath.Join(OpenIMOutput, "logs") + string(filepath.Separator)
|
||||
OpenIMOutputBin = filepath.Join(OpenIMOutput, "bin") + string(filepath.Separator)
|
||||
|
||||
OpenIMOutputBinPath = filepath.Join(OpenIMOutputBin, "platforms") + string(filepath.Separator)
|
||||
OpenIMOutputBinToolPath = filepath.Join(OpenIMOutputBin, "tools") + string(filepath.Separator)
|
||||
|
||||
OpenIMInitErrLogFile = filepath.Join(OpenIMOutputLogs, "openim-init-err.log")
|
||||
OpenIMInitLogFile = filepath.Join(OpenIMOutputLogs, "openim-init.log")
|
||||
|
||||
OpenIMOutputHostBin = filepath.Join(OpenIMOutputBinPath, OsArch()) + string(filepath.Separator)
|
||||
OpenIMOutputHostBinTools = filepath.Join(OpenIMOutputBinToolPath, OsArch()) + string(filepath.Separator)
|
||||
|
||||
dirs := []string{
|
||||
OpenIMOutputConfig,
|
||||
OpenIMOutput,
|
||||
OpenIMOutputTools,
|
||||
OpenIMOutputTmp,
|
||||
OpenIMOutputLogs,
|
||||
OpenIMOutputBin,
|
||||
OpenIMOutputBinPath,
|
||||
OpenIMOutputBinToolPath,
|
||||
OpenIMOutputHostBin,
|
||||
OpenIMOutputHostBinTools,
|
||||
}
|
||||
|
||||
for _, dir := range dirs {
|
||||
createDirIfNotExist(dir)
|
||||
}
|
||||
}
|
||||
|
||||
func createDirIfNotExist(dir string) {
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
fmt.Printf("Failed to create directory %s: %v\n", dir, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// GetBinFullPath constructs and returns the full path for the given binary name.
|
||||
func GetBinFullPath(binName string) string {
|
||||
binFullPath := filepath.Join(OpenIMOutputHostBin, binName)
|
||||
return binFullPath
|
||||
}
|
||||
|
||||
// GetToolFullPath constructs and returns the full path for the given tool name.
|
||||
func GetToolFullPath(toolName string) string {
|
||||
toolFullPath := filepath.Join(OpenIMOutputHostBinTools, toolName)
|
||||
return toolFullPath
|
||||
}
|
@ -1,208 +0,0 @@
|
||||
package mageutil
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/shirou/gopsutil/net"
|
||||
"github.com/shirou/gopsutil/process"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func OsArch() string {
|
||||
os := runtime.GOOS
|
||||
arch := runtime.GOARCH
|
||||
if os == "windows" {
|
||||
return fmt.Sprintf("%s\\%s", os, arch)
|
||||
}
|
||||
return fmt.Sprintf("%s/%s", os, arch)
|
||||
}
|
||||
|
||||
func CheckProcessNames(processPath string, expectedCount int) error {
|
||||
processes, err := process.Processes()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get processes: %v", err)
|
||||
}
|
||||
|
||||
runningCount := 0
|
||||
for _, p := range processes {
|
||||
exePath, err := p.Exe()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if strings.EqualFold(exePath, processPath) {
|
||||
runningCount++
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
if runningCount == expectedCount {
|
||||
return nil
|
||||
} else {
|
||||
return fmt.Errorf("%s Expected %d processes, but %d running", processPath, expectedCount, runningCount)
|
||||
}
|
||||
}
|
||||
|
||||
// CheckProcessNamesExist checks if there are any processes running that match the specified path.
|
||||
func CheckProcessNamesExist(processPath string) bool {
|
||||
processes, err := process.Processes()
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to get processes: %v\n", err)
|
||||
return false
|
||||
}
|
||||
|
||||
for _, p := range processes {
|
||||
exePath, err := p.Exe()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if exePath == processPath {
|
||||
return true // 找到至少一个匹配的进程
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// PrintBinaryPorts prints the ports listened by the process of a specified binary file along with its command line arguments.
|
||||
func PrintBinaryPorts(binaryPath string) {
|
||||
pids, err := FindPIDsByBinaryPath(binaryPath)
|
||||
if err != nil {
|
||||
fmt.Println("Error finding PIDs:", err)
|
||||
return
|
||||
}
|
||||
|
||||
if len(pids) == 0 {
|
||||
fmt.Printf("No running processes found for binary: %s\n", binaryPath)
|
||||
return
|
||||
}
|
||||
|
||||
for _, pid := range pids {
|
||||
|
||||
proc, err := process.NewProcess(int32(pid))
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to create process object for PID %d: %v\n", pid, err)
|
||||
continue
|
||||
}
|
||||
|
||||
cmdline, err := proc.Cmdline()
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to get command line for PID %d: %v\n", pid, err)
|
||||
continue
|
||||
}
|
||||
|
||||
connections, err := net.ConnectionsPid("all", int32(pid))
|
||||
if err != nil {
|
||||
fmt.Printf("Error getting connections for PID %d: %v\n", pid, err)
|
||||
continue
|
||||
}
|
||||
|
||||
portsMap := make(map[string]struct{})
|
||||
for _, conn := range connections {
|
||||
if conn.Status == "LISTEN" {
|
||||
port := fmt.Sprintf("%d", conn.Laddr.Port)
|
||||
portsMap[port] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
if len(portsMap) == 0 {
|
||||
PrintGreen(fmt.Sprintf("Cmdline: %s, PID: %d is not listening on any ports.", cmdline, pid))
|
||||
} else {
|
||||
ports := make([]string, 0, len(portsMap))
|
||||
for port := range portsMap {
|
||||
ports = append(ports, port)
|
||||
}
|
||||
PrintGreen(fmt.Sprintf("Cmdline: %s, PID: %d is listening on ports: %s", cmdline, pid, strings.Join(ports, ", ")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// FindPIDsByBinaryPath finds all matching process PIDs by binary path.
|
||||
func FindPIDsByBinaryPath(binaryPath string) ([]int, error) {
|
||||
var pids []int
|
||||
processes, err := process.Processes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, proc := range processes {
|
||||
exePath, err := proc.Exe()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if strings.EqualFold(exePath, binaryPath) {
|
||||
pids = append(pids, int(proc.Pid))
|
||||
}
|
||||
}
|
||||
|
||||
return pids, nil
|
||||
}
|
||||
|
||||
// KillExistBinary kills all processes matching the given binary file path.
|
||||
func KillExistBinary(binaryPath string) {
|
||||
processes, err := process.Processes()
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to get processes: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
for _, p := range processes {
|
||||
exePath, err := p.Exe()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if strings.Contains(strings.ToLower(exePath), strings.ToLower(binaryPath)) {
|
||||
|
||||
//if strings.EqualFold(exePath, binaryPath) {
|
||||
cmdline, err := p.Cmdline()
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to get command line for process %d: %v\n", p.Pid, err)
|
||||
continue
|
||||
}
|
||||
|
||||
err = p.Terminate()
|
||||
if err != nil {
|
||||
|
||||
err = p.Kill()
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to kill process cmdline: %s, pid: %d, err: %v\n", cmdline, p.Pid, err)
|
||||
} else {
|
||||
fmt.Printf("Killed process cmdline: %s, pid: %d\n", cmdline, p.Pid)
|
||||
}
|
||||
} else {
|
||||
fmt.Printf("Terminated process cmdline: %s, pid: %d\n", cmdline, p.Pid)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// DetectPlatform detects the operating system and architecture.
|
||||
func DetectPlatform() string {
|
||||
targetOS, targetArch := runtime.GOOS, runtime.GOARCH
|
||||
switch targetArch {
|
||||
case "amd64", "arm64":
|
||||
default:
|
||||
fmt.Printf("Unsupported architecture: %s\n", targetArch)
|
||||
os.Exit(1)
|
||||
}
|
||||
return fmt.Sprintf("%s_%s", targetOS, targetArch)
|
||||
}
|
||||
|
||||
// rootDir gets the absolute path of the current directory.
|
||||
func rootDir() string {
|
||||
dir, err := os.Getwd()
|
||||
if err != nil {
|
||||
fmt.Println("Failed to get current directory:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
var rootDirPath = rootDir()
|
||||
var platformsOutputBase = filepath.Join(rootDirPath, "_output/bin/platforms")
|
||||
var toolsOutputBase = filepath.Join(rootDirPath, "_output/bin/tools")
|
@ -1,72 +0,0 @@
|
||||
package memAsyncQueue
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// AsyncQueue is the interface responsible for asynchronous processing of functions.
|
||||
type AsyncQueue interface {
|
||||
Initialize(processFunc func(), workerCount int, bufferSize int)
|
||||
Push(task func()) error
|
||||
}
|
||||
|
||||
// MemoryQueue is an implementation of the AsyncQueue interface using a channel to process functions.
|
||||
type MemoryQueue struct {
|
||||
taskChan chan func()
|
||||
wg sync.WaitGroup
|
||||
isStopped bool
|
||||
stopMutex sync.Mutex // Mutex to protect access to isStopped
|
||||
}
|
||||
|
||||
func NewMemoryQueue(workerCount int, bufferSize int) *MemoryQueue {
|
||||
mq := &MemoryQueue{} // Create a new instance of MemoryQueue
|
||||
mq.Initialize(workerCount, bufferSize) // Initialize it with specified parameters
|
||||
return mq
|
||||
}
|
||||
|
||||
// Initialize sets up the worker nodes and the buffer size of the channel,
|
||||
// starting internal goroutines to handle tasks from the channel.
|
||||
func (mq *MemoryQueue) Initialize(workerCount int, bufferSize int) {
|
||||
mq.taskChan = make(chan func(), bufferSize) // Initialize the channel with the provided buffer size.
|
||||
mq.isStopped = false
|
||||
|
||||
// Start multiple goroutines based on the specified workerCount.
|
||||
for i := 0; i < workerCount; i++ {
|
||||
mq.wg.Add(1)
|
||||
go func(workerID int) {
|
||||
defer mq.wg.Done()
|
||||
for task := range mq.taskChan {
|
||||
task() // Execute the function
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
}
|
||||
|
||||
// Push submits a function to the queue.
|
||||
// Returns an error if the queue is stopped or if the queue is full.
|
||||
func (mq *MemoryQueue) Push(task func()) error {
|
||||
mq.stopMutex.Lock()
|
||||
if mq.isStopped {
|
||||
mq.stopMutex.Unlock()
|
||||
return errors.New("push failed: queue is stopped")
|
||||
}
|
||||
mq.stopMutex.Unlock()
|
||||
|
||||
select {
|
||||
case mq.taskChan <- task:
|
||||
return nil
|
||||
case <-time.After(time.Millisecond * 100): // Timeout to prevent deadlock/blocking
|
||||
return errors.New("push failed: queue is full")
|
||||
}
|
||||
}
|
||||
|
||||
// Stop is used to terminate the internal goroutines and close the channel.
|
||||
func (mq *MemoryQueue) Stop() {
|
||||
mq.stopMutex.Lock()
|
||||
mq.isStopped = true
|
||||
close(mq.taskChan)
|
||||
mq.stopMutex.Unlock()
|
||||
mq.wg.Wait()
|
||||
}
|
@ -1,61 +0,0 @@
|
||||
package memAsyncQueue
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNewMemoryQueue(t *testing.T) {
|
||||
workerCount := 3
|
||||
bufferSize := 10
|
||||
queue := NewMemoryQueue(workerCount, bufferSize)
|
||||
|
||||
if cap(queue.taskChan) != bufferSize {
|
||||
t.Errorf("Expected buffer size %d, got %d", bufferSize, cap(queue.taskChan))
|
||||
}
|
||||
|
||||
if queue.isStopped {
|
||||
t.Errorf("New queue is prematurely stopped")
|
||||
}
|
||||
|
||||
if len(queue.taskChan) != 0 {
|
||||
t.Errorf("New queue should be empty, found %d items", len(queue.taskChan))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPushAndStop(t *testing.T) {
|
||||
queue := NewMemoryQueue(1, 5)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
queue.Push(func() {
|
||||
time.Sleep(50 * time.Millisecond) // Simulate task delay
|
||||
wg.Done()
|
||||
})
|
||||
|
||||
queue.Stop()
|
||||
wg.Wait()
|
||||
|
||||
if err := queue.Push(func() {}); err == nil {
|
||||
t.Error("Expected error when pushing to stopped queue, got none")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPushTimeout(t *testing.T) {
|
||||
queue := NewMemoryQueue(1, 1) // Small buffer and worker to force full queue
|
||||
|
||||
done := make(chan bool)
|
||||
go func() {
|
||||
queue.Push(func() {
|
||||
time.Sleep(200 * time.Millisecond) // Long enough to cause the second push to timeout
|
||||
})
|
||||
done <- true
|
||||
}()
|
||||
|
||||
<-done // Ensure first task is pushed
|
||||
|
||||
if err := queue.Push(func() {}); err != nil {
|
||||
t.Error("Expected timeout error, got nil")
|
||||
}
|
||||
}
|
Loading…
Reference in new issue