[agent-go] [Bastion] - basic accomplished !

This commit is contained in:
zeaslity
2024-04-18 15:20:19 +08:00
parent 8e43f1f90f
commit 314b6054d3
14 changed files with 467 additions and 204 deletions

View File

@@ -8,6 +8,7 @@ import (
"io/ioutil"
"math/rand"
"reflect"
"regexp"
"strings"
"time"
"wdd.io/agent-common/logger"
@@ -233,15 +234,67 @@ func buildOctopusTCPConnect(agentConfig *viper.Viper) *rabbitmq.RabbitTCPConnect
func refreshAgentInfoByStatusInfo(agentInfo *a_status.AgentInfo, agentServerInfo *a_agent.AgentServerInfo) {
// host info
agentServerInfo.Platform = agentInfo.HostInfo.Platform
agentServerInfo.PlatformFamily = agentInfo.HostInfo.PlatformFamily
agentServerInfo.PlatformVersion = agentInfo.HostInfo.PlatformVersion
agentServerInfo.KernelVersion = agentInfo.HostInfo.KernelVersion
agentServerInfo.KernelArch = agentInfo.HostInfo.KernelArch
// network part
refreshAgentNetworkInfo(agentInfo, agentServerInfo)
log.DebugF("[refreshAgentInfoByStatusInfo] - ok !")
}
func refreshAgentNetworkInfo(agentInfo *a_status.AgentInfo, agentServerInfo *a_agent.AgentServerInfo) {
// 测试网卡名称
//testCases := []string{"ens33", "eno1", "enp0s3", "enp1s2", "eth0", "enp2s5", "enx1234567890ab", "ens1234567890ab", "enp1234567890ab", "enp1234567890ab", "enp1", "lo","","docker0", "virbr0", "veth0",}
//for _, tc := range testCases {
// fmt.Printf("Network interface '%s' is %s\n", tc, fmt.Sprintf("%v", isNetworkInterface(tc)))
//}
// inner ip v4 v6
for _, networkInfo := range agentInfo.NetworkInfo {
if isNetworkInterface(networkInfo.Name) {
log.InfoF("refreshAgentNetworkInfo - network interface is %v", networkInfo)
if networkInfo.InternalIPv4 == nil || len(networkInfo.InternalIPv4) == 0 {
continue
}
// 通配到对应的网卡
s := networkInfo.InternalIPv4[0]
if strings.Contains(s, "/") {
s = strings.Split(s, "/")[0]
}
agentServerInfo.ServerIPInV4 = s
if networkInfo.InternalIPv6 == nil || len(networkInfo.InternalIPv6) == 0 {
continue
}
s2 := networkInfo.InternalIPv6[0]
if strings.Contains(s2, "/") {
s2 = strings.Split(s2, "/")[0]
}
agentServerInfo.ServerIPInV6 = s2
if agentServerInfo.ServerIPInV4 != "" {
break
}
}
}
}
// isNetworkInterface 检查网卡名称是否符合给定的模式ens, eno或enp开头或者像enp1s2这样的格式
func isNetworkInterface(networkInterface string) bool {
// 正则表达式匹配 ens 或 eno 开头的字符串
// 或者以 enp 开头后面跟着至少一个数字一个连字符再是一个数字最后可以有一个可选的连字符和数字组合如enp0s3或enp1s2
pattern := `^(ens|eno|eth|enp)[0-9]+$|enp+[0-9]s+[0-9]$`
re := regexp.MustCompile(pattern)
return re.MatchString(networkInterface)
}
// handleInitMsgFromServer 处理从Server接收的 注册信息
func handleInitMsgFromServer(initFromServerMsg *rabbitmq.OctopusMessage, initToServerQueue *rabbitmq.RabbitQueue, agentServerInfo *a_agent.AgentServerInfo) bool {

View File

@@ -51,8 +51,8 @@ func BastionModeInit() {
// Build For Operator
bastionAgentServerInfo := &a_agent.AgentServerInfo{
ServerName: "BastionSingle",
ServerIPPbV4: "127.0.0.1",
ServerIPInV4: "127.0.0.1",
ServerIPPbV4: "",
ServerIPInV4: "",
ServerIPPbV6: "",
ServerIPInV6: "",
Location: "Bastion",
@@ -167,6 +167,12 @@ func buildBastionModeFunction() {
tcc.Insert(InstallDocker)
tcc.Insert(InstallDockerCompose)
tcc.Insert(InstallMinio)
tcc.Insert(InstallDefaultSsh)
tcc.Insert(DisableSwap)
tcc.Insert(DisableSelinux)
tcc.Insert(DisableFirewall)
tcc.Insert(ModifySysConfig)
tcc.Insert(ModifyDockerConfig)
tcc.Insert(InstallHarbor)
tcc.Insert(RemoveDocker)
tcc.Insert(Help)

View File

@@ -0,0 +1,49 @@
hostname: HarborHostName
http:
port: 8033
harbor_admin_password: HarborAdminPas
database:
password: HarborAdminPas
max_idle_conns: 50
max_open_conns: 1000
conn_max_lifetime: 3600
conn_max_idle_time: 3600
data_volume: /var/lib/docker/harbor-data
jobservice:
max_job_workers: 10
job_loggers:
- STD_OUTPUT
- FILE
logger_sweeper_duration: 3
notification:
webhook_job_max_retry: 10
webhook_job_http_client_timeout: 10
log:
level: warning
local:
rotate_count: 50
rotate_size: 200M
location: /var/log/harbor
cache:
enabled: false
expire_hours: 24
_version: 2.9.0
proxy:
http_proxy:
https_proxy:
no_proxy:
components:
- core
- jobservice
- trivy

View File

@@ -0,0 +1,14 @@
package bastion_init
import "fmt"
var BastionFunctionList []string
func PrintBastionHelp() {
fmt.Println()
fmt.Println("Bastion Mode Supported Commands:")
for i, s := range BastionFunctionList {
fmt.Printf("\t%d. %s\n", i+1, s)
}
fmt.Println()
}

View File

@@ -1 +0,0 @@
package bastion_init

View File

@@ -1,91 +0,0 @@
package bastion_init
import "strings"
// 假设我们的预定义字符串列表存储在这个map中键为字符串索引值为字符串本身
var dictionary = map[string]struct{}{
"apple": {},
"apply": {},
"apron": {},
"docker": {},
"docker-compose": {},
"harbor": {},
// ...其他词汇
}
// normalize 将字符串转换为小写并去除特殊符号
func normalize(s string) string {
return strings.ToLower(strings.ReplaceAll(s, "\\W", ""))
}
// findBestMatch 在字典中找到最合适的单词
func findBestMatch(query string) string {
normQuery := normalize(query)
// 将查询字符串排序,以便二分查找
sortedQuery := []rune(normQuery)
var bestMatch string
minDistance := len(dictionary) + 1 // 最初假设没有匹配项
// 遍历字典中的所有单词
for word, _ := range dictionary {
normWord := normalize(word)
distance := levenshteinDistance(sortedQuery, []rune(normWord)) // 计算编辑距离
// 如果当前单词的编辑距离小于等于最佳匹配的距离,并且它是第一个匹配项(或者距离相同但字典序更低)
if distance <= minDistance || (distance == minDistance && strings.ToLower(word) < normQuery) {
minDistance = distance
bestMatch = word
}
}
return bestMatch
}
// levenshteinDistance 计算两个字符串之间的编辑距离(插入、删除或替换一个字符的次数)
func levenshteinDistance(a, b []rune) int {
lenA := len(a)
lenB := len(b)
dist := make([][]int, lenA+1)
for i := range dist {
dist[i] = make([]int, lenB+1)
}
for i := 0; i <= lenA; i++ {
dist[i][0] = i
}
for j := 0; j <= lenB; j++ {
dist[0][j] = j
}
for i := 1; i <= lenA; i++ {
for j := 1; j <= lenB; j++ {
cost := int(a[i-1] - b[j-1])
dist[i][j] = minInt(dist[i-1][j]+1, dist[i][j-1]+1, dist[i-1][j-1]+cost)
}
}
return dist[lenA][lenB]
}
// minInt 找到三个整数中的最小值
func minInt(a, b, c int) int {
if a < b {
if a < c {
return a
}
return c
}
if b < c {
return b
}
return c
}
func main() {
query := "app!"
bestMatch := findBestMatch(query)
println("The best match for", query, "is:", bestMatch)
}

View File

@@ -33,7 +33,10 @@ func (tn *TrieNode) Insert(word string) {
}
func (t *Trie) Insert(word string) {
// insert word into trie
t.root.Insert(word)
// insert to AllFunction List
BastionFunctionList = append(BastionFunctionList, word)
}
func (t *Trie) InsertAll(words []string) {
for _, word := range words {

View File

@@ -2,7 +2,6 @@ package bastion_init
import (
"fmt"
"syscall"
"testing"
)
@@ -22,37 +21,5 @@ func TestNewTrie(t *testing.T) {
}
func TestDp(t *testing.T) {
// 获取netlink接口用于网络控制的内核机制
nl := syscall.NewLk(syscall.AT_FDCWD, "netlink")
if nl == nil {
fmt.Println("Unable to open netlink")
return
}
defer nl.Close()
// 设置对netlink的访问权限
if err := syscall.Setpgid(0, syscall.Getpid()); err != nil {
fmt.Println("Unable to set pgid", err)
return
}
// 设置netlink接口为非阻塞模式
if err := nl.Control(syscall.SET_NONBLOCK, 1); err != nil {
fmt.Println("Unable to set netlink nonblocking", err)
return
}
// 获取IPv4路由转发设置的值
var value syscall.SysctlValInt
if err := syscall.Sysctl(nl, "net/ipv4/ip_forward", &value); err != nil {
fmt.Println("Unable to get ip_forward value:", err)
return
}
// 打印IPv4路由转发的状态
if value == 1 {
fmt.Println("IPv4 routing forwarding is enabled")
} else {
fmt.Println("IPv4 routing forwarding is disabled")
}
}

View File

@@ -1,5 +0,0 @@
package bastion_init
func PrintBastionHelp() {
}