本文整理汇总了Golang中github.com/sorintlab/stolon/Godeps/_workspace/src/github.com/davecgh/go-spew/spew.Sprintf函数的典型用法代码示例。如果您正苦于以下问题:Golang Sprintf函数的具体用法?Golang Sprintf怎么用?Golang Sprintf使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Sprintf函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: updateConfigHandler
func (s *Sentinel) updateConfigHandler(w http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
vars := mux.Vars(req)
configName := vars["name"]
// only configID == current is currently supported
if configName != "current" {
log.Errorf("wrong config name %q", configName)
http.Error(w, fmt.Sprintf("wrong config name %q", configName), http.StatusBadRequest)
}
decoder := json.NewDecoder(req.Body)
var config *cluster.NilConfig
err := decoder.Decode(&config)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
}
s.updateMutex.Lock()
defer s.updateMutex.Unlock()
if !s.isLeader() {
log.Errorf("we aren't the sentinels leader. cannot process config update request.")
http.Error(w, "we aren't the sentinels leader. cannot process config update request.", http.StatusBadRequest)
}
log.Infof(spew.Sprintf("updating config to %#v", config))
e := s.e
cd, pair, err := e.GetClusterData()
if err != nil {
log.Errorf("error retrieving cluster data: %v", err)
http.Error(w, fmt.Sprintf("error retrieving cluster data: %v", err), http.StatusInternalServerError)
}
if cd == nil {
log.Errorf("empty cluster data")
http.Error(w, "empty cluster data", http.StatusInternalServerError)
}
if cd.ClusterView == nil {
log.Errorf("empty cluster view")
http.Error(w, "empty cluster view", http.StatusInternalServerError)
}
log.Debugf(spew.Sprintf("keepersState: %#v", cd.KeepersState))
log.Debugf(spew.Sprintf("clusterView: %#v", cd.ClusterView))
newcv := cd.ClusterView.Copy()
newcv.Config = config
newcv.Version += 1
if _, err := e.SetClusterData(cd.KeepersState, newcv, pair); err != nil {
log.Errorf("error saving clusterdata: %v", err)
http.Error(w, fmt.Sprintf("error saving clusterdata: %v", err), http.StatusInternalServerError)
}
}
示例2: NewPostgresKeeper
func NewPostgresKeeper(id string, cfg config, stop chan bool, end chan error) (*PostgresKeeper, error) {
etcdPath := filepath.Join(common.EtcdBasePath, cfg.clusterName)
e, err := etcdm.NewEtcdManager(cfg.etcdEndpoints, etcdPath, common.DefaultEtcdRequestTimeout)
if err != nil {
return nil, fmt.Errorf("cannot create etcd manager: %v", err)
}
clusterConfig, _, err := e.GetClusterConfig()
if err != nil {
return nil, fmt.Errorf("cannot get cluster config: %v", err)
}
log.Debugf(spew.Sprintf("clusterConfig: %#v", clusterConfig))
p := &PostgresKeeper{id: id,
dataDir: cfg.dataDir,
e: e,
listenAddress: cfg.listenAddress,
port: cfg.port,
pgListenAddress: cfg.pgListenAddress,
pgPort: cfg.pgPort,
clusterConfig: clusterConfig,
stop: stop,
end: end,
}
serverParameters := p.createServerParameters()
pgm, err := postgresql.NewManager(id, cfg.pgBinPath, cfg.dataDir, serverParameters, p.getOurConnString(), p.getOurReplConnString(), clusterConfig.PGReplUser, clusterConfig.PGReplPassword, clusterConfig.RequestTimeout)
if err != nil {
return nil, fmt.Errorf("cannot create postgres manager: %v", err)
}
p.pgm = pgm
return p, nil
}
示例3: Check
func (c *ClusterChecker) Check() {
cv, _, err := c.e.GetClusterView()
if err != nil {
log.Errorf("cannot get clusterview: %v", err)
c.C <- pollon.ConfData{DestAddr: nil}
return
}
log.Debugf(spew.Sprintf("clusterview: %#v", cv))
if cv == nil {
log.Infof("no clusterview available, closing connections to previous master")
c.C <- pollon.ConfData{DestAddr: nil}
return
}
pc := cv.ProxyConf
if pc == nil {
log.Infof("no proxyconf available, closing connections to previous master")
c.C <- pollon.ConfData{DestAddr: nil}
if err := c.SetProxyInfo(c.e, cv.Version, 2*cluster.DefaultProxyCheckInterval); err != nil {
log.Errorf("failed to update proxyInfo: %v", err)
}
return
}
addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%s", pc.Host, pc.Port))
if err != nil {
log.Errorf("err: %v", err)
c.C <- pollon.ConfData{DestAddr: nil}
return
}
log.Infof("master address: %v", addr)
if err = c.SetProxyInfo(c.e, cv.Version, 2*cluster.DefaultProxyCheckInterval); err != nil {
log.Errorf("failed to update proxyInfo: %v", err)
}
c.C <- pollon.ConfData{DestAddr: addr}
}
示例4: NewPostgresKeeper
func NewPostgresKeeper(id string, cfg config, stop chan bool, end chan error) (*PostgresKeeper, error) {
etcdPath := filepath.Join(common.EtcdBasePath, cfg.clusterName)
e, err := etcdm.NewEtcdManager(cfg.etcdEndpoints, etcdPath, common.DefaultEtcdRequestTimeout)
if err != nil {
return nil, fmt.Errorf("cannot create etcd manager: %v", err)
}
cd, _, err := e.GetClusterData()
if err != nil {
return nil, fmt.Errorf("error retrieving cluster data: %v", err)
}
var cv *cluster.ClusterView
if cd == nil {
cv = cluster.NewClusterView()
} else {
cv = cd.ClusterView
}
log.Debugf(spew.Sprintf("clusterView: %#v", cv))
clusterConfig := cv.Config.ToConfig()
log.Debugf(spew.Sprintf("clusterConfig: %#v", clusterConfig))
p := &PostgresKeeper{id: id,
dataDir: cfg.dataDir,
e: e,
listenAddress: cfg.listenAddress,
port: cfg.port,
pgListenAddress: cfg.pgListenAddress,
pgPort: cfg.pgPort,
clusterConfig: clusterConfig,
stop: stop,
end: end,
}
followersIDs := cv.GetFollowersIDs(p.id)
pgParameters := p.createPGParameters(followersIDs)
pgm, err := postgresql.NewManager(id, cfg.pgBinPath, cfg.dataDir, cfg.pgConfDir, pgParameters, p.getOurConnString(), p.getOurReplConnString(), clusterConfig.PGReplUser, clusterConfig.PGReplPassword, clusterConfig.RequestTimeout)
if err != nil {
return nil, fmt.Errorf("cannot create postgres manager: %v", err)
}
p.pgm = pgm
return p, nil
}
示例5: setLeaderSentinelInfo
func (s *Sentinel) setLeaderSentinelInfo(ttl time.Duration) error {
sentinelInfo := &cluster.SentinelInfo{
ID: s.id,
ListenAddress: s.listenAddress,
Port: s.port,
}
log.Debugf(spew.Sprintf("sentinelInfo: %#v", sentinelInfo))
if _, err := s.e.SetLeaderSentinelInfo(sentinelInfo, ttl); err != nil {
return err
}
return nil
}
示例6: NewSentinel
func NewSentinel(id string, cfg config, stop chan bool, end chan bool) (*Sentinel, error) {
etcdPath := filepath.Join(common.EtcdBasePath, cfg.clusterName)
e, err := etcdm.NewEtcdManager(cfg.etcdEndpoints, etcdPath, common.DefaultEtcdRequestTimeout)
if err != nil {
return nil, fmt.Errorf("cannot create etcd manager: %v", err)
}
cd, _, err := e.GetClusterData()
if err != nil {
return nil, fmt.Errorf("error retrieving cluster data: %v", err)
}
var cv *cluster.ClusterView
if cd == nil {
cv = cluster.NewClusterView()
} else {
cv = cd.ClusterView
}
log.Debugf(spew.Sprintf("clusterView: %#v", cv))
clusterConfig := cv.Config.ToConfig()
if err != nil {
return nil, fmt.Errorf("cannot get cluster config: %v", err)
}
log.Debugf(spew.Sprintf("clusterConfig: %#v", clusterConfig))
lManager := e.NewLeaseManager()
return &Sentinel{
id: id,
e: e,
listenAddress: cfg.listenAddress,
port: cfg.port,
lManager: lManager,
clusterConfig: clusterConfig,
stop: stop,
end: end}, nil
}
示例7: SetProxyInfo
func (c *ClusterChecker) SetProxyInfo(e *store.StoreManager, cvVersion int, ttl time.Duration) error {
proxyInfo := &cluster.ProxyInfo{
ID: c.id,
ListenAddress: c.listenAddress,
Port: c.port,
ClusterViewVersion: cvVersion,
}
log.Debugf(spew.Sprintf("proxyInfo: %#v", proxyInfo))
if err := c.e.SetProxyInfo(proxyInfo, ttl); err != nil {
return err
}
return nil
}
示例8: publish
func (p *PostgresKeeper) publish() error {
if kubernetes.OnKubernetes() {
log.Infof("running under kubernetes. Not using store discovery")
return nil
}
discoveryInfo := &cluster.KeeperDiscoveryInfo{
ListenAddress: p.listenAddress,
Port: p.port,
}
log.Debugf(spew.Sprintf("discoveryInfo: %#v", discoveryInfo))
if err := p.e.SetKeeperDiscoveryInfo(p.id, discoveryInfo); err != nil {
return err
}
return nil
}
示例9: publish
func (p *PostgresKeeper) publish() error {
if kubernetes.OnKubernetes() {
log.Infof("running under kubernetes. Not publishing ourself to etcd")
return nil
}
discoveryInfo := &cluster.MemberDiscoveryInfo{
Host: p.listenAddress,
Port: p.port,
}
log.Debugf(spew.Sprintf("discoveryInfo: %#v", discoveryInfo))
if _, err := p.e.SetMemberDiscoveryInfo(p.id, discoveryInfo); err != nil {
return err
}
return nil
}
示例10: NewSentinel
func NewSentinel(id string, cfg config, stop chan bool, end chan bool) (*Sentinel, error) {
etcdPath := filepath.Join(common.EtcdBasePath, cfg.clusterName)
e, err := etcdm.NewEtcdManager(cfg.etcdEndpoints, etcdPath, common.DefaultEtcdRequestTimeout)
if err != nil {
return nil, fmt.Errorf("cannot create etcd manager: %v", err)
}
clusterConfig, _, err := e.GetClusterConfig()
if err != nil {
return nil, fmt.Errorf("cannot get cluster config: %v", err)
}
log.Debugf(spew.Sprintf("clusterConfig: %#v", clusterConfig))
lManager := e.NewLeaseManager()
return &Sentinel{id: id, e: e, lManager: lManager, clusterConfig: clusterConfig, stop: stop, end: end}, nil
}
示例11: TestParseTimeLineHistory
func TestParseTimeLineHistory(t *testing.T) {
tests := []struct {
contents string
tlsh cluster.PostgresTimeLinesHistory
err error
}{
{
contents: "",
tlsh: cluster.PostgresTimeLinesHistory{},
err: nil,
},
{
contents: `1 0/5000090 no recovery target specified`,
tlsh: cluster.PostgresTimeLinesHistory{
{
TimelineID: 1,
SwitchPoint: 83886224,
Reason: "no recovery target specified",
},
},
err: nil,
},
}
for i, tt := range tests {
tlsh, err := parseTimeLinesHistory(tt.contents)
t.Logf("test #%d", i)
if tt.err != nil {
if err == nil {
t.Errorf("got no error, wanted error: %v", tt.err)
} else if tt.err.Error() != err.Error() {
t.Errorf("got error: %v, wanted error: %v", err, tt.err)
}
} else {
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !reflect.DeepEqual(tlsh, tt.tlsh) {
t.Errorf(spew.Sprintf("#%d: wrong timeline history: got: %#+v, want: %#+v", i, tlsh, tt.tlsh))
}
}
}
}
示例12: GetBestStandby
func (s *Sentinel) GetBestStandby(cv *cluster.ClusterView, keepersState cluster.KeepersState, master string) (string, error) {
var bestID string
masterState := keepersState[master]
for id, k := range keepersState {
log.Debugf(spew.Sprintf("id: %s, k: %#v", id, k))
if id == master {
log.Debugf("ignoring node %q since it's the current master", id)
continue
}
if !k.Healthy {
log.Debugf("ignoring node %q since it's not healthy", id)
continue
}
if k.ClusterViewVersion != cv.Version {
log.Debugf("ignoring node since its clusterView version (%d) is different that the actual one (%d)", k.ClusterViewVersion, cv.Version)
continue
}
if k.PGState == nil {
log.Debugf("ignoring node since its pg state is unknown")
continue
}
if masterState.PGState.TimelineID != k.PGState.TimelineID {
log.Debugf("ignoring node since its pg timeline (%s) is different than master timeline (%d)", keepersState[id].PGState.TimelineID, masterState.PGState.TimelineID)
continue
}
if bestID == "" {
bestID = id
continue
}
if k.PGState.XLogPos > keepersState[bestID].PGState.XLogPos {
bestID = id
}
}
if bestID == "" {
return "", fmt.Errorf("no standbys available")
}
return bestID, nil
}
示例13: Start
func (p *PostgresKeeper) Start() {
endSMCh := make(chan struct{})
endPgStatecheckerCh := make(chan struct{})
endApiCh := make(chan error)
var err error
var cd *cluster.ClusterData
// TODO(sgotti) make the postgres manager stateless and instantiate a
// new one at every check loop, this will avoid the need to loop here
// to get the clusterconfig
for {
cd, _, err = p.e.GetClusterData()
if err == nil {
break
}
log.Errorf("error retrieving cluster data: %v", err)
time.Sleep(cluster.DefaultSleepInterval)
}
var cv *cluster.ClusterView
if cd == nil {
cv = cluster.NewClusterView()
} else {
cv = cd.ClusterView
}
log.Debugf(spew.Sprintf("clusterView: %#v", cv))
p.clusterConfig = cv.Config.ToConfig()
log.Debugf(spew.Sprintf("clusterConfig: %#v", p.clusterConfig))
if err := p.loadCVVersion(); err != nil {
p.end <- fmt.Errorf("failed to load cluster version file: %v", err)
return
}
// TODO(sgotti) reconfigure the various configurations options (PGRepl*
// and RequestTimeout) after a changed cluster config
followersIDs := cv.GetFollowersIDs(p.id)
pgParameters := p.createPGParameters(followersIDs)
pgm := postgresql.NewManager(p.id, cfg.pgBinPath, cfg.dataDir, cfg.pgConfDir, pgParameters, p.getOurConnString(), p.getOurReplConnString(), p.clusterConfig.PGReplUser, p.clusterConfig.PGReplPassword, p.clusterConfig.RequestTimeout)
p.pgm = pgm
p.pgm.Stop(true)
http.HandleFunc("/info", p.infoHandler)
http.HandleFunc("/pgstate", p.pgStateHandler)
go func() {
endApiCh <- http.ListenAndServe(fmt.Sprintf("%s:%s", p.listenAddress, p.port), nil)
}()
ctx, cancel := context.WithCancel(context.Background())
smTimerCh := time.NewTimer(0).C
updatePGStateTimerCh := time.NewTimer(0).C
for true {
select {
case <-p.stop:
log.Debugf("stopping stolon keeper")
cancel()
p.pgm.Stop(true)
p.end <- nil
return
case <-smTimerCh:
go func() {
p.postgresKeeperSM(ctx)
endSMCh <- struct{}{}
}()
case <-endSMCh:
smTimerCh = time.NewTimer(p.clusterConfig.SleepInterval).C
case <-updatePGStateTimerCh:
go func() {
p.updatePGState(ctx)
endPgStatecheckerCh <- struct{}{}
}()
case <-endPgStatecheckerCh:
updatePGStateTimerCh = time.NewTimer(p.clusterConfig.SleepInterval).C
case err := <-endApiCh:
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
close(p.stop)
}
}
}
示例14: updateClusterView
func (s *Sentinel) updateClusterView(cv *cluster.ClusterView, keepersState cluster.KeepersState) (*cluster.ClusterView, error) {
var wantedMasterID string
if cv.Master == "" {
log.Debugf("trying to find initial master")
// Check for an initial master
if len(keepersState) < 1 {
return nil, fmt.Errorf("cannot init cluster, no keepers registered")
}
if len(keepersState) > 1 {
return nil, fmt.Errorf("cannot init cluster, more than 1 keeper registered")
}
for id, k := range keepersState {
if k.PGState == nil {
return nil, fmt.Errorf("cannot init cluster using keeper %q since its pg state is unknown", id)
}
if !k.PGState.Initialized {
return nil, fmt.Errorf("cannot init cluster using keeper %q since pg instance is not initializied", id)
}
log.Infof("initializing cluster with master: %q", id)
wantedMasterID = id
break
}
} else {
masterID := cv.Master
wantedMasterID = masterID
masterOK := true
master, ok := keepersState[masterID]
if !ok {
return nil, fmt.Errorf("keeper state for master %q not available. This shouldn't happen!", masterID)
}
log.Debugf(spew.Sprintf("masterState: %#v", master))
if !master.Healthy {
log.Infof("master is failed")
masterOK = false
}
// Check that the wanted master is in master state (i.e. check that promotion from standby to master happened)
if !s.isKeeperConverged(master, cv) {
log.Infof("keeper %s not yet master", masterID)
masterOK = false
}
if !masterOK {
log.Infof("trying to find a standby to replace failed master")
bestStandby, err := s.GetBestStandby(cv, keepersState, masterID)
if err != nil {
log.Errorf("error trying to find the best standby: %v", err)
} else {
if bestStandby != masterID {
log.Infof("electing new master: %q", bestStandby)
wantedMasterID = bestStandby
} else {
log.Infof("cannot find a good standby to replace failed master")
}
}
}
}
newCV := cv.Copy()
newKeepersRole := newCV.KeepersRole
// Add new keepersRole from keepersState
for id, _ := range keepersState {
if _, ok := newKeepersRole[id]; !ok {
if err := newKeepersRole.Add(id, ""); err != nil {
// This shouldn't happen
panic(err)
}
}
}
// Setup master role
if cv.Master != wantedMasterID {
newCV.Master = wantedMasterID
newKeepersRole[wantedMasterID].Follow = ""
}
// Setup standbys
if cv.Master == wantedMasterID {
// wanted master is the previous one
masterState := keepersState[wantedMasterID]
if masterState.Healthy && s.isKeeperConverged(masterState, cv) {
for id, _ := range newKeepersRole {
if id == wantedMasterID {
continue
}
newKeepersRole[id].Follow = wantedMasterID
}
}
}
s.updateProxyConf(cv, newCV, keepersState)
if !newCV.Equals(cv) {
newCV.Version = cv.Version + 1
newCV.ChangeTime = time.Now()
}
return newCV, nil
//.........这里部分代码省略.........
示例15: TestParseConfig
func TestParseConfig(t *testing.T) {
tests := []struct {
in string
cfg *Config
err error
}{
{
in: "{}",
cfg: mergeDefaults(&NilConfig{}).ToConfig(),
err: nil,
},
// Test duration parsing
{
in: `{ "request_timeout": "3s" }`,
cfg: mergeDefaults(&NilConfig{RequestTimeout: &Duration{3 * time.Second}}).ToConfig(),
err: nil,
},
{
in: `{ "request_timeout": "3000ms" }`,
cfg: mergeDefaults(&NilConfig{RequestTimeout: &Duration{3 * time.Second}}).ToConfig(),
err: nil,
},
{
in: `{ "request_timeout": "-3s" }`,
cfg: nil,
err: fmt.Errorf("config validation failed: request_timeout must be positive"),
},
{
in: `{ "request_timeout": "-3s" }`,
cfg: nil,
err: fmt.Errorf("config validation failed: request_timeout must be positive"),
},
{
in: `{ "sleep_interval": "-3s" }`,
cfg: nil,
err: fmt.Errorf("config validation failed: sleep_interval must be positive"),
},
{
in: `{ "keeper_fail_interval": "-3s" }`,
cfg: nil,
err: fmt.Errorf("config validation failed: keeper_fail_interval must be positive"),
},
{
in: `{ "pg_repl_user": "" }`,
cfg: nil,
err: fmt.Errorf("config validation failed: pg_repl_user cannot be empty"),
},
{
in: `{ "pg_repl_password": "" }`,
cfg: nil,
err: fmt.Errorf("config validation failed: pg_repl_password cannot be empty"),
},
{
in: `{ "max_standbys_per_sender": 0 }`,
cfg: nil,
err: fmt.Errorf("config validation failed: max_standbys_per_sender must be at least 1"),
},
// All options defined
{
in: `{ "request_timeout": "10s", "sleep_interval": "10s", "keeper_fail_interval": "100s", "pg_repl_user": "username", "pg_repl_password": "password", "max_standbys_per_sender": 5, "synchronous_replication": true, "init_with_multiple_keepers": true,
"pg_parameters": {
"param01": "value01"
}
}`,
cfg: mergeDefaults(&NilConfig{
RequestTimeout: &Duration{10 * time.Second},
SleepInterval: &Duration{10 * time.Second},
KeeperFailInterval: &Duration{100 * time.Second},
PGReplUser: StringP("username"),
PGReplPassword: StringP("password"),
MaxStandbysPerSender: UintP(5),
SynchronousReplication: BoolP(true),
InitWithMultipleKeepers: BoolP(true),
PGParameters: &map[string]string{
"param01": "value01",
},
}).ToConfig(),
err: nil,
},
}
for i, tt := range tests {
var nilCfg *NilConfig
err := json.Unmarshal([]byte(tt.in), &nilCfg)
if err != nil {
if tt.err == nil {
t.Errorf("#%d: unexpected error: %v", i, err)
} else if tt.err.Error() != err.Error() {
t.Errorf("#%d: got error: %v, wanted error: %v", i, err, tt.err)
}
} else {
nilCfg.MergeDefaults()
cfg := nilCfg.ToConfig()
if tt.err != nil {
t.Errorf("#%d: got no error, wanted error: %v", i, tt.err)
}
if !reflect.DeepEqual(cfg, tt.cfg) {
t.Errorf(spew.Sprintf("#%d: wrong config: got: %#v, want: %#v", i, cfg, tt.cfg))
}
}
//.........这里部分代码省略.........