1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package chaosdaemon
17
18 import (
19 "context"
20 "fmt"
21 "net"
22
23 "github.com/golang/protobuf/ptypes/empty"
24 "github.com/pkg/errors"
25
26 "github.com/chaos-mesh/chaos-mesh/pkg/bpm"
27 pb "github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/pb"
28 "github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/util"
29 )
30
31 const (
32
33 DNSServerConfFile = "/etc/resolv.conf"
34 )
35
36 var ErrInvalidDNSServer = errors.New("invalid DNS server address")
37
38 func (s *DaemonServer) SetDNSServer(ctx context.Context,
39 req *pb.SetDNSServerRequest) (*empty.Empty, error) {
40 log := s.getLoggerFromContext(ctx)
41
42 log.Info("SetDNSServer", "request", req)
43 pid, err := s.crClient.GetPidFromContainerID(ctx, req.ContainerId)
44 if err != nil {
45 log.Error(err, "GetPidFromContainerID")
46 return nil, err
47 }
48
49 if req.Enable {
50
51
52 if net.ParseIP(req.DnsServer) == nil {
53 return nil, ErrInvalidDNSServer
54 }
55
56
57 processBuilder := bpm.DefaultProcessBuilder("sh", "-c", fmt.Sprintf("ls %s.chaos.bak || cp %s %s.chaos.bak", DNSServerConfFile, DNSServerConfFile, DNSServerConfFile)).SetContext(ctx)
58 if req.EnterNS {
59 processBuilder = processBuilder.SetNS(pid, bpm.MountNS)
60 }
61
62 cmd := processBuilder.Build(ctx)
63 output, err := cmd.CombinedOutput()
64 if err != nil {
65 log.Error(err, "execute command error", "command", cmd.String(), "output", output)
66 return nil, util.EncodeOutputToError(output, err)
67 }
68 if len(output) != 0 {
69 log.Info("command output", "output", string(output))
70 }
71
72
73
74 processBuilder = bpm.DefaultProcessBuilder("sh", "-c", fmt.Sprintf("cp %s /etc/resolv_conf_dnschaos_temp && sed -i 's/.*nameserver.*/nameserver %s/' /etc/resolv_conf_dnschaos_temp && cat /etc/resolv_conf_dnschaos_temp > %s && rm /etc/resolv_conf_dnschaos_temp", DNSServerConfFile, req.DnsServer, DNSServerConfFile)).SetContext(ctx)
75 if req.EnterNS {
76 processBuilder = processBuilder.SetNS(pid, bpm.MountNS)
77 }
78
79 cmd = processBuilder.Build(ctx)
80 output, err = cmd.CombinedOutput()
81 if err != nil {
82 log.Error(err, "execute command error", "command", cmd.String(), "output", output)
83 return nil, util.EncodeOutputToError(output, err)
84 }
85 if len(output) != 0 {
86 log.Info("command output", "output", string(output))
87 }
88 } else {
89
90 processBuilder := bpm.DefaultProcessBuilder("sh", "-c", fmt.Sprintf("ls %s.chaos.bak && cat %s.chaos.bak > %s || true", DNSServerConfFile, DNSServerConfFile, DNSServerConfFile)).SetContext(ctx)
91 if req.EnterNS {
92 processBuilder = processBuilder.SetNS(pid, bpm.MountNS)
93 }
94
95 cmd := processBuilder.Build(ctx)
96 output, err := cmd.CombinedOutput()
97 if err != nil {
98 log.Error(err, "execute command error", "command", cmd.String(), "output", output)
99 return nil, util.EncodeOutputToError(output, err)
100 }
101 if len(output) != 0 {
102 log.Info("command output", "output", string(output))
103 }
104 }
105
106 return &empty.Empty{}, nil
107 }
108