func main() {
	var configPath string

	flag.StringVar(&configPath, "config", "", "Path to redis config")
	flag.Parse()

	if configPath == "" {
		log.Fatal("Missing flag --config")
	}

	if _, err := os.Stat(configPath); os.IsNotExist(err) {
		log.Fatal("Redis config does not exist")
	}

	conf, err := redisconf.Load(configPath)
	if err != nil {
		log.Fatal("Invalid redis config")
	}

	_, err = client.Connect(client.Host(conf.Host()), client.Port(conf.Port()))
	if err != nil {
		log.Fatal("Can not connect to Redis")
	}

	m := metrics.Metrics{
		metrics.Metric{
			Name:  "foo",
			Value: 1,
			Unit:  "bar",
		},
	}
	encoder := json.NewEncoder(os.Stdout)
	encoder.Encode(m)
}
func (resetter *Resetter) ResetRedis() error {
	if err := resetter.stopRedis(); err != nil {
		return err
	}

	if err := resetter.deleteData(); err != nil {
		return err
	}

	if err := resetter.resetConfigWithNewPassword(); err != nil {
		return err
	}

	if err := resetter.startRedis(); err != nil {
		return err
	}

	conf, err := redisconf.Load(resetter.liveConfPath)
	if err != nil {
		return err
	}

	address, err := net.ResolveTCPAddr("tcp", "127.0.0.1:"+conf.Get("port"))
	if err != nil {
		return err
	}

	return resetter.portChecker.Check(address, resetter.timeout)
}
Exemple #3
0
func credentialsHandler(configPath string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		conf, err := redisconf.Load(configPath)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		port, err := strconv.Atoi(conf.Get("port"))
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		password := conf.Get("requirepass")

		credentials := struct {
			Port     int    `json:"port"`
			Password string `json:"password"`
		}{
			Port:     port,
			Password: password,
		}

		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		encoder := json.NewEncoder(w)
		encoder.Encode(credentials)
	}
}
func startRedis(confPath string) (*gexec.Session, redis.Conn) {
	redisSession, err := gexec.Start(exec.Command("redis-server", confPath), GinkgoWriter, GinkgoWriter)
	Ω(err).ShouldNot(HaveOccurred())

	conf, err := redisconf.Load(confPath)
	Ω(err).ShouldNot(HaveOccurred())

	port, err := strconv.Atoi(conf.Get("port"))
	Ω(err).ShouldNot(HaveOccurred())

	Expect(helpers.ServiceAvailable(uint(port))).To(BeTrue())
	return redisSession, helpers.BuildRedisClient(uint(port), "localhost", conf.Get("requirepass"))
}
Exemple #5
0
func templateRedisConf(config *agentconfig.Config, logger lager.Logger) {
	newConfig, err := redisconf.Load(config.DefaultConfPath)
	if err != nil {
		logger.Fatal("Error loading default redis.conf", err, lager.Data{
			"path": config.DefaultConfPath,
		})
	}

	if fileExists(config.ConfPath) {
		existingConf, err := redisconf.Load(config.ConfPath)
		if err != nil {
			logger.Fatal("Error loading existing redis.conf", err, lager.Data{
				"path": config.ConfPath,
			})
		}
		err = newConfig.InitForDedicatedNode(existingConf.Password())
	} else {
		err = newConfig.InitForDedicatedNode()
	}

	if err != nil {
		logger.Fatal("Error initializing redis conf for dedicated node", err)
	}

	err = newConfig.Save(config.ConfPath)
	if err != nil {
		logger.Fatal("Error saving redis.conf", err, lager.Data{
			"path": config.ConfPath,
		})
	}

	logger.Info("Finished writing redis.conf", lager.Data{
		"path": config.ConfPath,
		"conf": newConfig,
	})
}
func (resetter *Resetter) resetConfigWithNewPassword() error {
	conf, err := redisconf.Load(resetter.defaultConfPath)
	if err != nil {
		return err
	}

	err = conf.InitForDedicatedNode()
	if err != nil {
		return err
	}

	if err := conf.Save(resetter.liveConfPath); err != nil {
		return err
	}

	return nil
}
func (repo *LocalRepository) FindByID(instanceID string) (*Instance, error) {
	conf, err := redisconf.Load(repo.InstanceConfigPath(instanceID))
	if err != nil {
		return nil, err
	}

	port, err := strconv.Atoi(conf.Get("port"))
	if err != nil {
		return nil, err
	}

	instance := &Instance{
		ID:       instanceID,
		Password: conf.Get("requirepass"),
		Port:     port,
		Host:     repo.RedisConf.Host,
	}

	return instance, nil
}
func checkRedisStopAndStart(c chan<- bool) {
	defer GinkgoRecover()

	Eventually(redisSession, "3s").Should(gexec.Exit())

	// Sleep here to emulate the time it takes monit to do it's thing
	time.Sleep(time.Millisecond * 200)

	var err error
	redisSession, err = gexec.Start(exec.Command("redis-server", redisConfPath), GinkgoWriter, GinkgoWriter)
	Ω(err).ShouldNot(HaveOccurred())

	conf, err := redisconf.Load(redisConfPath)
	Ω(err).ShouldNot(HaveOccurred())

	port, err := strconv.Atoi(conf.Get("port"))
	Ω(err).ShouldNot(HaveOccurred())

	Expect(helpers.ServiceAvailable(uint(port))).To(BeTrue())

	c <- true
}
func (f *configFinder) Find() ([]RedisConfig, error) {
	paths, err := f.findFiles()
	if err != nil {
		return nil, err
	}

	redisConfigs := make([]RedisConfig, len(paths))

	for i, path := range paths {
		config, err := redisconf.Load(path)
		if err != nil {
			return nil, err
		}

		redisConfigs[i] = RedisConfig{
			Conf: config,
			Path: path,
		}
	}

	return redisConfigs, err
}
func main() {
	var configPath string

	flag.StringVar(&configPath, "config", "", "Path to redis config file")
	flag.Parse()

	if configPath == "" {
		log.Fatal("Missing flag --config")
	}

	config, err := redisconf.Load(configPath)
	if err != nil {
		log.Fatalf("Error loading Redis config file: %s", err)
	}

	port := config.Port()
	host := config.Host()
	password := config.Password()

	clientConnection, err := client.Connect(
		client.Port(port),
		client.Host(host),
		client.Password(password),
	)
	if err != nil {
		log.Fatalf("Error connecting to Redis: %s", err)
	}

	m, err := metrics.CPULoad(clientConnection)
	if err != nil {
		log.Fatalf("Error getting metrics: %s", err)
	}

	if err := json.NewEncoder(os.Stdout).Encode(m); err != nil {
		log.Fatalf("Error encoding json: %s", err)
	}
}
Exemple #11
0
func redisPIDProvider(instancePath string) process.PIDProvider {
	return func() (int, error) {
		instanceConf, err := redisconf.Load(path.Join(instancePath, "redis.conf"))
		if err != nil {
			return 0, err
		}

		client, err := client.Connect(
			client.Host("localhost"),
			client.Port(instanceConf.Port()),
			client.Password(instanceConf.Password()),
			client.CmdAliases(instanceConf.CommandAliases()),
		)
		if err != nil {
			return 0, err
		}

		pidfile, err := client.GetConfig("pidfile")
		if err != nil {
			return 0, err
		}
		return process.ReadPID(pidfile)
	}
}
func moveDataFor(propertyName, fileName, redisConfFilePath string) error {
	var fileContents []byte
	var redisConf redisconf.Conf
	var err error

	if redisConf, err = redisconf.Load(redisConfFilePath); err != nil {
		return err
	}
	if redisConf.Get(propertyName) != "" {
		os.Remove(fileName)
		return nil
	}

	if fileContents, err = ioutil.ReadFile(fileName); err != nil {
		return err
	}

	redisConf.Set(propertyName, string(fileContents))
	if err = redisConf.Save(redisConfFilePath); err != nil {
		return err
	}
	os.Remove(fileName)
	return nil
}
	AfterEach(func() {
		stopAgent(agentSession)
	})

	Context("when there is no redis.conf", func() {
		BeforeEach(func() {
			os.Remove(redisConfPath)
			agentSession = startAgent()
		})

		loadRedisConfFileWhenItExists := func() redisconf.Conf {
			Eventually(func() bool {
				return helpers.FileExists(redisConfPath)
			}).Should(BeTrue())
			conf, err := redisconf.Load(redisConfPath)
			Expect(err).ToNot(HaveOccurred())
			return conf
		}

		It("copies a redis.conf from the default path and adds a password", func() {
			conf := loadRedisConfFileWhenItExists()

			Expect(conf.Get("daemonize")).To(Equal("no"))
			Expect(conf.HasKey("requirepass")).To(BeTrue())
		})

		It("creates a new password each time", func() {
			initialConf := loadRedisConfFileWhenItExists()

			helpers.KillProcess(agentSession)
var agentSession *gexec.Session

var _ = Describe("DELETE /", func() {

	var (
		redisConn         redis.Conn
		aofPath           string
		originalRedisConf redisconf.Conf
	)

	BeforeEach(func() {
		agentSession = startAgent()
		redisSession, aofPath = startRedisAndBlockUntilUp()

		var err error
		originalRedisConf, err = redisconf.Load(redisConfPath)
		Ω(err).ShouldNot(HaveOccurred())

		redisRestarted := make(chan bool)
		httpRequestReturned := make(chan bool)

		go checkRedisStopAndStart(redisRestarted)
		go doResetRequest(httpRequestReturned)

		select {
		case <-redisRestarted:
			<-httpRequestReturned
		case <-time.After(time.Second * 10):
			Fail("Test timed out after 10 seconds")
		}
				configMigrator.Migrate()

				_, err := os.Stat(redisPortFilePath)
				Expect(os.IsNotExist(err)).To(BeTrue())
				_, err = os.Stat(redisPasswordFilePath)
				Expect(os.IsNotExist(err)).To(BeTrue())
			})

			It("copies the port and password to redis.conf", func() {
				ioutil.WriteFile(redisConfFile, []byte("#port 63490"), 0777)
				ioutil.WriteFile(redisPortFilePath, []byte("3455"), 0777)
				ioutil.WriteFile(redisPasswordFilePath, []byte("secret-password"), 0777)

				configMigrator.Migrate()

				redisConfigValues, err := redisconf.Load(redisConfFile)
				Expect(err).ToNot(HaveOccurred())
				Expect(redisConfigValues.Get("port")).To(Equal("3455"))
				Expect(redisConfigValues.Get("requirepass")).To(Equal("secret-password"))
			})

			It("does not change the other values", func() {
				ioutil.WriteFile(redisConfFile, []byte("foo bar"), 0777)

				configMigrator.Migrate()

				redisConfigValues, err := redisconf.Load(redisConfFile)
				Expect(err).ToNot(HaveOccurred())
				Expect(redisConfigValues.Get("foo")).To(Equal("bar"))
			})
			os.Mkdir(redisInstanceDir, 0755)
			copyOverFromAssets("redis-server.port", redisInstanceDir)
			copyOverFromAssets("redis-server.password", redisInstanceDir)
			copyOverFromAssets("redis.conf", redisInstanceDir)

			executablePath := buildExecutable("github.com/pivotal-cf/cf-redis-broker/cmd/configmigrator")
			session := launchProcessWithBrokerConfig(executablePath, "broker.yml")
			session.Wait(10 * time.Second)

			Expect(session.ExitCode()).To(Equal(0))
			_, err := os.Stat(path.Join(redisInstanceDir, "redis-server.port"))
			Expect(os.IsNotExist(err)).To(BeTrue())
			_, err = os.Stat(path.Join(redisInstanceDir, "redis-server.password"))
			Expect(os.IsNotExist(err)).To(BeTrue())

			redisConfValues, _ := redisconf.Load(path.Join(redisInstanceDir, "redis.conf"))
			Expect(redisConfValues.Get("port")).To(Equal("1234"))
			Expect(redisConfValues.Get("requirepass")).To(Equal("secret-password"))
		})
	})
})

func copyOverFromAssets(fileName, dir string) {
	assetPath := helpers.AssetPath(fileName)
	data, _ := ioutil.ReadFile(assetPath)
	ioutil.WriteFile(path.Join(dir, fileName), data, 0644)
}

func buildExecutable(sourcePath string) string {
	executable, err := gexec.Build(sourcePath)
	if err != nil {
	"strconv"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"github.com/pivotal-cf/cf-redis-broker/redisconf"
)

var _ = Describe("redisconf", func() {
	Describe("InitForDedicatedNode", func() {
		var conf redisconf.Conf

		BeforeEach(func() {
			path, err := filepath.Abs(path.Join("assets", "redis.conf"))
			Expect(err).ToNot(HaveOccurred())
			conf, err = redisconf.Load(path)
			Expect(err).ToNot(HaveOccurred())
			Expect(conf.Get("maxmemory")).To(BeEmpty())
			Expect(conf.Password()).To(BeEmpty())
		})

		It("sets the max memory parameter", func() {
			err := conf.InitForDedicatedNode()
			Expect(err).ToNot(HaveOccurred())

			maxmemory := conf.Get("maxmemory")
			Expect(maxmemory).ToNot(BeEmpty())

			_, err = strconv.Atoi(maxmemory)
			Expect(err).ToNot(HaveOccurred())
		})