本文整理匯總了Golang中github.com/juju/juju/state.Open函數的典型用法代碼示例。如果您正苦於以下問題:Golang Open函數的具體用法?Golang Open怎麽用?Golang Open使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Open函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: newState
// newState returns a new State that uses the given environment.
// The environment must have already been bootstrapped.
func newState(environ environs.Environ, mongoInfo *mongo.MongoInfo) (*state.State, error) {
config := environ.Config()
password := config.AdminSecret()
if password == "" {
return nil, fmt.Errorf("cannot connect without admin-secret")
}
modelTag := names.NewModelTag(config.UUID())
mongoInfo.Password = password
opts := mongo.DefaultDialOpts()
st, err := state.Open(modelTag, mongoInfo, opts, environs.NewStatePolicy())
if errors.IsUnauthorized(errors.Cause(err)) {
// We try for a while because we might succeed in
// connecting to mongo before the state has been
// initialized and the initial password set.
for a := redialStrategy.Start(); a.Next(); {
st, err = state.Open(modelTag, mongoInfo, opts, environs.NewStatePolicy())
if !errors.IsUnauthorized(errors.Cause(err)) {
break
}
}
if err != nil {
return nil, err
}
} else if err != nil {
return nil, err
}
if err := updateSecrets(environ, st); err != nil {
st.Close()
return nil, fmt.Errorf("unable to push secrets: %v", err)
}
return st, nil
}
示例2: NewConn
// NewConn returns a new Conn that uses the
// given environment. The environment must have already
// been bootstrapped.
func NewConn(environ environs.Environ) (*Conn, error) {
info, _, err := environ.StateInfo()
if err != nil {
return nil, err
}
password := environ.Config().AdminSecret()
if password == "" {
return nil, fmt.Errorf("cannot connect without admin-secret")
}
err = environs.CheckEnvironment(environ)
if err != nil {
return nil, err
}
info.Password = password
opts := mongo.DefaultDialOpts()
st, err := state.Open(info, opts, environs.NewStatePolicy())
if errors.IsUnauthorized(err) {
logger.Infof("authorization error while connecting to state server; retrying")
// We can't connect with the administrator password,;
// perhaps this was the first connection and the
// password has not been changed yet.
info.Password = utils.UserPasswordHash(password, utils.CompatSalt)
// We try for a while because we might succeed in
// connecting to mongo before the state has been
// initialized and the initial password set.
for a := redialStrategy.Start(); a.Next(); {
st, err = state.Open(info, opts, environs.NewStatePolicy())
if !errors.IsUnauthorized(err) {
break
}
}
if err != nil {
return nil, err
}
if err := st.SetAdminMongoPassword(password); err != nil {
return nil, err
}
} else if err != nil {
return nil, err
}
conn := &Conn{
Environ: environ,
State: st,
}
if err := conn.updateSecrets(); err != nil {
conn.Close()
return nil, fmt.Errorf("unable to push secrets: %v", err)
}
return conn, nil
}
示例3: TestInitialPassword
func (s *BootstrapSuite) TestInitialPassword(c *gc.C) {
machineConf, cmd, err := s.initBootstrapCommand(c, nil, "--env-config", s.envcfg, "--instance-id", string(s.instanceId))
c.Assert(err, gc.IsNil)
err = cmd.Run(nil)
c.Assert(err, gc.IsNil)
// Check that we cannot now connect to the state without a
// password.
info := &authentication.MongoInfo{
Info: mongo.Info{
Addrs: []string{gitjujutesting.MgoServer.Addr()},
CACert: testing.CACert,
},
}
testOpenState(c, info, errors.Unauthorizedf(""))
// Check we can log in to mongo as admin.
// TODO(dfc) does passing nil for the admin user name make your skin crawl ? mine too.
info.Tag, info.Password = nil, testPasswordHash()
st, err := state.Open(info, mongo.DefaultDialOpts(), environs.NewStatePolicy())
c.Assert(err, gc.IsNil)
// Reset password so the tests can continue to use the same server.
defer st.Close()
defer st.SetAdminMongoPassword("")
// Check that the admin user has been given an appropriate
// password
u, err := st.User("admin")
c.Assert(err, gc.IsNil)
c.Assert(u.PasswordValid(testPassword), gc.Equals, true)
// Check that the machine configuration has been given a new
// password and that we can connect to mongo as that machine
// and that the in-mongo password also verifies correctly.
machineConf1, err := agent.ReadConfig(agent.ConfigPath(machineConf.DataDir(), names.NewMachineTag("0")))
c.Assert(err, gc.IsNil)
stateinfo, ok := machineConf1.MongoInfo()
c.Assert(ok, jc.IsTrue)
st, err = state.Open(stateinfo, mongo.DialOpts{}, environs.NewStatePolicy())
c.Assert(err, gc.IsNil)
defer st.Close()
m, err := st.Machine("0")
c.Assert(err, gc.IsNil)
c.Assert(m.HasVote(), jc.IsTrue)
}
示例4: tryOpenState
func tryOpenState(modelTag names.ModelTag, info *mongo.MongoInfo) error {
st, err := state.Open(modelTag, info, mongo.DefaultDialOpts(), environs.NewStatePolicy())
if err == nil {
st.Close()
}
return err
}
示例5: fixEnvironment
// fixEnvironment undoes the work of invalidateEnvironment.
func (s *CommonProvisionerSuite) fixEnvironment(c *gc.C) error {
st, err := state.Open(s.MongoInfo(c), mongo.DefaultDialOpts(), state.Policy(nil))
c.Assert(err, gc.IsNil)
defer st.Close()
attrs := map[string]interface{}{"type": s.cfg.AllAttrs()["type"]}
return st.UpdateEnvironConfig(attrs, nil, nil)
}
示例6: TestSetConstraints
func (s *BootstrapSuite) TestSetConstraints(c *gc.C) {
tcons := constraints.Value{Mem: uint64p(2048), CpuCores: uint64p(2)}
_, cmd, err := s.initBootstrapCommand(c, nil,
"--env-config", s.b64yamlEnvcfg,
"--instance-id", string(s.instanceId),
"--constraints", tcons.String(),
)
c.Assert(err, jc.ErrorIsNil)
err = cmd.Run(nil)
c.Assert(err, jc.ErrorIsNil)
st, err := state.Open(testing.EnvironmentTag, &mongo.MongoInfo{
Info: mongo.Info{
Addrs: []string{gitjujutesting.MgoServer.Addr()},
CACert: testing.CACert,
},
Password: testPasswordHash(),
}, mongo.DefaultDialOpts(), environs.NewStatePolicy())
c.Assert(err, jc.ErrorIsNil)
defer st.Close()
cons, err := st.EnvironConstraints()
c.Assert(err, jc.ErrorIsNil)
c.Assert(cons, gc.DeepEquals, tcons)
machines, err := st.AllMachines()
c.Assert(err, jc.ErrorIsNil)
c.Assert(machines, gc.HasLen, 1)
cons, err = machines[0].Constraints()
c.Assert(err, jc.ErrorIsNil)
c.Assert(cons, gc.DeepEquals, tcons)
}
示例7: TestInvalidConfig
func (s *environSuite) TestInvalidConfig(c *gc.C) {
var oldType string
oldType = s.Environ.Config().AllAttrs()["type"].(string)
// Create an invalid config by taking the current config and
// tweaking the provider type.
info := s.MongoInfo(c)
opts := mongo.DefaultDialOpts()
st2, err := state.Open(info, opts, state.Policy(nil))
c.Assert(err, gc.IsNil)
defer st2.Close()
err = st2.UpdateEnvironConfig(map[string]interface{}{"type": "unknown"}, nil, nil)
c.Assert(err, gc.IsNil)
w := st2.WatchForEnvironConfigChanges()
defer stopWatcher(c, w)
done := make(chan environs.Environ)
go func() {
env, err := worker.WaitForEnviron(w, st2, nil)
c.Check(err, gc.IsNil)
done <- env
}()
// Wait for the loop to process the invalid configuratrion
<-worker.LoadedInvalid
st2.UpdateEnvironConfig(map[string]interface{}{
"type": oldType,
"secret": "environ_test",
}, nil, nil)
env := <-done
c.Assert(env, gc.NotNil)
c.Assert(env.Config().AllAttrs()["secret"], gc.Equals, "environ_test")
}
示例8: Run
func (c *MigrateCommand) Run(ctx *cmd.Context) (err error) {
defer func() {
if err != nil {
fmt.Fprintf(ctx.Stdout, "error stack:\n"+errors.ErrorStack(err))
}
}()
loggo.GetLogger("juju").SetLogLevel(loggo.DEBUG)
conf, err := agent.ReadConfig(agent.ConfigPath(c.dataDir, c.machineTag))
if err != nil {
return err
}
info, ok := conf.MongoInfo()
if !ok {
return errors.Errorf("no state info available")
}
st, err := state.Open(conf.Model(), info, mongo.DefaultDialOpts(), environs.NewStatePolicy())
if err != nil {
return err
}
defer st.Close()
if c.operation == "export" {
return c.exportModel(ctx, st)
}
return c.importModel(ctx, st)
}
示例9: Run
// Run implements cmd.Command.
func (c *dumpLogsCommand) Run(ctx *cmd.Context) error {
config := c.agentConfig.CurrentConfig()
info, ok := config.MongoInfo()
if !ok {
return errors.New("no database connection info available (is this a controller host?)")
}
st0, err := state.Open(config.Environment(), info, mongo.DefaultDialOpts(), environs.NewStatePolicy())
if err != nil {
return errors.Annotate(err, "failed to connect to database")
}
defer st0.Close()
envs, err := st0.AllEnvironments()
if err != nil {
return errors.Annotate(err, "failed to look up environments")
}
for _, env := range envs {
err := c.dumpLogsForEnv(ctx, st0, env.EnvironTag())
if err != nil {
return errors.Annotatef(err, "failed to dump logs for environment %s", env.UUID())
}
}
return nil
}
示例10: tryOpenState
func tryOpenState(info *mongo.MongoInfo) error {
st, err := state.Open(info, mongo.DialOpts{}, environs.NewStatePolicy())
if err == nil {
st.Close()
}
return err
}
示例11: invalidateEnvironment
// invalidateEnvironment alters the environment configuration
// so the Settings returned from the watcher will not pass
// validation.
func (s *CommonProvisionerSuite) invalidateEnvironment(c *gc.C) {
st, err := state.Open(s.MongoInfo(c), mongo.DefaultDialOpts(), state.Policy(nil))
c.Assert(err, gc.IsNil)
defer st.Close()
attrs := map[string]interface{}{"type": "unknown"}
err = st.UpdateEnvironConfig(attrs, nil, nil)
c.Assert(err, gc.IsNil)
}
示例12: openStateForUpgrade
func (s *UpgradeSuite) openStateForUpgrade() (*state.State, func(), error) {
mongoInfo := s.State.MongoConnectionInfo()
st, err := state.Open(s.State.ModelTag(), mongoInfo, mongo.DefaultDialOpts(), environs.NewStatePolicy())
if err != nil {
return nil, nil, err
}
return st, func() { st.Close() }, nil
}
示例13: TestEnvironmentChanges
func (s *environSuite) TestEnvironmentChanges(c *gc.C) {
originalConfig, err := s.State.EnvironConfig()
c.Assert(err, gc.IsNil)
logc := make(logChan, 1009)
c.Assert(loggo.RegisterWriter("testing", logc, loggo.WARNING), gc.IsNil)
defer loggo.RemoveWriter("testing")
obs, err := worker.NewEnvironObserver(s.State)
c.Assert(err, gc.IsNil)
env := obs.Environ()
c.Assert(env.Config().AllAttrs(), gc.DeepEquals, originalConfig.AllAttrs())
var oldType string
oldType = env.Config().AllAttrs()["type"].(string)
info := s.MongoInfo(c)
opts := mongo.DefaultDialOpts()
st2, err := state.Open(info, opts, state.Policy(nil))
defer st2.Close()
// Change to an invalid configuration and check
// that the observer's environment remains the same.
st2.UpdateEnvironConfig(map[string]interface{}{"type": "invalid"}, nil, nil)
st2.StartSync()
// Wait for the observer to register the invalid environment
timeout := time.After(coretesting.LongWait)
loop:
for {
select {
case msg := <-logc:
if strings.Contains(msg, "error creating Environ") {
break loop
}
case <-timeout:
c.Fatalf("timed out waiting to see broken environment")
}
}
// Check that the returned environ is still the same.
env = obs.Environ()
c.Assert(env.Config().AllAttrs(), gc.DeepEquals, originalConfig.AllAttrs())
// Change the environment back to a valid configuration
// with a different name and check that we see it.
st2.UpdateEnvironConfig(map[string]interface{}{"type": oldType, "name": "a-new-name"}, nil, nil)
st2.StartSync()
for a := coretesting.LongAttempt.Start(); a.Next(); {
env := obs.Environ()
if !a.HasNext() {
c.Fatalf("timed out waiting for new environ")
}
if env.Config().Name() == "a-new-name" {
break
}
}
}
示例14: AssertCanOpenState
func (s *AgentSuite) AssertCanOpenState(c *gc.C, tag names.Tag, dataDir string) {
config, err := agent.ReadConfig(agent.ConfigPath(dataDir, tag))
c.Assert(err, jc.ErrorIsNil)
info, ok := config.MongoInfo()
c.Assert(ok, jc.IsTrue)
st, err := state.Open(config.Model(), info, mongo.DefaultDialOpts(), environs.NewStatePolicy())
c.Assert(err, jc.ErrorIsNil)
st.Close()
}
示例15: assertCanOpenState
func (s *agentSuite) assertCanOpenState(c *gc.C, tag, dataDir string) {
config, err := agent.ReadConfig(agent.ConfigPath(dataDir, tag))
c.Assert(err, gc.IsNil)
info, ok := config.StateInfo()
c.Assert(ok, jc.IsTrue)
st, err := state.Open(info, mongo.DialOpts{}, environs.NewStatePolicy())
c.Assert(err, gc.IsNil)
st.Close()
}