Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/service-waiter/cmd/redis.go
2498 views
1
// Copyright (c) 2020 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
package cmd
6
7
import (
8
"context"
9
"net"
10
"time"
11
12
"github.com/redis/go-redis/v9"
13
"github.com/spf13/cobra"
14
"github.com/spf13/viper"
15
16
"github.com/gitpod-io/gitpod/common-go/log"
17
)
18
19
var redisCmd = &cobra.Command{
20
Use: "redis",
21
Short: "waits for redis to become reachable",
22
PreRun: func(cmd *cobra.Command, args []string) {
23
err := viper.BindPFlags(cmd.Flags())
24
if err != nil {
25
log.WithError(err).Fatal("cannot bind Viper to pflags")
26
}
27
},
28
Run: func(cmd *cobra.Command, args []string) {
29
host := viper.GetString("host")
30
port := viper.GetString("port")
31
32
timeout := getTimeout()
33
done := make(chan bool)
34
logger := log.WithField("timeout", timeout.String()).WithField("host", host).WithField("port", port)
35
go func() {
36
logger.Info("Attempting to connect to redis")
37
for {
38
redisClient := redis.NewClient(&redis.Options{
39
Addr: net.JoinHostPort(host, port),
40
})
41
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
42
defer cancel()
43
44
err := redisClient.Ping(ctx).Err()
45
if err == nil {
46
break
47
}
48
49
logger.WithError(err).Error("Failed to ping redis, retrying...")
50
<-time.After(time.Second)
51
}
52
53
close(done)
54
}()
55
56
select {
57
case <-done:
58
logger.Info("Redis became reachable")
59
return
60
case <-time.After(timeout):
61
logger.Fatal("Redis did not become available in time")
62
}
63
},
64
}
65
66
func init() {
67
rootCmd.AddCommand(redisCmd)
68
69
redisCmd.Flags().StringP("host", "H", "redis", "Host to try and connect to")
70
redisCmd.Flags().StringP("port", "p", "6379", "Port to connect on")
71
}
72
73