本文整理汇总了Golang中github.com/juju/juju/state.State类的典型用法代码示例。如果您正苦于以下问题:Golang State类的具体用法?Golang State怎么用?Golang State使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了State类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: NewUserManagerAPI
func NewUserManagerAPI(
st *state.State,
resources facade.Resources,
authorizer facade.Authorizer,
) (*UserManagerAPI, error) {
if !authorizer.AuthClient() {
return nil, common.ErrPerm
}
// Since we know this is a user tag (because AuthClient is true),
// we just do the type assertion to the UserTag.
apiUser, _ := authorizer.GetAuthTag().(names.UserTag)
// Pretty much all of the user manager methods have special casing for admin
// users, so look once when we start and remember if the user is an admin.
isAdmin, err := authorizer.HasPermission(permission.SuperuserAccess, st.ControllerTag())
if err != nil {
return nil, errors.Trace(err)
}
return &UserManagerAPI{
state: st,
authorizer: authorizer,
check: common.NewBlockChecker(st),
apiUser: apiUser,
isAdmin: isAdmin,
}, nil
}
开发者ID:bac,项目名称:juju,代码行数:27,代码来源:usermanager.go
示例2: populateGUIArchive
// populateGUIArchive stores the uploaded Juju GUI archive in provider storage,
// updates the GUI metadata and set the current Juju GUI version.
func (c *BootstrapCommand) populateGUIArchive(st *state.State, env environs.Environ) error {
agentConfig := c.CurrentConfig()
dataDir := agentConfig.DataDir()
guistorage, err := st.GUIStorage()
if err != nil {
return errors.Trace(err)
}
defer guistorage.Close()
gui, err := agenttools.ReadGUIArchive(dataDir)
if err != nil {
return errors.Annotate(err, "cannot fetch GUI info")
}
f, err := os.Open(filepath.Join(agenttools.SharedGUIDir(dataDir), "gui.tar.bz2"))
if err != nil {
return errors.Annotate(err, "cannot read GUI archive")
}
defer f.Close()
if err := guistorage.Add(f, binarystorage.Metadata{
Version: gui.Version.String(),
Size: gui.Size,
SHA256: gui.SHA256,
}); err != nil {
return errors.Annotate(err, "cannot store GUI archive")
}
if err = st.GUISetVersion(gui.Version); err != nil {
return errors.Annotate(err, "cannot set current GUI version")
}
return nil
}
开发者ID:AlexisBruemmer,项目名称:juju,代码行数:31,代码来源:bootstrap.go
示例3: ImportModel
// ImportModel deserializes a model description from the bytes, transforms
// the model config based on information from the controller model, and then
// imports that as a new database model.
func ImportModel(st *state.State, bytes []byte) (*state.Model, *state.State, error) {
model, err := description.Deserialize(bytes)
if err != nil {
return nil, nil, errors.Trace(err)
}
controllerModel, err := st.ControllerModel()
if err != nil {
return nil, nil, errors.Trace(err)
}
controllerConfig, err := controllerModel.Config()
if err != nil {
return nil, nil, errors.Trace(err)
}
model.UpdateConfig(controllerValues(controllerConfig))
if err := updateConfigFromProvider(model, controllerConfig); err != nil {
return nil, nil, errors.Trace(err)
}
dbModel, dbState, err := st.Import(model)
if err != nil {
return nil, nil, errors.Trace(err)
}
return dbModel, dbState, nil
}
开发者ID:AlexisBruemmer,项目名称:juju,代码行数:31,代码来源:migration.go
示例4: assertDyingEnvironTransitionDyingToDead
func (s *ModelSuite) assertDyingEnvironTransitionDyingToDead(c *gc.C, st *state.State) {
// Add a service to prevent the model from transitioning directly to Dead.
// Add the service before getting the Model, otherwise we'll have to run
// the transaction twice, and hit the hook point too early.
svc := factory.NewFactory(st).MakeService(c, nil)
env, err := st.Model()
c.Assert(err, jc.ErrorIsNil)
// ProcessDyingModel is called by a worker after Destroy is called. To
// avoid a race, we jump the gun here and test immediately after the
// environement was set to dead.
defer state.SetAfterHooks(c, st, func() {
c.Assert(env.Refresh(), jc.ErrorIsNil)
c.Assert(env.Life(), gc.Equals, state.Dying)
err := svc.Destroy()
c.Assert(err, jc.ErrorIsNil)
c.Assert(st.ProcessDyingModel(), jc.ErrorIsNil)
c.Assert(env.Refresh(), jc.ErrorIsNil)
c.Assert(env.Life(), gc.Equals, state.Dead)
}).Check()
c.Assert(env.Destroy(), jc.ErrorIsNil)
}
开发者ID:makyo,项目名称:juju,代码行数:26,代码来源:model_test.go
示例5: addServiceUnits
// addServiceUnits adds a given number of units to a service.
func addServiceUnits(state *state.State, args params.AddServiceUnits) ([]*state.Unit, error) {
service, err := state.Service(args.ServiceName)
if err != nil {
return nil, err
}
if args.NumUnits < 1 {
return nil, fmt.Errorf("must add at least one unit")
}
// New API uses placement directives.
if len(args.Placement) > 0 {
return jjj.AddUnitsWithPlacement(state, service, args.NumUnits, args.Placement)
}
// Otherwise we use the older machine spec.
if args.NumUnits > 1 && args.ToMachineSpec != "" {
return nil, fmt.Errorf("cannot use NumUnits with ToMachineSpec")
}
if args.ToMachineSpec != "" && names.IsValidMachine(args.ToMachineSpec) {
_, err = state.Machine(args.ToMachineSpec)
if err != nil {
return nil, errors.Annotatef(err, `cannot add units for service "%v" to machine %v`, args.ServiceName, args.ToMachineSpec)
}
}
return jjj.AddUnits(state, service, args.NumUnits, args.ToMachineSpec)
}
开发者ID:mhilton,项目名称:juju,代码行数:28,代码来源:client.go
示例6: assertMachineStorageRefs
// assertMachineStorageRefs ensures that the specified machine's set of volume
// and filesystem references corresponds exactly to the volume and filesystem
// attachments that relate to the machine.
func assertMachineStorageRefs(c *gc.C, st *state.State, m names.MachineTag) {
machines, closer := state.GetRawCollection(st, state.MachinesC)
defer closer()
var doc struct {
Volumes []string `bson:"volumes,omitempty"`
Filesystems []string `bson:"filesystems,omitempty"`
}
err := machines.FindId(state.DocID(st, m.Id())).One(&doc)
c.Assert(err, jc.ErrorIsNil)
have := make(set.Tags)
for _, v := range doc.Volumes {
have.Add(names.NewVolumeTag(v))
}
for _, f := range doc.Filesystems {
have.Add(names.NewFilesystemTag(f))
}
expect := make(set.Tags)
volumeAttachments, err := st.MachineVolumeAttachments(m)
c.Assert(err, jc.ErrorIsNil)
for _, a := range volumeAttachments {
expect.Add(a.Volume())
}
filesystemAttachments, err := st.MachineFilesystemAttachments(m)
c.Assert(err, jc.ErrorIsNil)
for _, a := range filesystemAttachments {
expect.Add(a.Filesystem())
}
c.Assert(have, jc.DeepEquals, expect)
}
开发者ID:kat-co,项目名称:juju,代码行数:36,代码来源:storage_test.go
示例7: currentInfo
func currentInfo(st *state.State, db *mgo.Database) (*serverInfo, error) {
var doc stateServersDoc
err := db.C("stateServers").Find(bson.D{{"_id", "e"}}).One(&doc)
if err != nil {
return nil, fmt.Errorf("cannot get state server info: %v", err)
}
ms := make(map[string]*state.Machine)
var all []string
all = append(all, doc.MachineIds...)
all = append(all, doc.VotingMachineIds...)
for _, id := range all {
if _, ok := ms[id]; ok {
continue
}
m, err := st.Machine(id)
if err != nil {
return nil, fmt.Errorf("cannot get info on machine %s: %v", id, err)
}
ms[id] = m
}
return &serverInfo{
servers: &doc,
machines: ms,
}, nil
}
开发者ID:macressler,项目名称:misc,代码行数:25,代码来源:juju-stateservers.go
示例8: newPublicFacade
func (payloads) newPublicFacade(st *state.State, resources *common.Resources, authorizer common.Authorizer) (*server.PublicAPI, error) {
up, err := st.EnvPayloads()
if err != nil {
return nil, errors.Trace(err)
}
return server.NewPublicAPI(up), nil
}
开发者ID:imoapps,项目名称:juju,代码行数:7,代码来源:payload.go
示例9: exportModel
func (c *MigrateCommand) exportModel(ctx *cmd.Context, st *state.State) error {
ctx.Infof("\nexport %s", c.modelUUID)
// first make sure the uuid is good enough
tag := names.NewModelTag(c.modelUUID)
_, err := st.GetModel(tag)
if err != nil {
return errors.Trace(err)
}
modelState, err := st.ForModel(tag)
if err != nil {
return errors.Trace(err)
}
defer modelState.Close()
model, err := modelState.Export()
if err != nil {
return errors.Trace(err)
}
bytes, err := yaml.Marshal(model)
if err != nil {
return errors.Trace(err)
}
ctx.Stdout.Write(bytes)
return nil
}
开发者ID:howbazaar,项目名称:migration-test,代码行数:29,代码来源:main.go
示例10: createRemovalWatcher
func (s *MachineRemovalSuite) createRemovalWatcher(c *gc.C, st *state.State) (
state.NotifyWatcher, testing.NotifyWatcherC,
) {
w := st.WatchMachineRemovals()
s.AddCleanup(func(c *gc.C) { workertest.CleanKill(c, w) })
return w, testing.NewNotifyWatcherC(c, st, w)
}
开发者ID:bac,项目名称:juju,代码行数:7,代码来源:machineremovals_test.go
示例11: newHookContextFacade
func (payloads) newHookContextFacade(st *state.State, unit *state.Unit) (interface{}, error) {
up, err := st.UnitPayloads(unit)
if err != nil {
return nil, errors.Trace(err)
}
return internalserver.NewUnitFacade(up), nil
}
开发者ID:imoapps,项目名称:juju,代码行数:7,代码来源:payload.go
示例12: getAllUnitNames
// getAllUnitNames returns a sequence of valid Unit objects from state. If any
// of the service names or unit names are not found, an error is returned.
func getAllUnitNames(st *state.State, units, services []string) (result []*state.Unit, err error) {
unitsSet := set.NewStrings(units...)
for _, name := range services {
service, err := st.Service(name)
if err != nil {
return nil, err
}
units, err := service.AllUnits()
if err != nil {
return nil, err
}
for _, unit := range units {
unitsSet.Add(unit.Name())
}
}
for _, unitName := range unitsSet.Values() {
unit, err := st.Unit(unitName)
if err != nil {
return nil, err
}
// We only operate on units that have an assigned machine.
if _, err := unit.AssignedMachineId(); err != nil {
return nil, err
}
result = append(result, unit)
}
return result, nil
}
开发者ID:imoapps,项目名称:juju,代码行数:30,代码来源:run.go
示例13: createStatusWatcher
func (s *MigrationSuite) createStatusWatcher(c *gc.C, st *state.State) (
state.NotifyWatcher, statetesting.NotifyWatcherC,
) {
w := st.WatchMigrationStatus()
s.AddCleanup(func(c *gc.C) { statetesting.AssertStop(c, w) })
return w, statetesting.NewNotifyWatcherC(c, st, w)
}
开发者ID:bac,项目名称:juju,代码行数:7,代码来源:modelmigration_test.go
示例14: handleResponse
func handleResponse(mm *state.MetricsManager, st *state.State, response wireformat.Response) {
for _, envResp := range response.EnvResponses {
err := st.SetMetricBatchesSent(envResp.AcknowledgedBatches)
if err != nil {
logger.Errorf("failed to set sent on metrics %v", err)
}
for unitName, status := range envResp.UnitStatuses {
unit, err := st.Unit(unitName)
if err != nil {
logger.Errorf("failed to retrieve unit %q: %v", unitName, err)
continue
}
err = unit.SetMeterStatus(status.Status, status.Info)
if err != nil {
logger.Errorf("failed to set unit %q meter status to %v: %v", unitName, status, err)
}
}
}
if response.NewGracePeriod > 0 {
err := mm.SetGracePeriod(response.NewGracePeriod)
if err != nil {
logger.Errorf("failed to set new grace period %v", err)
}
}
}
开发者ID:exekias,项目名称:juju,代码行数:25,代码来源:metricsender.go
示例15: processGet
// processGet handles a tools GET request.
func (h *toolsDownloadHandler) processGet(r *http.Request, st *state.State) ([]byte, error) {
version, err := version.ParseBinary(r.URL.Query().Get(":version"))
if err != nil {
return nil, errors.Annotate(err, "error parsing version")
}
storage, err := st.ToolsStorage()
if err != nil {
return nil, errors.Annotate(err, "error getting tools storage")
}
defer storage.Close()
_, reader, err := storage.Open(version.String())
if errors.IsNotFound(err) {
// Tools could not be found in tools storage,
// so look for them in simplestreams, fetch
// them and cache in tools storage.
logger.Infof("%v tools not found locally, fetching", version)
reader, err = h.fetchAndCacheTools(version, storage, st)
if err != nil {
err = errors.Annotate(err, "error fetching tools")
}
}
if err != nil {
return nil, err
}
defer reader.Close()
data, err := ioutil.ReadAll(reader)
if err != nil {
return nil, errors.Annotate(err, "failed to read tools tarball")
}
return data, nil
}
开发者ID:bac,项目名称:juju,代码行数:32,代码来源:tools.go
示例16: loadImage
// loadImage loads an os image from the blobstore,
// downloading and caching it if necessary.
func (h *imagesDownloadHandler) loadImage(st *state.State, envuuid, kind, series, arch string) (
*imagestorage.Metadata, io.ReadCloser, error,
) {
// We want to ensure that if an image needs to be downloaded and cached,
// this only happens once.
imageIdent := fmt.Sprintf("image-%s-%s-%s-%s", envuuid, kind, series, arch)
lockDir := filepath.Join(h.dataDir, "locks")
lock, err := fslock.NewLock(lockDir, imageIdent, fslock.Defaults())
if err != nil {
return nil, nil, errors.Trace(err)
}
lock.Lock("fetch and cache image " + imageIdent)
defer lock.Unlock()
storage := st.ImageStorage()
metadata, imageReader, err := storage.Image(kind, series, arch)
// Not in storage, so go fetch it.
if errors.IsNotFound(err) {
if err := h.fetchAndCacheLxcImage(storage, envuuid, series, arch); err != nil {
return nil, nil, errors.Annotate(err, "error fetching and caching image")
}
err = networkOperationWitDefaultRetries(func() error {
metadata, imageReader, err = storage.Image(string(instance.LXC), series, arch)
return err
}, "streaming os image from blobstore")()
}
if err != nil {
return nil, nil, errors.Trace(err)
}
return metadata, imageReader, nil
}
开发者ID:imoapps,项目名称:juju,代码行数:32,代码来源:images.go
示例17: AddSubnetsWithTemplate
// AddSubnetsWithTemplate adds numSubnets subnets, using the given
// infoTemplate. Any string field in the infoTemplate can be specified
// as a text/template string containing {{.}}, which is the current
// index of the subnet-to-add (between 0 and numSubnets-1).
//
// Example:
//
// AddSubnetsWithTemplate(c, st, 2, state.SubnetInfo{
// CIDR: "10.10.{{.}}.0/24",
// ProviderId: "subnet-{{.}}",
// SpaceName: "space1",
// AvailabilityZone: "zone-{{.}}",
// AllocatableIPLow: "{{if (gt . 0)}}10.10.{{.}}.5{{end}}",
// AllocatableIPHigh: "{{if (gt . 0)}}10.10.{{.}}.254{{end}}",
// VLANTag: 42,
// })
//
// This is equivalent to the following calls:
//
// _, err := st.AddSubnet(state.SubnetInfo{
// CIDR: "10.10.0.0/24",
// ProviderId: "subnet-0",
// SpaceName: "space1",
// AvailabilityZone: "zone-0",
// VLANTag: 42,
// })
// c.Assert(err, jc.ErrorIsNil)
// _, err = st.AddSubnet(state.SubnetInfo{
// CIDR: "10.10.1.0/24",
// ProviderId: "subnet-1",
// SpaceName: "space1",
// AvailabilityZone: "zone-1",
// AllocatableIPLow: "10.10.1.5",
// AllocatableIPHigh: "10.10.1.254",
// VLANTag: 42,
// })
func AddSubnetsWithTemplate(c *gc.C, st *state.State, numSubnets uint, infoTemplate state.SubnetInfo) {
for subnetIndex := 0; subnetIndex < int(numSubnets); subnetIndex++ {
info := infoTemplate // make a copy each time.
// permute replaces the contents of *s with the result of interpreting
// *s as a template.
permute := func(s string) string {
t, err := template.New("").Parse(s)
c.Assert(err, jc.ErrorIsNil)
var buf bytes.Buffer
err = t.Execute(&buf, subnetIndex)
c.Assert(err, jc.ErrorIsNil)
return buf.String()
}
info.ProviderId = network.Id(permute(string(info.ProviderId)))
info.CIDR = permute(info.CIDR)
info.AllocatableIPHigh = permute(info.AllocatableIPHigh)
info.AllocatableIPLow = permute(info.AllocatableIPLow)
info.AvailabilityZone = permute(info.AvailabilityZone)
info.SpaceName = permute(info.SpaceName)
_, err := st.AddSubnet(info)
c.Assert(err, jc.ErrorIsNil)
}
}
开发者ID:AlexisBruemmer,项目名称:juju,代码行数:63,代码来源:utils.go
示例18: checkCreds
// checkCreds validates the entities credentials in the current environment.
// If the entity is a user, and lookForEnvUser is true, an env user must exist
// for the environment. In the case of a user logging in to the server, but
// not an environment, there is no env user needed. While we have the env
// user, if we do have it, update the last login time.
func checkCreds(st *state.State, req params.LoginRequest, lookForEnvUser bool) (state.Entity, *time.Time, error) {
tag, err := names.ParseTag(req.AuthTag)
if err != nil {
return nil, nil, err
}
entity, err := st.FindEntity(tag)
if errors.IsNotFound(err) {
// We return the same error when an entity does not exist as for a bad
// password, so that we don't allow unauthenticated users to find
// information about existing entities.
logger.Debugf("entity %q not found", tag)
return nil, nil, common.ErrBadCreds
}
if err != nil {
return nil, nil, errors.Trace(err)
}
authenticator, err := authentication.FindEntityAuthenticator(entity)
if err != nil {
return nil, nil, err
}
if err = authenticator.Authenticate(entity, req.Credentials, req.Nonce); err != nil {
logger.Debugf("bad credentials")
return nil, nil, err
}
// For user logins, update the last login time.
// NOTE: this code path is only for local users. When we support remote
// user logins with bearer tokens, we will need to make sure that we also
// update the last connection times for the environment users there.
var lastLogin *time.Time
if user, ok := entity.(*state.User); ok {
userLastLogin, err := user.LastLogin()
if err != nil && !state.IsNeverLoggedInError(err) {
return nil, nil, errors.Trace(err)
}
if lookForEnvUser {
envUser, err := st.EnvironmentUser(user.UserTag())
if err != nil {
return nil, nil, errors.Wrap(err, common.ErrBadCreds)
}
// The last connection for the environment takes precedence over
// the local user last login time.
userLastLogin, err = envUser.LastConnection()
if err != nil && !state.IsNeverConnectedError(err) {
return nil, nil, errors.Trace(err)
}
envUser.UpdateLastConnection()
}
// Only update the user's last login time if it is a successful
// login, meaning that if we are logging into an environment, make
// sure that there is an environment user in that environment for
// this user.
user.UpdateLastLogin()
lastLogin = &userLastLogin
}
return entity, lastLogin, nil
}
开发者ID:kakamessi99,项目名称:juju,代码行数:65,代码来源:admin.go
示例19: newHookContextFacade
func (r resources) newHookContextFacade(st *corestate.State, unit *corestate.Unit) (interface{}, error) {
res, err := st.Resources()
if err != nil {
return nil, errors.Trace(err)
}
return internalserver.NewUnitFacade(&resourcesUnitDataStore{res, unit}), nil
}
开发者ID:AlexisBruemmer,项目名称:juju,代码行数:7,代码来源:resource.go
示例20: modelIsImporting
func modelIsImporting(st *state.State) (bool, error) {
model, err := st.Model()
if err != nil {
return false, errors.Trace(err)
}
return model.MigrationMode() == state.MigrationModeImporting, nil
}
开发者ID:bac,项目名称:juju,代码行数:7,代码来源:charms.go
注:本文中的github.com/juju/juju/state.State类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论