Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ping.go « nodes « praefect « internal - gitlab.com/gitlab-org/gitaly.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6aadc92e7e5f10c1b83777386f84edf1bc207c17 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
package nodes

import (
	"context"
	"errors"
	"fmt"
	"io"
	"strings"
	"sync"

	gitalyauth "gitlab.com/gitlab-org/gitaly/v16/auth"
	"gitlab.com/gitlab-org/gitaly/v16/client"
	internalclient "gitlab.com/gitlab-org/gitaly/v16/internal/gitaly/client"
	"gitlab.com/gitlab-org/gitaly/v16/internal/praefect/config"
	"gitlab.com/gitlab-org/gitaly/v16/proto/go/gitalypb"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health/grpc_health_v1"
)

type (
	virtualStorage string
	gitalyStorage  string
)

func newPingSet(conf config.Config, printer Printer, quiet bool) map[string]*Ping {
	nodeByAddress := map[string]*Ping{} // key is address

	// flatten nodes between virtual storages
	for _, vs := range conf.VirtualStorages {
		vsName := virtualStorage(vs.Name)
		for _, node := range vs.Nodes {
			gsName := gitalyStorage(node.Storage)

			n, ok := nodeByAddress[node.Address]
			if !ok {
				n = &Ping{
					storages:  map[gitalyStorage][]virtualStorage{},
					vStorages: map[virtualStorage]struct{}{},
					printer:   printer,
					quiet:     quiet,
				}
			}
			n.address = node.Address

			s := n.storages[gsName]
			n.storages[gsName] = append(s, vsName)

			n.vStorages[vsName] = struct{}{}
			n.token = node.Token
			nodeByAddress[node.Address] = n
		}
	}
	return nodeByAddress
}

// Ping is used to determine node health for a gitaly node
type Ping struct {
	address string
	// set of storages this node hosts
	storages  map[gitalyStorage][]virtualStorage
	vStorages map[virtualStorage]struct{} // set of virtual storages node belongs to
	token     string                      // auth token
	err       error                       // any error during dial/ping
	printer   Printer
	quiet     bool
}

// Address returns the address of the node
func (p *Ping) Address() string {
	return p.address
}

func (p *Ping) dial(ctx context.Context) (*grpc.ClientConn, error) {
	opts := []grpc.DialOption{
		grpc.WithBlock(),
		internalclient.UnaryInterceptor(),
		internalclient.StreamInterceptor(),
	}

	if len(p.token) > 0 {
		opts = append(opts, grpc.WithPerRPCCredentials(gitalyauth.RPCCredentialsV2(p.token)))
	}

	return client.DialContext(ctx, p.address, opts)
}

func (p *Ping) healthCheck(ctx context.Context, cc *grpc.ClientConn) (grpc_health_v1.HealthCheckResponse_ServingStatus, error) {
	hClient := grpc_health_v1.NewHealthClient(cc)

	resp, err := hClient.Check(ctx, &grpc_health_v1.HealthCheckRequest{})
	if err != nil {
		return 0, err
	}

	return resp.GetStatus(), nil
}

func (p *Ping) isConsistent(ctx context.Context, cc *grpc.ClientConn) bool {
	praefect := gitalypb.NewServerServiceClient(cc)

	if len(p.storages) == 0 {
		p.log("ERROR: current configuration has no storages")
		return false
	}

	resp, err := praefect.ServerInfo(ctx, &gitalypb.ServerInfoRequest{})
	if err != nil {
		p.log("ERROR: failed to receive state from the remote: %v", err)
		return false
	}

	if len(resp.StorageStatuses) == 0 {
		p.log("ERROR: remote has no configured storages")
		return false
	}

	storagesSet := make(map[gitalyStorage]bool, len(resp.StorageStatuses))

	knownStoragesSet := make(map[gitalyStorage]bool, len(p.storages))
	for k := range p.storages {
		knownStoragesSet[k] = true
	}

	consistent := true
	for _, status := range resp.StorageStatuses {
		gStorage := gitalyStorage(status.StorageName)

		// only proceed if the gitaly storage belongs to a configured
		// virtual storage
		if len(p.storages[gStorage]) == 0 {
			continue
		}

		if storagesSet[gStorage] {
			p.log("ERROR: remote has duplicated storage: %q", status.StorageName)
			consistent = false
			continue
		}
		storagesSet[gStorage] = true

		if status.Readable && status.Writeable {
			p.log(
				"SUCCESS: confirmed Gitaly storage %q in virtual storages %v is served",
				status.StorageName,
				p.storages[gStorage],
			)
			delete(knownStoragesSet, gStorage) // storage found
		} else {
			p.log("ERROR: storage %q is not readable or writable", status.StorageName)
			consistent = false
		}
	}

	for storage := range knownStoragesSet {
		p.log("ERROR: configured storage was not reported by remote: %q", storage)
		consistent = false
	}

	return consistent
}

func (p *Ping) log(msg string, args ...interface{}) {
	if p.quiet {
		return
	}

	p.printer.Printf("[%s]: %s", p.address, fmt.Sprintf(msg, args...))
}

// Printer is an interface for Ping to print messages
type Printer interface {
	// Printf prints a message, taking into account whether
	// or not the verbose flag has been set
	Printf(format string, args ...interface{})
}

// TextPrinter is a basic printer that writes to a writer
type TextPrinter struct {
	w io.Writer
}

// NewTextPrinter creates a new TextPrinter instance
func NewTextPrinter(w io.Writer) *TextPrinter {
	return &TextPrinter{w: w}
}

// Printf prints the message and adds a newline
func (t *TextPrinter) Printf(format string, args ...interface{}) {
	fmt.Fprintf(t.w, format, args...)
	fmt.Fprint(t.w, "\n")
}

// CheckNode checks network connectivity by issuing a healthcheck request, and
//
//	also calls the ServerInfo RPC to check disk read/write access.
func (p *Ping) CheckNode(ctx context.Context) {
	p.log("dialing...")
	cc, err := p.dial(ctx)
	if err != nil {
		p.log("ERROR: dialing failed: %v", err)
		p.err = err
		return
	}
	defer cc.Close()
	p.log("dialed successfully!")

	p.log("checking health...")
	health, err := p.healthCheck(ctx, cc)
	if err != nil {
		p.log("ERROR: unable to request health check: %v", err)
		p.err = err
		return
	}

	if health != grpc_health_v1.HealthCheckResponse_SERVING {
		p.err = fmt.Errorf(
			"health check did not report serving, instead reported: %s",
			health.String())
		p.log("ERROR: %v", p.err)
		return
	}

	p.log("SUCCESS: node is healthy!")

	p.log("checking consistency...")
	if !p.isConsistent(ctx, cc) {
		p.err = errors.New("consistency check failed")
		p.log("ERROR: %v", p.err)
		return
	}
	p.log("SUCCESS: node configuration is consistent!")
}

func (p *Ping) Error() error {
	return p.err
}

// PingAll loops through all the pings and calls CheckNode on them. Returns a PingError in case
// pinging a subset of nodes failed.
func PingAll(ctx context.Context, cfg config.Config, printer Printer, quiet bool) error {
	pings := newPingSet(cfg, printer, quiet)

	var wg sync.WaitGroup
	for _, n := range pings {
		wg.Add(1)
		go func(n *Ping) {
			defer wg.Done()
			n.CheckNode(ctx)
		}(n)
	}
	wg.Wait()

	var unhealthyAddresses []string
	for _, n := range pings {
		if n.Error() != nil {
			unhealthyAddresses = append(unhealthyAddresses, n.address)
		}
	}

	if len(unhealthyAddresses) > 0 {
		return &PingError{unhealthyAddresses}
	}

	return nil
}

// PingError is an error returned in case pinging a node failed.
type PingError struct {
	// UnhealthyAddresses contains all addresses which
	UnhealthyAddresses []string
}

// Error returns a composite error message based on which nodes were deemed unhealthy
func (n *PingError) Error() string {
	return fmt.Sprintf("the following nodes are not healthy: %s", strings.Join(n.UnhealthyAddresses, ", "))
}