Skip to content

Commit 5539314

Browse files
authored
Merge pull request kosmos-io#771 from gao12312/Heartbeat
update node-agent Heartbeat
2 parents c87aed4 + fa4f60a commit 5539314

File tree

5 files changed

+92
-7
lines changed

5 files changed

+92
-7
lines changed

cmd/kubenest/node-agent/app/root.go

+6-6
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package app
22

33
import (
4-
"os"
54
"strings"
65

76
"github.com/spf13/cobra"
@@ -30,11 +29,12 @@ var RootCmd = &cobra.Command{
3029

3130
func initConfig() {
3231
// Tell Viper to automatically look for a .env file
33-
viper.SetConfigFile("agent.env")
34-
currentDir, _ := os.Getwd()
35-
viper.AddConfigPath(currentDir)
36-
viper.AddConfigPath("/srv/node-agent/agent.env")
37-
viper.SetConfigType("toml")
32+
//viper.SetConfigFile("agent.env")
33+
viper.SetConfigFile("/srv/node-agent/agent.env")
34+
//currentDir, _ := os.Getwd()
35+
//viper.AddConfigPath(currentDir)
36+
//viper.AddConfigPath("/srv/node-agent/agent.env")
37+
//viper.SetConfigType("toml")
3838
// If a agent.env file is found, read it in.
3939
if err := viper.ReadInConfig(); err != nil {
4040
log.Warnf("Load config file error, %s", err)

cmd/kubenest/node-agent/app/serve/serve.go

+69
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package serve
22

33
import (
44
"bufio"
5+
"context"
56
"crypto/sha256"
67
"crypto/tls"
78
"encoding/base64"
@@ -22,8 +23,12 @@ import (
2223
"github.com/gorilla/websocket"
2324
"github.com/spf13/cobra"
2425
"github.com/spf13/viper"
26+
corev1 "k8s.io/api/core/v1"
27+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
28+
"k8s.io/client-go/tools/clientcmd"
2529

2630
"github.com/kosmos.io/kosmos/cmd/kubenest/node-agent/app/logger"
31+
"github.com/kosmos.io/kosmos/pkg/generated/clientset/versioned"
2732
)
2833

2934
var (
@@ -36,6 +41,7 @@ var (
3641
certFile string // SSL certificate file
3742
keyFile string // SSL key file
3843
addr string // server listen address
44+
nodeName string // server nodename
3945
log = logger.GetLogger()
4046
)
4147

@@ -47,14 +53,28 @@ var upgrader = websocket.Upgrader{
4753
},
4854
} // use default options
4955

56+
const (
57+
defaultKubeconfig = "/srv/node-agent/kubeconfigpath"
58+
) // kubeconfig for heartbeatCheck
59+
5060
func init() {
5161
// setup flags
5262
ServeCmd.PersistentFlags().StringVarP(&addr, "addr", "a", ":5678", "websocket service address")
5363
ServeCmd.PersistentFlags().StringVarP(&certFile, "cert", "c", "cert.pem", "SSL certificate file")
5464
ServeCmd.PersistentFlags().StringVarP(&keyFile, "key", "k", "key.pem", "SSL key file")
65+
ServeCmd.PersistentFlags().StringVarP(&nodeName, "nodename", "n", "", "set nodename")
5566
}
5667

5768
func serveCmdRun(_ *cobra.Command, _ []string) error {
69+
//start heartbeatCheck Goroutine
70+
ctx, cancel := context.WithCancel(context.Background())
71+
defer cancel()
72+
73+
if len(nodeName) == 0 {
74+
nodeName = viper.GetString("NODE_NAME")
75+
}
76+
go heartbeatCheck(ctx, nodeName)
77+
5878
user := viper.GetString("WEB_USER")
5979
password := viper.GetString("WEB_PASS")
6080
port := viper.GetString("WEB_PORT")
@@ -65,9 +85,57 @@ func serveCmdRun(_ *cobra.Command, _ []string) error {
6585
if port != "" {
6686
addr = ":" + port
6787
}
88+
6889
return Start(addr, certFile, keyFile, user, password)
6990
}
7091

92+
func heartbeatCheck(ctx context.Context, nodeName string) {
93+
kubeconfigPath := defaultKubeconfig
94+
config, err := clientcmd.BuildConfigFromFlags("", kubeconfigPath)
95+
if err != nil {
96+
log.Errorf("Failed to load kubeconfig from path %s:%v", kubeconfigPath, err)
97+
return
98+
}
99+
kosmosClient, err := versioned.NewForConfig(config)
100+
if err != nil {
101+
log.Errorf("Failed to get config: %v", err)
102+
return
103+
}
104+
105+
ticker := time.NewTicker(10 * time.Second)
106+
defer ticker.Stop()
107+
108+
for {
109+
select {
110+
case <-ctx.Done():
111+
log.Infof("Heartbeat for node %s stopped", nodeName)
112+
return
113+
case <-ticker.C:
114+
node, err := kosmosClient.KosmosV1alpha1().GlobalNodes().Get(ctx, nodeName, metav1.GetOptions{})
115+
if err != nil {
116+
log.Errorf("Failed to get node: %v", err)
117+
}
118+
heartbeatTime := metav1.Now()
119+
120+
if len(node.Status.Conditions) == 0 {
121+
log.Infof("GlobalNode %s has no conditions, initializing default condition", node.Name)
122+
node.Status.Conditions = []corev1.NodeCondition{
123+
{
124+
LastHeartbeatTime: heartbeatTime,
125+
},
126+
}
127+
} else {
128+
node.Status.Conditions[0].LastHeartbeatTime = heartbeatTime
129+
}
130+
if _, err := kosmosClient.KosmosV1alpha1().GlobalNodes().UpdateStatus(ctx, node, metav1.UpdateOptions{}); err != nil {
131+
log.Errorf("update node %s status for globalnode failed, %v", node.Name, err)
132+
} else {
133+
log.Infof("GlobalnodeHeartbeat: successfully updated global node %s, Status.Conditions: %+v", node.Name, node.Status.Conditions)
134+
}
135+
}
136+
}
137+
}
138+
71139
// start server
72140
func Start(addr, certFile, keyFile, user, password string) error {
73141
passwordHash := sha256.Sum256([]byte(password))
@@ -146,6 +214,7 @@ func Start(addr, certFile, keyFile, user, password string) error {
146214
TLSConfig: tlsConfig,
147215
ReadHeaderTimeout: 10 * time.Second,
148216
}
217+
149218
err := server.ListenAndServeTLS("", "")
150219
if err != nil {
151220
log.Errorf("failed to start server %v", err)

deploy/virtual-cluster-operator.yml

+13
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,11 @@ spec:
230230
secretKeyRef:
231231
name: node-agent-secret
232232
key: password
233+
- name: NODE_NAME
234+
valueFrom:
235+
fieldRef:
236+
apiVersion: v1
237+
fieldPath: spec.nodeName
233238
command: ["/bin/bash"]
234239
args:
235240
- "/app/init.sh"
@@ -240,6 +245,10 @@ spec:
240245
- mountPath: /host-systemd
241246
name: systemd-path
242247
readOnly: false
248+
- mountPath: /app/kubeconfigpath
249+
name: kubeconfig
250+
subPath: kubeconfig
251+
readOnly: false
243252
containers:
244253
- name: install-agent
245254
image: cis-hub-huabei-3.cmecloud.cn/node-agent/node-agent:latest
@@ -282,6 +291,10 @@ spec:
282291
hostPath:
283292
path: /etc/systemd/system
284293
type: DirectoryOrCreate
294+
- name: kubeconfig
295+
secret:
296+
secretName: virtual-cluster-operator
297+
285298
---
286299
apiVersion: v1
287300
kind: Secret

hack/node-agent/agent.env

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
WEB_USER={{WEB_USER}}
22
WEB_PASS={{WEB_PASS}}
33
WEB_PORT={{WEB_PORT}}
4+
NODE_NAME={{NODE_NAME}}

hack/node-agent/init.sh

+3-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
WEB_USER="$WEB_USER" sed -i 's/^WEB_USER=.*/WEB_USER="'"$WEB_USER"'"/' /app/agent.env
44
WEB_PASS="$WEB_PASS" sed -i 's/^WEB_PASS=.*/WEB_PASS="'"$WEB_PASS"'"/' /app/agent.env
55
WEB_PORT="$WEB_PORT" sed -i 's/^WEB_PORT=.*/WEB_PORT="'"$WEB_PORT"'"/' /app/agent.env
6+
NODE_NAME="$NODE_NAME" sed -i 's/^NODE_NAME=.*/NODE_NAME="'"$NODE_NAME"'"/' /app/agent.env
7+
68
sha256sum /app/node-agent > /app/node-agent.sum
79
sha256sum /host-path/node-agent >> /app/node-agent.sum
810
rsync -avz /app/ /host-path/
9-
cp /app/node-agent.service /host-systemd/node-agent.service
11+
cp /app/node-agent.service /host-systemd/node-agent.service

0 commit comments

Comments
 (0)