Path: blob/main/components/service-waiter/cmd/redis.go
2498 views
// Copyright (c) 2020 Gitpod GmbH. All rights reserved.1// Licensed under the GNU Affero General Public License (AGPL).2// See License.AGPL.txt in the project root for license information.34package cmd56import (7"context"8"net"9"time"1011"github.com/redis/go-redis/v9"12"github.com/spf13/cobra"13"github.com/spf13/viper"1415"github.com/gitpod-io/gitpod/common-go/log"16)1718var redisCmd = &cobra.Command{19Use: "redis",20Short: "waits for redis to become reachable",21PreRun: func(cmd *cobra.Command, args []string) {22err := viper.BindPFlags(cmd.Flags())23if err != nil {24log.WithError(err).Fatal("cannot bind Viper to pflags")25}26},27Run: func(cmd *cobra.Command, args []string) {28host := viper.GetString("host")29port := viper.GetString("port")3031timeout := getTimeout()32done := make(chan bool)33logger := log.WithField("timeout", timeout.String()).WithField("host", host).WithField("port", port)34go func() {35logger.Info("Attempting to connect to redis")36for {37redisClient := redis.NewClient(&redis.Options{38Addr: net.JoinHostPort(host, port),39})40ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)41defer cancel()4243err := redisClient.Ping(ctx).Err()44if err == nil {45break46}4748logger.WithError(err).Error("Failed to ping redis, retrying...")49<-time.After(time.Second)50}5152close(done)53}()5455select {56case <-done:57logger.Info("Redis became reachable")58return59case <-time.After(timeout):60logger.Fatal("Redis did not become available in time")61}62},63}6465func init() {66rootCmd.AddCommand(redisCmd)6768redisCmd.Flags().StringP("host", "H", "redis", "Host to try and connect to")69redisCmd.Flags().StringP("port", "p", "6379", "Port to connect on")70}717273