Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions ctl/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"github.com/spf13/cobra"

"kmesh.net/kmesh/ctl/authz"
"kmesh.net/kmesh/ctl/dnsproxy"
"kmesh.net/kmesh/ctl/dump"
logcmd "kmesh.net/kmesh/ctl/log"
"kmesh.net/kmesh/ctl/monitoring"
Expand All @@ -43,6 +44,7 @@ func GetRootCommand() *cobra.Command {
rootCmd.AddCommand(waypoint.NewCmd())
rootCmd.AddCommand(version.NewCmd())
rootCmd.AddCommand(monitoring.NewCmd())
rootCmd.AddCommand(dnsproxy.NewCmd())
rootCmd.AddCommand(authz.NewCmd())
rootCmd.AddCommand(secret.NewCmd())

Expand Down
147 changes: 147 additions & 0 deletions ctl/dnsproxy/dnsproxy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
/*
* Copyright The Kmesh Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package dnsproxy

import (
"context"
"fmt"
"io"
"net/http"
"os"
"strings"

"github.com/spf13/cobra"

"kmesh.net/kmesh/ctl/utils"
"kmesh.net/kmesh/pkg/kube"
"kmesh.net/kmesh/pkg/logger"
)

const patternDnsproxy = "/dnsproxy"

var log = logger.NewLoggerScope("kmeshctl/dnsproxy")

func NewCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "dnsproxy [pod] enable|disable",
Short: "Enable or disable Kmesh's DNS proxy",
Example: `# Enable Kmesh's DNS proxy:
kmeshctl dnsproxy <kmesh-daemon-pod> enable

# Disable Kmesh's DNS proxy:
kmeshctl dnsproxy <kmesh-daemon-pod> disable

# Enable/Disable DNS proxy on all kmesh daemons in the cluster:
kmeshctl dnsproxy enable
kmeshctl dnsproxy disable`,
Args: cobra.RangeArgs(1, 2),
Run: func(cmd *cobra.Command, args []string) {
ControlDnsproxy(cmd, args)
},
}
return cmd
}

func ControlDnsproxy(cmd *cobra.Command, args []string) {
client, err := utils.CreateKubeClient()
if err != nil {
log.Errorf("failed to create cli client: %v", err)
os.Exit(1)
}

var podName string
var enableStr string
if len(args) == 1 {
enableStr = args[0]
podName = ""
} else {
podName = args[0]
enableStr = args[1]
}

if enableStr != "enable" && enableStr != "disable" {
log.Errorf("Error: Argument must be 'enable' or 'disable'")
os.Exit(1)
}

if podName != "" && strings.Contains(podName, "--") {
log.Errorf("Error: Invalid pod name")
os.Exit(1)
}

if podName != "" {
SetDnsproxyPerKmeshDaemon(client, podName, enableStr)
return
}

// Apply to all kmesh daemons
podList, err := client.PodsForSelector(context.TODO(), utils.KmeshNamespace, utils.KmeshLabel)
if err != nil {
log.Errorf("failed to get kmesh podList: %v", err)
os.Exit(1)
}
for _, pod := range podList.Items {
SetDnsproxyPerKmeshDaemon(client, pod.GetName(), enableStr)
}
Comment on lines +86 to +99

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

After modifying SetDnsproxyPerKmeshDaemon to return an error, ControlDnsproxy should be updated to handle these errors. When a single pod is targeted, an error should cause the command to exit with a non-zero status. When all pods are targeted, an error for one pod should be logged, but the command should continue to process the remaining pods.

	if podName != "" {
		if err := SetDnsproxyPerKmeshDaemon(client, podName, enableStr); err != nil {
			log.Errorf("failed to set dnsproxy for pod %s: %v", podName, err)
			os.Exit(1)
		}
		return
	}

	// Apply to all kmesh daemons
	podList, err := client.PodsForSelector(context.TODO(), utils.KmeshNamespace, utils.KmeshLabel)
	if err != nil {
		log.Errorf("failed to get kmesh podList: %v", err)
		os.Exit(1)
	}
	for _, pod := range podList.Items {
		if err := SetDnsproxyPerKmeshDaemon(client, pod.GetName(), enableStr); err != nil {
			log.Errorf("failed to set dnsproxy for pod %s: %v", pod.GetName(), err)
		}
	}

}

func SetDnsproxyPerKmeshDaemon(cli kube.CLIClient, podName, info string) {
var status string
if info == "enable" {
status = "true"
} else {
status = "false"
}

fw, err := utils.CreateKmeshPortForwarder(cli, podName)
if err != nil {
log.Errorf("failed to create port forwarder for Kmesh daemon pod %s: %v", podName, err)
os.Exit(1)
}
if err := fw.Start(); err != nil {
log.Errorf("failed to start port forwarder for Kmesh daemon pod %s: %v", podName, err)
os.Exit(1)
}
defer fw.Close()

url := fmt.Sprintf("http://%s%s?enable=%s", fw.Address(), patternDnsproxy, status)

req, err := http.NewRequest(http.MethodPost, url, nil)
if err != nil {
log.Errorf("Error creating request: %v", err)
return
}

req.Header.Set("Content-Type", "application/json")
httpClient := &http.Client{}
resp, err := httpClient.Do(req)
if err != nil {
log.Errorf("failed to make HTTP request: %v", err)
return
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
log.Errorf("Error: received status code %d", resp.StatusCode)
bodyBytes, readErr := io.ReadAll(resp.Body)
if readErr != nil {
log.Errorf("Error reading response body: %v", readErr)
return
}
log.Errorf("response: %s", string(bodyBytes))
}
}
Comment on lines +102 to +147

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The function SetDnsproxyPerKmeshDaemon calls os.Exit(1) on failure. When kmeshctl dnsproxy enable is run without a pod name, it iterates over all kmesh daemons. If an error occurs for one daemon (e.g., it's not reachable), the entire command will exit, preventing it from configuring the other daemons.

The function should be refactored to return an error instead of exiting. This allows the caller (ControlDnsproxy) to handle the error gracefully, such as logging it and continuing to the next pod in the loop.

func SetDnsproxyPerKmeshDaemon(cli kube.CLIClient, podName, info string) error {
	var status string
	if info == "enable" {
		status = "true"
	} else {
		status = "false"
	}

	fw, err := utils.CreateKmeshPortForwarder(cli, podName)
	if err != nil {
		return fmt.Errorf("failed to create port forwarder for Kmesh daemon pod %s: %v", podName, err)
	}
	if err := fw.Start(); err != nil {
		return fmt.Errorf("failed to start port forwarder for Kmesh daemon pod %s: %v", podName, err)
	}
	defer fw.Close()

	url := fmt.Sprintf("http://%s%s?enable=%s", fw.Address(), patternDnsproxy, status)

	req, err := http.NewRequest(http.MethodPost, url, nil)
	if err != nil {
		return fmt.Errorf("Error creating request: %v", err)
	}

	req.Header.Set("Content-Type", "application/json")
	httpClient := &http.Client{}
	resp, err := httpClient.Do(req)
	if err != nil {
		return fmt.Errorf("failed to make HTTP request: %v", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		bodyBytes, readErr := io.ReadAll(resp.Body)
		if readErr != nil {
			return fmt.Errorf("error reading response body for status %d: %v", resp.StatusCode, readErr)
		}
		return fmt.Errorf("received status code %d, response: %s", resp.StatusCode, string(bodyBytes))
	}
	return nil
}

2 changes: 1 addition & 1 deletion daemon/manager/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ func Execute(configs *options.BootstrapConfigs) error {
log.Info("controller start successfully")
defer c.Stop()

statusServer := status.NewServer(c.GetXdsClient(), configs, bpfLoader)
statusServer := status.NewServer(c, configs, bpfLoader)
statusServer.StartServer()
defer func() {
_ = statusServer.StopServer()
Expand Down
2 changes: 2 additions & 0 deletions daemon/options/bpf.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ type BpfConfig struct {
EnablePeriodicReport bool
EnableProfiling bool
EnableIPsec bool
EnableDnsProxy bool
}

func (c *BpfConfig) AttachFlags(cmd *cobra.Command) {
Expand All @@ -45,6 +46,7 @@ func (c *BpfConfig) AttachFlags(cmd *cobra.Command) {
cmd.PersistentFlags().BoolVar(&c.EnablePeriodicReport, "periodic-report", false, "enable kmesh periodic report in daemon process")
cmd.PersistentFlags().BoolVar(&c.EnableProfiling, "profiling", false, "whether to enable profiling or not, default to false")
cmd.PersistentFlags().BoolVar(&c.EnableIPsec, "enable-ipsec", false, "enable ipsec encryption and authentication between nodes")
cmd.PersistentFlags().BoolVar(&c.EnableDnsProxy, "enable-dns-proxy", false, "enable dns proxy, a DNS server will be started in kmesh daemon and serve DNS requests")
}

func (c *BpfConfig) ParseConfig() error {
Expand Down
6 changes: 1 addition & 5 deletions deploy/charts/kmesh-helm/templates/daemonset.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ spec:
prometheus.io/scrape: "true"
spec:
containers:
- args: ["./start_kmesh.sh {{ .Values.deploy.kmesh.containers.kmeshDaemonArgs }}"]
- args: ["./start_kmesh.sh {{ .Values.deploy.kmesh.containers.kmeshDaemonArgs }}{{ if .Values.features.dnsProxy.enabled }} --enable-dns-proxy{{ end }}"]
command:
- /bin/sh
- -c
Expand Down Expand Up @@ -51,10 +51,6 @@ spec:
valueFrom:
fieldRef:
fieldPath: spec.nodeName
{{ if .Values.features.dnsProxy.enabled }}
- name: KMESH_ENABLE_DNS_PROXY
value: {{ .Values.features.dnsProxy.enabled | quote }}
{{- end }}
image: {{ .Values.deploy.kmesh.image.repository }}:{{ .Values.deploy.kmesh.image.tag | default .Chart.AppVersion }}
imagePullPolicy: {{ .Values.deploy.kmesh.imagePullPolicy }}
name: kmesh
Expand Down
4 changes: 1 addition & 3 deletions deploy/yaml/kmesh.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ spec:
command: ["/bin/sh", "-c"]
args:
[
"./start_kmesh.sh --mode=dual-engine --enable-bypass=false",
"./start_kmesh.sh --mode=dual-engine --enable-bypass=false --enable-dns-proxy",
]
securityContext:
privileged: true
Expand Down Expand Up @@ -107,8 +107,6 @@ spec:
valueFrom:
fieldRef:
fieldPath: spec.nodeName
- name: KMESH_ENABLE_DNS_PROXY
value: "true"
volumeMounts:
- name: mnt
mountPath: /mnt
Expand Down
1 change: 1 addition & 0 deletions docs/ctl/kmeshctl.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ Kmesh command line tools to operate and debug Kmesh
### SEE ALSO

* [kmeshctl authz](kmeshctl_authz.md) - Manage xdp authz eBPF program for Kmesh's authz offloading
* [kmeshctl dnsproxy](kmeshctl_dnsproxy.md) - Enable or disable Kmesh's DNS proxy
* [kmeshctl dump](kmeshctl_dump.md) - Dump config of kernel-native or dual-engine mode
* [kmeshctl log](kmeshctl_log.md) - Get or set kmesh-daemon's logger level
* [kmeshctl monitoring](kmeshctl_monitoring.md) - Control Kmesh's monitoring to be turned on as needed
Expand Down
31 changes: 31 additions & 0 deletions docs/ctl/kmeshctl_dnsproxy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
## kmeshctl dnsproxy

Enable or disable Kmesh's DNS proxy

```bash
kmeshctl dnsproxy [pod] enable|disable [flags]
```

### Examples

```bash
# Enable Kmesh's DNS proxy:
kmeshctl dnsproxy <kmesh-daemon-pod> enable

# Disable Kmesh's DNS proxy:
kmeshctl dnsproxy <kmesh-daemon-pod> disable

# Enable/Disable DNS proxy on all kmesh daemons in the cluster:
kmeshctl dnsproxy enable
kmeshctl dnsproxy disable
```

### Options

```bash
-h, --help help for dnsproxy
```

### SEE ALSO

* [kmeshctl](kmeshctl.md) - Kmesh command line tools to operate and debug Kmesh
Loading
Loading