id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
157,000
juju/juju
apiserver/authentication/interactions.go
Expire
func (m *Interactions) Expire(t time.Time) { m.mu.Lock() defer m.mu.Unlock() for id, item := range m.items { if item.done || item.expiry.After(t) { continue } delete(m.items, id) close(item.c) } }
go
func (m *Interactions) Expire(t time.Time) { m.mu.Lock() defer m.mu.Unlock() for id, item := range m.items { if item.done || item.expiry.After(t) { continue } delete(m.items, id) close(item.c) } }
[ "func", "(", "m", "*", "Interactions", ")", "Expire", "(", "t", "time", ".", "Time", ")", "{", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unlock", "(", ")", "\n", "for", "id", ",", "item", ":=", "range", "m", ".", "items", "{", "if", "item", ".", "done", "||", "item", ".", "expiry", ".", "After", "(", "t", ")", "{", "continue", "\n", "}", "\n", "delete", "(", "m", ".", "items", ",", "id", ")", "\n", "close", "(", "item", ".", "c", ")", "\n", "}", "\n", "}" ]
// Expire removes any interactions that were due to expire by the // specified time.
[ "Expire", "removes", "any", "interactions", "that", "were", "due", "to", "expire", "by", "the", "specified", "time", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/authentication/interactions.go#L126-L136
157,001
juju/juju
provider/cloudsigma/client.go
isMyController
func (c environClient) isMyController(s gosigma.Server) bool { if v, ok := s.Get(jujuMetaInstance); ok && v == jujuMetaInstanceController { return c.isMyEnvironment(s) } return false }
go
func (c environClient) isMyController(s gosigma.Server) bool { if v, ok := s.Get(jujuMetaInstance); ok && v == jujuMetaInstanceController { return c.isMyEnvironment(s) } return false }
[ "func", "(", "c", "environClient", ")", "isMyController", "(", "s", "gosigma", ".", "Server", ")", "bool", "{", "if", "v", ",", "ok", ":=", "s", ".", "Get", "(", "jujuMetaInstance", ")", ";", "ok", "&&", "v", "==", "jujuMetaInstanceController", "{", "return", "c", ".", "isMyEnvironment", "(", "s", ")", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isMyController is used to filter servers in the CloudSigma account
[ "isMyController", "is", "used", "to", "filter", "servers", "in", "the", "CloudSigma", "account" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/cloudsigma/client.go#L82-L87
157,002
juju/juju
provider/cloudsigma/client.go
instances
func (c *environClient) instances() ([]gosigma.Server, error) { return c.conn.ServersFiltered(gosigma.RequestDetail, c.isMyServer) }
go
func (c *environClient) instances() ([]gosigma.Server, error) { return c.conn.ServersFiltered(gosigma.RequestDetail, c.isMyServer) }
[ "func", "(", "c", "*", "environClient", ")", "instances", "(", ")", "(", "[", "]", "gosigma", ".", "Server", ",", "error", ")", "{", "return", "c", ".", "conn", ".", "ServersFiltered", "(", "gosigma", ".", "RequestDetail", ",", "c", ".", "isMyServer", ")", "\n", "}" ]
// instances returns a list of CloudSigma servers for this environment
[ "instances", "returns", "a", "list", "of", "CloudSigma", "servers", "for", "this", "environment" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/cloudsigma/client.go#L90-L92
157,003
juju/juju
provider/cloudsigma/client.go
instanceMap
func (c *environClient) instanceMap() (map[string]gosigma.Server, error) { servers, err := c.conn.ServersFiltered(gosigma.RequestDetail, c.isMyServer) if err != nil { return nil, errors.Trace(err) } m := make(map[string]gosigma.Server, len(servers)) for _, s := range servers { m[s.UUID()] = s } return m, nil }
go
func (c *environClient) instanceMap() (map[string]gosigma.Server, error) { servers, err := c.conn.ServersFiltered(gosigma.RequestDetail, c.isMyServer) if err != nil { return nil, errors.Trace(err) } m := make(map[string]gosigma.Server, len(servers)) for _, s := range servers { m[s.UUID()] = s } return m, nil }
[ "func", "(", "c", "*", "environClient", ")", "instanceMap", "(", ")", "(", "map", "[", "string", "]", "gosigma", ".", "Server", ",", "error", ")", "{", "servers", ",", "err", ":=", "c", ".", "conn", ".", "ServersFiltered", "(", "gosigma", ".", "RequestDetail", ",", "c", ".", "isMyServer", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "m", ":=", "make", "(", "map", "[", "string", "]", "gosigma", ".", "Server", ",", "len", "(", "servers", ")", ")", "\n", "for", "_", ",", "s", ":=", "range", "servers", "{", "m", "[", "s", ".", "UUID", "(", ")", "]", "=", "s", "\n", "}", "\n\n", "return", "m", ",", "nil", "\n", "}" ]
// instanceMap of server ids to servers at CloudSigma account
[ "instanceMap", "of", "server", "ids", "to", "servers", "at", "CloudSigma", "account" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/cloudsigma/client.go#L95-L107
157,004
juju/juju
provider/cloudsigma/client.go
getControllerIds
func (c *environClient) getControllerIds() (ids []instance.Id, err error) { logger.Tracef("query state...") servers, err := c.conn.ServersFiltered(gosigma.RequestDetail, c.isMyController) if err != nil { return []instance.Id{}, errors.Trace(err) } if len(servers) == 0 { return []instance.Id{}, environs.ErrNotBootstrapped } ids = make([]instance.Id, len(servers)) for i, server := range servers { logger.Tracef("controller id: %s", server.UUID()) ids[i] = instance.Id(server.UUID()) } return ids, nil }
go
func (c *environClient) getControllerIds() (ids []instance.Id, err error) { logger.Tracef("query state...") servers, err := c.conn.ServersFiltered(gosigma.RequestDetail, c.isMyController) if err != nil { return []instance.Id{}, errors.Trace(err) } if len(servers) == 0 { return []instance.Id{}, environs.ErrNotBootstrapped } ids = make([]instance.Id, len(servers)) for i, server := range servers { logger.Tracef("controller id: %s", server.UUID()) ids[i] = instance.Id(server.UUID()) } return ids, nil }
[ "func", "(", "c", "*", "environClient", ")", "getControllerIds", "(", ")", "(", "ids", "[", "]", "instance", ".", "Id", ",", "err", "error", ")", "{", "logger", ".", "Tracef", "(", "\"", "\"", ")", "\n\n", "servers", ",", "err", ":=", "c", ".", "conn", ".", "ServersFiltered", "(", "gosigma", ".", "RequestDetail", ",", "c", ".", "isMyController", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "instance", ".", "Id", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "len", "(", "servers", ")", "==", "0", "{", "return", "[", "]", "instance", ".", "Id", "{", "}", ",", "environs", ".", "ErrNotBootstrapped", "\n", "}", "\n\n", "ids", "=", "make", "(", "[", "]", "instance", ".", "Id", ",", "len", "(", "servers", ")", ")", "\n\n", "for", "i", ",", "server", ":=", "range", "servers", "{", "logger", ".", "Tracef", "(", "\"", "\"", ",", "server", ".", "UUID", "(", ")", ")", "\n", "ids", "[", "i", "]", "=", "instance", ".", "Id", "(", "server", ".", "UUID", "(", ")", ")", "\n", "}", "\n\n", "return", "ids", ",", "nil", "\n", "}" ]
//getControllerIds get list of ids for all controller instances
[ "getControllerIds", "get", "list", "of", "ids", "for", "all", "controller", "instances" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/cloudsigma/client.go#L110-L130
157,005
juju/juju
provider/cloudsigma/client.go
stopInstance
func (c *environClient) stopInstance(id instance.Id) error { uuid := string(id) if uuid == "" { return errors.New("invalid instance id") } s, err := c.conn.Server(uuid) if err != nil { return errors.Trace(err) } err = s.StopWait() logger.Tracef("environClient.StopInstance - stop server, %q = %v", uuid, err) err = s.Remove(gosigma.RecurseAllDrives) logger.Tracef("environClient.StopInstance - remove server, %q = %v", uuid, err) return nil }
go
func (c *environClient) stopInstance(id instance.Id) error { uuid := string(id) if uuid == "" { return errors.New("invalid instance id") } s, err := c.conn.Server(uuid) if err != nil { return errors.Trace(err) } err = s.StopWait() logger.Tracef("environClient.StopInstance - stop server, %q = %v", uuid, err) err = s.Remove(gosigma.RecurseAllDrives) logger.Tracef("environClient.StopInstance - remove server, %q = %v", uuid, err) return nil }
[ "func", "(", "c", "*", "environClient", ")", "stopInstance", "(", "id", "instance", ".", "Id", ")", "error", "{", "uuid", ":=", "string", "(", "id", ")", "\n", "if", "uuid", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "s", ",", "err", ":=", "c", ".", "conn", ".", "Server", "(", "uuid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "err", "=", "s", ".", "StopWait", "(", ")", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "uuid", ",", "err", ")", "\n\n", "err", "=", "s", ".", "Remove", "(", "gosigma", ".", "RecurseAllDrives", ")", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "uuid", ",", "err", ")", "\n\n", "return", "nil", "\n", "}" ]
//stopInstance stops the CloudSigma server corresponding to the given instance ID.
[ "stopInstance", "stops", "the", "CloudSigma", "server", "corresponding", "to", "the", "given", "instance", "ID", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/cloudsigma/client.go#L133-L151
157,006
juju/juju
state/raftlease/target.go
leaseHolderDocId
func leaseHolderDocId(namespace, modelUUID, lease string) string { return fmt.Sprintf("%s:%s#%s#", modelUUID, namespace, lease) }
go
func leaseHolderDocId(namespace, modelUUID, lease string) string { return fmt.Sprintf("%s:%s#%s#", modelUUID, namespace, lease) }
[ "func", "leaseHolderDocId", "(", "namespace", ",", "modelUUID", ",", "lease", "string", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "modelUUID", ",", "namespace", ",", "lease", ")", "\n", "}" ]
// leaseHolderDocId returns the _id for the document holding details of the supplied // namespace and lease.
[ "leaseHolderDocId", "returns", "the", "_id", "for", "the", "document", "holding", "details", "of", "the", "supplied", "namespace", "and", "lease", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/raftlease/target.go#L49-L51
157,007
juju/juju
state/raftlease/target.go
newLeaseHolderDoc
func newLeaseHolderDoc(namespace, modelUUID, name, holder string) (*leaseHolderDoc, error) { doc := &leaseHolderDoc{ Id: leaseHolderDocId(namespace, modelUUID, name), Namespace: namespace, ModelUUID: modelUUID, Lease: name, Holder: holder, } if err := doc.validate(); err != nil { return nil, errors.Trace(err) } return doc, nil }
go
func newLeaseHolderDoc(namespace, modelUUID, name, holder string) (*leaseHolderDoc, error) { doc := &leaseHolderDoc{ Id: leaseHolderDocId(namespace, modelUUID, name), Namespace: namespace, ModelUUID: modelUUID, Lease: name, Holder: holder, } if err := doc.validate(); err != nil { return nil, errors.Trace(err) } return doc, nil }
[ "func", "newLeaseHolderDoc", "(", "namespace", ",", "modelUUID", ",", "name", ",", "holder", "string", ")", "(", "*", "leaseHolderDoc", ",", "error", ")", "{", "doc", ":=", "&", "leaseHolderDoc", "{", "Id", ":", "leaseHolderDocId", "(", "namespace", ",", "modelUUID", ",", "name", ")", ",", "Namespace", ":", "namespace", ",", "ModelUUID", ":", "modelUUID", ",", "Lease", ":", "name", ",", "Holder", ":", "holder", ",", "}", "\n", "if", "err", ":=", "doc", ".", "validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "doc", ",", "nil", "\n", "}" ]
// newLeaseHolderDoc returns a valid lease document encoding the supplied lease and // entry in the supplied namespace, or an error.
[ "newLeaseHolderDoc", "returns", "a", "valid", "lease", "document", "encoding", "the", "supplied", "lease", "and", "entry", "in", "the", "supplied", "namespace", "or", "an", "error", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/raftlease/target.go#L66-L78
157,008
juju/juju
state/raftlease/target.go
NewNotifyTarget
func NewNotifyTarget(mongo Mongo, collection string, logDest io.Writer, errorLogger Logger) raftlease.NotifyTarget { return &notifyTarget{ mongo: mongo, collection: collection, logger: log.New(logDest, "", log.LstdFlags|log.Lmicroseconds|log.LUTC), errorLogger: errorLogger, } }
go
func NewNotifyTarget(mongo Mongo, collection string, logDest io.Writer, errorLogger Logger) raftlease.NotifyTarget { return &notifyTarget{ mongo: mongo, collection: collection, logger: log.New(logDest, "", log.LstdFlags|log.Lmicroseconds|log.LUTC), errorLogger: errorLogger, } }
[ "func", "NewNotifyTarget", "(", "mongo", "Mongo", ",", "collection", "string", ",", "logDest", "io", ".", "Writer", ",", "errorLogger", "Logger", ")", "raftlease", ".", "NotifyTarget", "{", "return", "&", "notifyTarget", "{", "mongo", ":", "mongo", ",", "collection", ":", "collection", ",", "logger", ":", "log", ".", "New", "(", "logDest", ",", "\"", "\"", ",", "log", ".", "LstdFlags", "|", "log", ".", "Lmicroseconds", "|", "log", ".", "LUTC", ")", ",", "errorLogger", ":", "errorLogger", ",", "}", "\n", "}" ]
// NewNotifyTarget returns something that can be used to report lease // changes.
[ "NewNotifyTarget", "returns", "something", "that", "can", "be", "used", "to", "report", "lease", "changes", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/raftlease/target.go#L98-L105
157,009
juju/juju
state/raftlease/target.go
Claimed
func (t *notifyTarget) Claimed(key lease.Key, holder string) { docId := leaseHolderDocId(key.Namespace, key.ModelUUID, key.Lease) t.log("claimed %q for %q", docId, holder) _, err := applyClaimed(t.mongo, t.collection, docId, key, holder) if err != nil { t.errorLogger.Errorf("couldn't claim lease %q for %q in db: %s", docId, holder, err.Error()) t.log("couldn't claim lease %q for %q in db: %s", docId, holder, err.Error()) return } }
go
func (t *notifyTarget) Claimed(key lease.Key, holder string) { docId := leaseHolderDocId(key.Namespace, key.ModelUUID, key.Lease) t.log("claimed %q for %q", docId, holder) _, err := applyClaimed(t.mongo, t.collection, docId, key, holder) if err != nil { t.errorLogger.Errorf("couldn't claim lease %q for %q in db: %s", docId, holder, err.Error()) t.log("couldn't claim lease %q for %q in db: %s", docId, holder, err.Error()) return } }
[ "func", "(", "t", "*", "notifyTarget", ")", "Claimed", "(", "key", "lease", ".", "Key", ",", "holder", "string", ")", "{", "docId", ":=", "leaseHolderDocId", "(", "key", ".", "Namespace", ",", "key", ".", "ModelUUID", ",", "key", ".", "Lease", ")", "\n", "t", ".", "log", "(", "\"", "\"", ",", "docId", ",", "holder", ")", "\n", "_", ",", "err", ":=", "applyClaimed", "(", "t", ".", "mongo", ",", "t", ".", "collection", ",", "docId", ",", "key", ",", "holder", ")", "\n", "if", "err", "!=", "nil", "{", "t", ".", "errorLogger", ".", "Errorf", "(", "\"", "\"", ",", "docId", ",", "holder", ",", "err", ".", "Error", "(", ")", ")", "\n", "t", ".", "log", "(", "\"", "\"", ",", "docId", ",", "holder", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n", "}" ]
// Claimed is part of raftlease.NotifyTarget.
[ "Claimed", "is", "part", "of", "raftlease", ".", "NotifyTarget", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/raftlease/target.go#L181-L190
157,010
juju/juju
state/raftlease/target.go
Expired
func (t *notifyTarget) Expired(key lease.Key) { coll, closer := t.mongo.GetCollection(t.collection) defer closer() docId := leaseHolderDocId(key.Namespace, key.ModelUUID, key.Lease) t.log("expired %q", docId) err := t.mongo.RunTransaction(func(_ int) ([]txn.Op, error) { existingDoc, err := getRecord(coll, docId) if err == mgo.ErrNotFound { return nil, jujutxn.ErrNoOperations } if err != nil { return nil, errors.Trace(err) } return []txn.Op{{ C: t.collection, Id: docId, Assert: bson.M{ fieldHolder: existingDoc.Holder, }, Remove: true, }}, nil }) if err != nil { t.errorLogger.Errorf("couldn't expire lease %q in db: %s", docId, err.Error()) t.log("couldn't expire lease %q in db: %s", docId, err.Error()) return } }
go
func (t *notifyTarget) Expired(key lease.Key) { coll, closer := t.mongo.GetCollection(t.collection) defer closer() docId := leaseHolderDocId(key.Namespace, key.ModelUUID, key.Lease) t.log("expired %q", docId) err := t.mongo.RunTransaction(func(_ int) ([]txn.Op, error) { existingDoc, err := getRecord(coll, docId) if err == mgo.ErrNotFound { return nil, jujutxn.ErrNoOperations } if err != nil { return nil, errors.Trace(err) } return []txn.Op{{ C: t.collection, Id: docId, Assert: bson.M{ fieldHolder: existingDoc.Holder, }, Remove: true, }}, nil }) if err != nil { t.errorLogger.Errorf("couldn't expire lease %q in db: %s", docId, err.Error()) t.log("couldn't expire lease %q in db: %s", docId, err.Error()) return } }
[ "func", "(", "t", "*", "notifyTarget", ")", "Expired", "(", "key", "lease", ".", "Key", ")", "{", "coll", ",", "closer", ":=", "t", ".", "mongo", ".", "GetCollection", "(", "t", ".", "collection", ")", "\n", "defer", "closer", "(", ")", "\n", "docId", ":=", "leaseHolderDocId", "(", "key", ".", "Namespace", ",", "key", ".", "ModelUUID", ",", "key", ".", "Lease", ")", "\n", "t", ".", "log", "(", "\"", "\"", ",", "docId", ")", "\n", "err", ":=", "t", ".", "mongo", ".", "RunTransaction", "(", "func", "(", "_", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "existingDoc", ",", "err", ":=", "getRecord", "(", "coll", ",", "docId", ")", "\n", "if", "err", "==", "mgo", ".", "ErrNotFound", "{", "return", "nil", ",", "jujutxn", ".", "ErrNoOperations", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "[", "]", "txn", ".", "Op", "{", "{", "C", ":", "t", ".", "collection", ",", "Id", ":", "docId", ",", "Assert", ":", "bson", ".", "M", "{", "fieldHolder", ":", "existingDoc", ".", "Holder", ",", "}", ",", "Remove", ":", "true", ",", "}", "}", ",", "nil", "\n", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "t", ".", "errorLogger", ".", "Errorf", "(", "\"", "\"", ",", "docId", ",", "err", ".", "Error", "(", ")", ")", "\n", "t", ".", "log", "(", "\"", "\"", ",", "docId", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n", "}" ]
// Expired is part of raftlease.NotifyTarget.
[ "Expired", "is", "part", "of", "raftlease", ".", "NotifyTarget", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/raftlease/target.go#L193-L221
157,011
juju/juju
state/raftlease/target.go
MakeTrapdoorFunc
func MakeTrapdoorFunc(mongo Mongo, collection string) raftlease.TrapdoorFunc { return func(key lease.Key, holder string) lease.Trapdoor { return func(attempt int, out interface{}) error { outPtr, ok := out.(*[]txn.Op) if !ok { return errors.NotValidf("expected *[]txn.Op; %T", out) } if attempt != 0 { // If the assertion failed it may be because a claim // notify failed in the past due to the DB not being // available. Sync the lease holder - this is safe to // do because raft is the arbiter of who really holds // the lease, and we check that the lease is held in // buildTxnWithLeadership each time before collecting // the assertion ops. docId := leaseHolderDocId(key.Namespace, key.ModelUUID, key.Lease) writeNeeded, err := applyClaimed(mongo, collection, docId, key, holder) if err != nil { return errors.Trace(err) } if writeNeeded { logger.Infof("trapdoor claimed lease %q for %q", docId, holder) } } *outPtr = []txn.Op{{ C: collection, Id: leaseHolderDocId( key.Namespace, key.ModelUUID, key.Lease, ), Assert: bson.M{ fieldHolder: holder, }, }} return nil } } }
go
func MakeTrapdoorFunc(mongo Mongo, collection string) raftlease.TrapdoorFunc { return func(key lease.Key, holder string) lease.Trapdoor { return func(attempt int, out interface{}) error { outPtr, ok := out.(*[]txn.Op) if !ok { return errors.NotValidf("expected *[]txn.Op; %T", out) } if attempt != 0 { // If the assertion failed it may be because a claim // notify failed in the past due to the DB not being // available. Sync the lease holder - this is safe to // do because raft is the arbiter of who really holds // the lease, and we check that the lease is held in // buildTxnWithLeadership each time before collecting // the assertion ops. docId := leaseHolderDocId(key.Namespace, key.ModelUUID, key.Lease) writeNeeded, err := applyClaimed(mongo, collection, docId, key, holder) if err != nil { return errors.Trace(err) } if writeNeeded { logger.Infof("trapdoor claimed lease %q for %q", docId, holder) } } *outPtr = []txn.Op{{ C: collection, Id: leaseHolderDocId( key.Namespace, key.ModelUUID, key.Lease, ), Assert: bson.M{ fieldHolder: holder, }, }} return nil } } }
[ "func", "MakeTrapdoorFunc", "(", "mongo", "Mongo", ",", "collection", "string", ")", "raftlease", ".", "TrapdoorFunc", "{", "return", "func", "(", "key", "lease", ".", "Key", ",", "holder", "string", ")", "lease", ".", "Trapdoor", "{", "return", "func", "(", "attempt", "int", ",", "out", "interface", "{", "}", ")", "error", "{", "outPtr", ",", "ok", ":=", "out", ".", "(", "*", "[", "]", "txn", ".", "Op", ")", "\n", "if", "!", "ok", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "out", ")", "\n", "}", "\n", "if", "attempt", "!=", "0", "{", "// If the assertion failed it may be because a claim", "// notify failed in the past due to the DB not being", "// available. Sync the lease holder - this is safe to", "// do because raft is the arbiter of who really holds", "// the lease, and we check that the lease is held in", "// buildTxnWithLeadership each time before collecting", "// the assertion ops.", "docId", ":=", "leaseHolderDocId", "(", "key", ".", "Namespace", ",", "key", ".", "ModelUUID", ",", "key", ".", "Lease", ")", "\n", "writeNeeded", ",", "err", ":=", "applyClaimed", "(", "mongo", ",", "collection", ",", "docId", ",", "key", ",", "holder", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "writeNeeded", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "docId", ",", "holder", ")", "\n", "}", "\n", "}", "\n", "*", "outPtr", "=", "[", "]", "txn", ".", "Op", "{", "{", "C", ":", "collection", ",", "Id", ":", "leaseHolderDocId", "(", "key", ".", "Namespace", ",", "key", ".", "ModelUUID", ",", "key", ".", "Lease", ",", ")", ",", "Assert", ":", "bson", ".", "M", "{", "fieldHolder", ":", "holder", ",", "}", ",", "}", "}", "\n", "return", "nil", "\n", "}", "\n", "}", "\n", "}" ]
// MakeTrapdoorFunc returns a raftlease.TrapdoorFunc for the specified // collection.
[ "MakeTrapdoorFunc", "returns", "a", "raftlease", ".", "TrapdoorFunc", "for", "the", "specified", "collection", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/raftlease/target.go#L225-L263
157,012
juju/juju
state/raftlease/target.go
LeaseHolders
func LeaseHolders(mongo Mongo, collection, namespace, modelUUID string) (map[string]string, error) { coll, closer := mongo.GetCollection(collection) defer closer() iter := coll.Find(bson.M{ fieldNamespace: namespace, fieldModelUUID: modelUUID, }).Iter() results := make(map[string]string) var doc leaseHolderDoc for iter.Next(&doc) { results[doc.Lease] = doc.Holder } if err := iter.Close(); err != nil { return nil, errors.Trace(err) } return results, nil }
go
func LeaseHolders(mongo Mongo, collection, namespace, modelUUID string) (map[string]string, error) { coll, closer := mongo.GetCollection(collection) defer closer() iter := coll.Find(bson.M{ fieldNamespace: namespace, fieldModelUUID: modelUUID, }).Iter() results := make(map[string]string) var doc leaseHolderDoc for iter.Next(&doc) { results[doc.Lease] = doc.Holder } if err := iter.Close(); err != nil { return nil, errors.Trace(err) } return results, nil }
[ "func", "LeaseHolders", "(", "mongo", "Mongo", ",", "collection", ",", "namespace", ",", "modelUUID", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "coll", ",", "closer", ":=", "mongo", ".", "GetCollection", "(", "collection", ")", "\n", "defer", "closer", "(", ")", "\n\n", "iter", ":=", "coll", ".", "Find", "(", "bson", ".", "M", "{", "fieldNamespace", ":", "namespace", ",", "fieldModelUUID", ":", "modelUUID", ",", "}", ")", ".", "Iter", "(", ")", "\n", "results", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "var", "doc", "leaseHolderDoc", "\n", "for", "iter", ".", "Next", "(", "&", "doc", ")", "{", "results", "[", "doc", ".", "Lease", "]", "=", "doc", ".", "Holder", "\n", "}", "\n\n", "if", "err", ":=", "iter", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// LeaseHolders returns a map of each lease and the holder in the // specified namespace and model.
[ "LeaseHolders", "returns", "a", "map", "of", "each", "lease", "and", "the", "holder", "in", "the", "specified", "namespace", "and", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/raftlease/target.go#L276-L294
157,013
juju/juju
cmd/juju/action/run.go
SetFlags
func (c *runCommand) SetFlags(f *gnuflag.FlagSet) { c.ActionCommandBase.SetFlags(f) c.out.AddFlags(f, "yaml", output.DefaultFormatters) f.Var(&c.paramsYAML, "params", "Path to yaml-formatted params file") f.BoolVar(&c.parseStrings, "string-args", false, "Use raw string values of CLI args") f.Var(&c.wait, "wait", "Wait for results, with optional timeout") }
go
func (c *runCommand) SetFlags(f *gnuflag.FlagSet) { c.ActionCommandBase.SetFlags(f) c.out.AddFlags(f, "yaml", output.DefaultFormatters) f.Var(&c.paramsYAML, "params", "Path to yaml-formatted params file") f.BoolVar(&c.parseStrings, "string-args", false, "Use raw string values of CLI args") f.Var(&c.wait, "wait", "Wait for results, with optional timeout") }
[ "func", "(", "c", "*", "runCommand", ")", "SetFlags", "(", "f", "*", "gnuflag", ".", "FlagSet", ")", "{", "c", ".", "ActionCommandBase", ".", "SetFlags", "(", "f", ")", "\n", "c", ".", "out", ".", "AddFlags", "(", "f", ",", "\"", "\"", ",", "output", ".", "DefaultFormatters", ")", "\n", "f", ".", "Var", "(", "&", "c", ".", "paramsYAML", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "f", ".", "BoolVar", "(", "&", "c", ".", "parseStrings", ",", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n", "f", ".", "Var", "(", "&", "c", ".", "wait", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}" ]
// SetFlags offers an option for YAML output.
[ "SetFlags", "offers", "an", "option", "for", "YAML", "output", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/action/run.go#L91-L97
157,014
juju/juju
apiserver/common/addresses.go
NewAPIAddresser
func NewAPIAddresser(getter AddressAndCertGetter, resources facade.Resources) *APIAddresser { return &APIAddresser{ getter: getter, resources: resources, } }
go
func NewAPIAddresser(getter AddressAndCertGetter, resources facade.Resources) *APIAddresser { return &APIAddresser{ getter: getter, resources: resources, } }
[ "func", "NewAPIAddresser", "(", "getter", "AddressAndCertGetter", ",", "resources", "facade", ".", "Resources", ")", "*", "APIAddresser", "{", "return", "&", "APIAddresser", "{", "getter", ":", "getter", ",", "resources", ":", "resources", ",", "}", "\n", "}" ]
// NewAPIAddresser returns a new APIAddresser that uses the given getter to // fetch its addresses.
[ "NewAPIAddresser", "returns", "a", "new", "APIAddresser", "that", "uses", "the", "given", "getter", "to", "fetch", "its", "addresses", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/addresses.go#L34-L39
157,015
juju/juju
apiserver/common/addresses.go
APIHostPorts
func (a *APIAddresser) APIHostPorts() (params.APIHostPortsResult, error) { servers, err := a.getter.APIHostPortsForAgents() if err != nil { return params.APIHostPortsResult{}, err } return params.APIHostPortsResult{ Servers: params.FromNetworkHostsPorts(servers), }, nil }
go
func (a *APIAddresser) APIHostPorts() (params.APIHostPortsResult, error) { servers, err := a.getter.APIHostPortsForAgents() if err != nil { return params.APIHostPortsResult{}, err } return params.APIHostPortsResult{ Servers: params.FromNetworkHostsPorts(servers), }, nil }
[ "func", "(", "a", "*", "APIAddresser", ")", "APIHostPorts", "(", ")", "(", "params", ".", "APIHostPortsResult", ",", "error", ")", "{", "servers", ",", "err", ":=", "a", ".", "getter", ".", "APIHostPortsForAgents", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "APIHostPortsResult", "{", "}", ",", "err", "\n", "}", "\n", "return", "params", ".", "APIHostPortsResult", "{", "Servers", ":", "params", ".", "FromNetworkHostsPorts", "(", "servers", ")", ",", "}", ",", "nil", "\n", "}" ]
// APIHostPorts returns the API server addresses.
[ "APIHostPorts", "returns", "the", "API", "server", "addresses", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/addresses.go#L42-L50
157,016
juju/juju
apiserver/common/addresses.go
WatchAPIHostPorts
func (a *APIAddresser) WatchAPIHostPorts() (params.NotifyWatchResult, error) { watch := a.getter.WatchAPIHostPortsForAgents() if _, ok := <-watch.Changes(); ok { return params.NotifyWatchResult{ NotifyWatcherId: a.resources.Register(watch), }, nil } return params.NotifyWatchResult{}, watcher.EnsureErr(watch) }
go
func (a *APIAddresser) WatchAPIHostPorts() (params.NotifyWatchResult, error) { watch := a.getter.WatchAPIHostPortsForAgents() if _, ok := <-watch.Changes(); ok { return params.NotifyWatchResult{ NotifyWatcherId: a.resources.Register(watch), }, nil } return params.NotifyWatchResult{}, watcher.EnsureErr(watch) }
[ "func", "(", "a", "*", "APIAddresser", ")", "WatchAPIHostPorts", "(", ")", "(", "params", ".", "NotifyWatchResult", ",", "error", ")", "{", "watch", ":=", "a", ".", "getter", ".", "WatchAPIHostPortsForAgents", "(", ")", "\n", "if", "_", ",", "ok", ":=", "<-", "watch", ".", "Changes", "(", ")", ";", "ok", "{", "return", "params", ".", "NotifyWatchResult", "{", "NotifyWatcherId", ":", "a", ".", "resources", ".", "Register", "(", "watch", ")", ",", "}", ",", "nil", "\n", "}", "\n", "return", "params", ".", "NotifyWatchResult", "{", "}", ",", "watcher", ".", "EnsureErr", "(", "watch", ")", "\n", "}" ]
// WatchAPIHostPorts watches the API server addresses.
[ "WatchAPIHostPorts", "watches", "the", "API", "server", "addresses", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/addresses.go#L53-L61
157,017
juju/juju
apiserver/common/addresses.go
ModelUUID
func (a *APIAddresser) ModelUUID() params.StringResult { return params.StringResult{Result: a.getter.ModelUUID()} }
go
func (a *APIAddresser) ModelUUID() params.StringResult { return params.StringResult{Result: a.getter.ModelUUID()} }
[ "func", "(", "a", "*", "APIAddresser", ")", "ModelUUID", "(", ")", "params", ".", "StringResult", "{", "return", "params", ".", "StringResult", "{", "Result", ":", "a", ".", "getter", ".", "ModelUUID", "(", ")", "}", "\n", "}" ]
// ModelUUID returns the model UUID to connect to the model // that the current connection is for.
[ "ModelUUID", "returns", "the", "model", "UUID", "to", "connect", "to", "the", "model", "that", "the", "current", "connection", "is", "for", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/addresses.go#L93-L95
157,018
juju/juju
service/systemd/conf.go
normalize
func normalize(name string, conf common.Conf, scriptPath string, renderer confRenderer) (common.Conf, []byte) { var data []byte var cmds []string if conf.Logfile != "" { filename := conf.Logfile cmds = append(cmds, "# Set up logging.") cmds = append(cmds, renderer.Touch(filename, nil)...) // TODO(ericsnow) We should drop the assumption that the logfile // is syslog. user, group := syslogUserGroup() cmds = append(cmds, renderer.Chown(filename, user, group)...) cmds = append(cmds, renderer.Chmod(filename, 0600)...) cmds = append(cmds, renderer.RedirectOutput(filename)...) cmds = append(cmds, renderer.RedirectFD("out", "err")...) cmds = append(cmds, "", "# Run the script.", ) // We leave conf.Logfile alone (it will be ignored during validation). } cmds = append(cmds, conf.ExecStart) if conf.ExtraScript != "" { cmds = append([]string{conf.ExtraScript}, cmds...) conf.ExtraScript = "" } if !isSimpleCommand(strings.Join(cmds, "\n")) { data = renderer.RenderScript(cmds) conf.ExecStart = scriptPath } if len(conf.Env) == 0 { conf.Env = nil } if len(conf.Limit) == 0 { conf.Limit = nil } if conf.Transient { // TODO(ericsnow) Handle Transient via systemd-run command? conf.ExecStopPost = commands{}.disable(name) } return conf, data }
go
func normalize(name string, conf common.Conf, scriptPath string, renderer confRenderer) (common.Conf, []byte) { var data []byte var cmds []string if conf.Logfile != "" { filename := conf.Logfile cmds = append(cmds, "# Set up logging.") cmds = append(cmds, renderer.Touch(filename, nil)...) // TODO(ericsnow) We should drop the assumption that the logfile // is syslog. user, group := syslogUserGroup() cmds = append(cmds, renderer.Chown(filename, user, group)...) cmds = append(cmds, renderer.Chmod(filename, 0600)...) cmds = append(cmds, renderer.RedirectOutput(filename)...) cmds = append(cmds, renderer.RedirectFD("out", "err")...) cmds = append(cmds, "", "# Run the script.", ) // We leave conf.Logfile alone (it will be ignored during validation). } cmds = append(cmds, conf.ExecStart) if conf.ExtraScript != "" { cmds = append([]string{conf.ExtraScript}, cmds...) conf.ExtraScript = "" } if !isSimpleCommand(strings.Join(cmds, "\n")) { data = renderer.RenderScript(cmds) conf.ExecStart = scriptPath } if len(conf.Env) == 0 { conf.Env = nil } if len(conf.Limit) == 0 { conf.Limit = nil } if conf.Transient { // TODO(ericsnow) Handle Transient via systemd-run command? conf.ExecStopPost = commands{}.disable(name) } return conf, data }
[ "func", "normalize", "(", "name", "string", ",", "conf", "common", ".", "Conf", ",", "scriptPath", "string", ",", "renderer", "confRenderer", ")", "(", "common", ".", "Conf", ",", "[", "]", "byte", ")", "{", "var", "data", "[", "]", "byte", "\n\n", "var", "cmds", "[", "]", "string", "\n", "if", "conf", ".", "Logfile", "!=", "\"", "\"", "{", "filename", ":=", "conf", ".", "Logfile", "\n", "cmds", "=", "append", "(", "cmds", ",", "\"", "\"", ")", "\n", "cmds", "=", "append", "(", "cmds", ",", "renderer", ".", "Touch", "(", "filename", ",", "nil", ")", "...", ")", "\n", "// TODO(ericsnow) We should drop the assumption that the logfile", "// is syslog.", "user", ",", "group", ":=", "syslogUserGroup", "(", ")", "\n", "cmds", "=", "append", "(", "cmds", ",", "renderer", ".", "Chown", "(", "filename", ",", "user", ",", "group", ")", "...", ")", "\n", "cmds", "=", "append", "(", "cmds", ",", "renderer", ".", "Chmod", "(", "filename", ",", "0600", ")", "...", ")", "\n", "cmds", "=", "append", "(", "cmds", ",", "renderer", ".", "RedirectOutput", "(", "filename", ")", "...", ")", "\n", "cmds", "=", "append", "(", "cmds", ",", "renderer", ".", "RedirectFD", "(", "\"", "\"", ",", "\"", "\"", ")", "...", ")", "\n", "cmds", "=", "append", "(", "cmds", ",", "\"", "\"", ",", "\"", "\"", ",", ")", "\n", "// We leave conf.Logfile alone (it will be ignored during validation).", "}", "\n", "cmds", "=", "append", "(", "cmds", ",", "conf", ".", "ExecStart", ")", "\n\n", "if", "conf", ".", "ExtraScript", "!=", "\"", "\"", "{", "cmds", "=", "append", "(", "[", "]", "string", "{", "conf", ".", "ExtraScript", "}", ",", "cmds", "...", ")", "\n", "conf", ".", "ExtraScript", "=", "\"", "\"", "\n", "}", "\n", "if", "!", "isSimpleCommand", "(", "strings", ".", "Join", "(", "cmds", ",", "\"", "\\n", "\"", ")", ")", "{", "data", "=", "renderer", ".", "RenderScript", "(", "cmds", ")", "\n", "conf", ".", "ExecStart", "=", "scriptPath", "\n", "}", "\n\n", "if", "len", "(", "conf", ".", "Env", ")", "==", "0", "{", "conf", ".", "Env", "=", "nil", "\n", "}", "\n\n", "if", "len", "(", "conf", ".", "Limit", ")", "==", "0", "{", "conf", ".", "Limit", "=", "nil", "\n", "}", "\n\n", "if", "conf", ".", "Transient", "{", "// TODO(ericsnow) Handle Transient via systemd-run command?", "conf", ".", "ExecStopPost", "=", "commands", "{", "}", ".", "disable", "(", "name", ")", "\n", "}", "\n\n", "return", "conf", ",", "data", "\n", "}" ]
// normalize adjusts the conf to more standardized content and // returns a new Conf with that updated content. It also returns the // content of any script file that should accompany the conf.
[ "normalize", "adjusts", "the", "conf", "to", "more", "standardized", "content", "and", "returns", "a", "new", "Conf", "with", "that", "updated", "content", ".", "It", "also", "returns", "the", "content", "of", "any", "script", "file", "that", "should", "accompany", "the", "conf", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/service/systemd/conf.go#L59-L105
157,019
juju/juju
service/systemd/conf.go
serialize
func serialize(name string, conf common.Conf, renderer shell.Renderer) ([]byte, error) { if err := validate(name, conf, renderer); err != nil { return nil, errors.Trace(err) } var unitOptions []*unit.UnitOption unitOptions = append(unitOptions, serializeUnit(conf)...) unitOptions = append(unitOptions, serializeService(conf)...) unitOptions = append(unitOptions, serializeInstall(conf)...) // Don't use unit.Serialize because it has map ordering issues. // Serialize copied locally, and outputs sections in alphabetical order. data, err := ioutil.ReadAll(UnitSerialize(unitOptions)) return data, errors.Trace(err) }
go
func serialize(name string, conf common.Conf, renderer shell.Renderer) ([]byte, error) { if err := validate(name, conf, renderer); err != nil { return nil, errors.Trace(err) } var unitOptions []*unit.UnitOption unitOptions = append(unitOptions, serializeUnit(conf)...) unitOptions = append(unitOptions, serializeService(conf)...) unitOptions = append(unitOptions, serializeInstall(conf)...) // Don't use unit.Serialize because it has map ordering issues. // Serialize copied locally, and outputs sections in alphabetical order. data, err := ioutil.ReadAll(UnitSerialize(unitOptions)) return data, errors.Trace(err) }
[ "func", "serialize", "(", "name", "string", ",", "conf", "common", ".", "Conf", ",", "renderer", "shell", ".", "Renderer", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "err", ":=", "validate", "(", "name", ",", "conf", ",", "renderer", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "var", "unitOptions", "[", "]", "*", "unit", ".", "UnitOption", "\n", "unitOptions", "=", "append", "(", "unitOptions", ",", "serializeUnit", "(", "conf", ")", "...", ")", "\n", "unitOptions", "=", "append", "(", "unitOptions", ",", "serializeService", "(", "conf", ")", "...", ")", "\n", "unitOptions", "=", "append", "(", "unitOptions", ",", "serializeInstall", "(", "conf", ")", "...", ")", "\n", "// Don't use unit.Serialize because it has map ordering issues.", "// Serialize copied locally, and outputs sections in alphabetical order.", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "UnitSerialize", "(", "unitOptions", ")", ")", "\n", "return", "data", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// serialize returns the data that should be written to disk for the // provided Conf, rendered in the systemd unit file format.
[ "serialize", "returns", "the", "data", "that", "should", "be", "written", "to", "disk", "for", "the", "provided", "Conf", "rendered", "in", "the", "systemd", "unit", "file", "format", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/service/systemd/conf.go#L141-L154
157,020
juju/juju
jujuclient/credentials.go
ReadCredentialsFile
func ReadCredentialsFile(file string) (map[string]cloud.CloudCredential, error) { data, err := ioutil.ReadFile(file) if err != nil { if os.IsNotExist(err) { return nil, nil } return nil, err } credentials, err := cloud.ParseCredentials(data) if err != nil { return nil, err } return credentials, nil }
go
func ReadCredentialsFile(file string) (map[string]cloud.CloudCredential, error) { data, err := ioutil.ReadFile(file) if err != nil { if os.IsNotExist(err) { return nil, nil } return nil, err } credentials, err := cloud.ParseCredentials(data) if err != nil { return nil, err } return credentials, nil }
[ "func", "ReadCredentialsFile", "(", "file", "string", ")", "(", "map", "[", "string", "]", "cloud", ".", "CloudCredential", ",", "error", ")", "{", "data", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "file", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "credentials", ",", "err", ":=", "cloud", ".", "ParseCredentials", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "credentials", ",", "nil", "\n", "}" ]
// ReadCredentialsFile loads all credentials defined in a given file. // If the file is not found, it is not an error.
[ "ReadCredentialsFile", "loads", "all", "credentials", "defined", "in", "a", "given", "file", ".", "If", "the", "file", "is", "not", "found", "it", "is", "not", "an", "error", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/jujuclient/credentials.go#L26-L39
157,021
juju/juju
jujuclient/credentials.go
WriteCredentialsFile
func WriteCredentialsFile(credentials map[string]cloud.CloudCredential) error { data, err := yaml.Marshal(credentialsCollection{credentials}) if err != nil { return errors.Annotate(err, "cannot marshal yaml credentials") } return utils.AtomicWriteFile(JujuCredentialsPath(), data, os.FileMode(0600)) }
go
func WriteCredentialsFile(credentials map[string]cloud.CloudCredential) error { data, err := yaml.Marshal(credentialsCollection{credentials}) if err != nil { return errors.Annotate(err, "cannot marshal yaml credentials") } return utils.AtomicWriteFile(JujuCredentialsPath(), data, os.FileMode(0600)) }
[ "func", "WriteCredentialsFile", "(", "credentials", "map", "[", "string", "]", "cloud", ".", "CloudCredential", ")", "error", "{", "data", ",", "err", ":=", "yaml", ".", "Marshal", "(", "credentialsCollection", "{", "credentials", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "utils", ".", "AtomicWriteFile", "(", "JujuCredentialsPath", "(", ")", ",", "data", ",", "os", ".", "FileMode", "(", "0600", ")", ")", "\n", "}" ]
// WriteCredentialsFile marshals to YAML details of the given credentials // and writes it to the credentials file.
[ "WriteCredentialsFile", "marshals", "to", "YAML", "details", "of", "the", "given", "credentials", "and", "writes", "it", "to", "the", "credentials", "file", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/jujuclient/credentials.go#L43-L49
157,022
juju/juju
worker/uniter/manifold.go
Manifold
func Manifold(config ManifoldConfig) dependency.Manifold { return dependency.Manifold{ Inputs: []string{ config.AgentName, config.APICallerName, config.LeadershipTrackerName, config.CharmDirName, config.HookRetryStrategyName, }, Start: func(context dependency.Context) (worker.Worker, error) { if config.Clock == nil { return nil, errors.NotValidf("missing Clock") } if config.MachineLock == nil { return nil, errors.NotValidf("missing MachineLock") } // Collect all required resources. var agent agent.Agent if err := context.Get(config.AgentName, &agent); err != nil { return nil, err } var apiConn api.Connection if err := context.Get(config.APICallerName, &apiConn); err != nil { // TODO(fwereade): absence of an APICaller shouldn't be the end of // the world -- we ought to return a type that can at least run the // leader-deposed hook -- but that's not done yet. return nil, err } var leadershipTracker leadership.TrackerWorker if err := context.Get(config.LeadershipTrackerName, &leadershipTracker); err != nil { return nil, err } var charmDirGuard fortress.Guard if err := context.Get(config.CharmDirName, &charmDirGuard); err != nil { return nil, err } var hookRetryStrategy params.RetryStrategy if err := context.Get(config.HookRetryStrategyName, &hookRetryStrategy); err != nil { return nil, err } downloader := api.NewCharmDownloader(apiConn) manifoldConfig := config // Configure and start the uniter. agentConfig := agent.CurrentConfig() tag := agentConfig.Tag() unitTag, ok := tag.(names.UnitTag) if !ok { return nil, errors.Errorf("expected a unit tag, got %v", tag) } uniterFacade := uniter.NewState(apiConn, unitTag) uniter, err := NewUniter(&UniterParams{ UniterFacade: uniterFacade, UnitTag: unitTag, ModelType: model.IAAS, LeadershipTracker: leadershipTracker, DataDir: agentConfig.DataDir(), Downloader: downloader, MachineLock: manifoldConfig.MachineLock, CharmDirGuard: charmDirGuard, UpdateStatusSignal: NewUpdateStatusTimer(), HookRetryStrategy: hookRetryStrategy, NewOperationExecutor: operation.NewExecutor, TranslateResolverErr: config.TranslateResolverErr, Clock: manifoldConfig.Clock, }) if err != nil { return nil, errors.Trace(err) } return uniter, nil }, } }
go
func Manifold(config ManifoldConfig) dependency.Manifold { return dependency.Manifold{ Inputs: []string{ config.AgentName, config.APICallerName, config.LeadershipTrackerName, config.CharmDirName, config.HookRetryStrategyName, }, Start: func(context dependency.Context) (worker.Worker, error) { if config.Clock == nil { return nil, errors.NotValidf("missing Clock") } if config.MachineLock == nil { return nil, errors.NotValidf("missing MachineLock") } // Collect all required resources. var agent agent.Agent if err := context.Get(config.AgentName, &agent); err != nil { return nil, err } var apiConn api.Connection if err := context.Get(config.APICallerName, &apiConn); err != nil { // TODO(fwereade): absence of an APICaller shouldn't be the end of // the world -- we ought to return a type that can at least run the // leader-deposed hook -- but that's not done yet. return nil, err } var leadershipTracker leadership.TrackerWorker if err := context.Get(config.LeadershipTrackerName, &leadershipTracker); err != nil { return nil, err } var charmDirGuard fortress.Guard if err := context.Get(config.CharmDirName, &charmDirGuard); err != nil { return nil, err } var hookRetryStrategy params.RetryStrategy if err := context.Get(config.HookRetryStrategyName, &hookRetryStrategy); err != nil { return nil, err } downloader := api.NewCharmDownloader(apiConn) manifoldConfig := config // Configure and start the uniter. agentConfig := agent.CurrentConfig() tag := agentConfig.Tag() unitTag, ok := tag.(names.UnitTag) if !ok { return nil, errors.Errorf("expected a unit tag, got %v", tag) } uniterFacade := uniter.NewState(apiConn, unitTag) uniter, err := NewUniter(&UniterParams{ UniterFacade: uniterFacade, UnitTag: unitTag, ModelType: model.IAAS, LeadershipTracker: leadershipTracker, DataDir: agentConfig.DataDir(), Downloader: downloader, MachineLock: manifoldConfig.MachineLock, CharmDirGuard: charmDirGuard, UpdateStatusSignal: NewUpdateStatusTimer(), HookRetryStrategy: hookRetryStrategy, NewOperationExecutor: operation.NewExecutor, TranslateResolverErr: config.TranslateResolverErr, Clock: manifoldConfig.Clock, }) if err != nil { return nil, errors.Trace(err) } return uniter, nil }, } }
[ "func", "Manifold", "(", "config", "ManifoldConfig", ")", "dependency", ".", "Manifold", "{", "return", "dependency", ".", "Manifold", "{", "Inputs", ":", "[", "]", "string", "{", "config", ".", "AgentName", ",", "config", ".", "APICallerName", ",", "config", ".", "LeadershipTrackerName", ",", "config", ".", "CharmDirName", ",", "config", ".", "HookRetryStrategyName", ",", "}", ",", "Start", ":", "func", "(", "context", "dependency", ".", "Context", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "if", "config", ".", "Clock", "==", "nil", "{", "return", "nil", ",", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "config", ".", "MachineLock", "==", "nil", "{", "return", "nil", ",", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Collect all required resources.", "var", "agent", "agent", ".", "Agent", "\n", "if", "err", ":=", "context", ".", "Get", "(", "config", ".", "AgentName", ",", "&", "agent", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "apiConn", "api", ".", "Connection", "\n", "if", "err", ":=", "context", ".", "Get", "(", "config", ".", "APICallerName", ",", "&", "apiConn", ")", ";", "err", "!=", "nil", "{", "// TODO(fwereade): absence of an APICaller shouldn't be the end of", "// the world -- we ought to return a type that can at least run the", "// leader-deposed hook -- but that's not done yet.", "return", "nil", ",", "err", "\n", "}", "\n", "var", "leadershipTracker", "leadership", ".", "TrackerWorker", "\n", "if", "err", ":=", "context", ".", "Get", "(", "config", ".", "LeadershipTrackerName", ",", "&", "leadershipTracker", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "charmDirGuard", "fortress", ".", "Guard", "\n", "if", "err", ":=", "context", ".", "Get", "(", "config", ".", "CharmDirName", ",", "&", "charmDirGuard", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "hookRetryStrategy", "params", ".", "RetryStrategy", "\n", "if", "err", ":=", "context", ".", "Get", "(", "config", ".", "HookRetryStrategyName", ",", "&", "hookRetryStrategy", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "downloader", ":=", "api", ".", "NewCharmDownloader", "(", "apiConn", ")", "\n\n", "manifoldConfig", ":=", "config", "\n", "// Configure and start the uniter.", "agentConfig", ":=", "agent", ".", "CurrentConfig", "(", ")", "\n", "tag", ":=", "agentConfig", ".", "Tag", "(", ")", "\n", "unitTag", ",", "ok", ":=", "tag", ".", "(", "names", ".", "UnitTag", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "tag", ")", "\n", "}", "\n", "uniterFacade", ":=", "uniter", ".", "NewState", "(", "apiConn", ",", "unitTag", ")", "\n", "uniter", ",", "err", ":=", "NewUniter", "(", "&", "UniterParams", "{", "UniterFacade", ":", "uniterFacade", ",", "UnitTag", ":", "unitTag", ",", "ModelType", ":", "model", ".", "IAAS", ",", "LeadershipTracker", ":", "leadershipTracker", ",", "DataDir", ":", "agentConfig", ".", "DataDir", "(", ")", ",", "Downloader", ":", "downloader", ",", "MachineLock", ":", "manifoldConfig", ".", "MachineLock", ",", "CharmDirGuard", ":", "charmDirGuard", ",", "UpdateStatusSignal", ":", "NewUpdateStatusTimer", "(", ")", ",", "HookRetryStrategy", ":", "hookRetryStrategy", ",", "NewOperationExecutor", ":", "operation", ".", "NewExecutor", ",", "TranslateResolverErr", ":", "config", ".", "TranslateResolverErr", ",", "Clock", ":", "manifoldConfig", ".", "Clock", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "uniter", ",", "nil", "\n", "}", ",", "}", "\n", "}" ]
// Manifold returns a dependency manifold that runs a uniter worker, // using the resource names defined in the supplied config.
[ "Manifold", "returns", "a", "dependency", "manifold", "that", "runs", "a", "uniter", "worker", "using", "the", "resource", "names", "defined", "in", "the", "supplied", "config", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/manifold.go#L40-L115
157,023
juju/juju
container/lxd/storage.go
EnsureDefaultStorage
func (s *Server) EnsureDefaultStorage(profile *api.Profile, eTag string) error { // If there is already a "/" device, we have nothing to do. for _, dev := range profile.Devices { if dev["path"] == "/" { return nil } } // If there is a "default" pool, use it. // Otherwise if there are other pools available, choose the first. pools, err := s.GetStoragePoolNames() if err != nil { return errors.Trace(err) } poolName := "" for _, p := range pools { if p == "default" { poolName = p } } if poolName == "" && len(pools) > 0 { poolName = pools[0] } // We need to create a new storage pool. if poolName == "" { poolName = "default" req := api.StoragePoolsPost{ Name: poolName, Driver: "dir", } err := s.CreateStoragePool(req) if err != nil { return errors.Trace(err) } } // Create a new disk device in the input profile. if profile.Devices == nil { profile.Devices = map[string]device{} } profile.Devices["root"] = map[string]string{ "type": "disk", "path": "/", "pool": poolName, } if err := s.UpdateProfile(profile.Name, profile.Writable(), eTag); err != nil { return errors.Trace(err) } logger.Debugf("created new disk device \"root\" in profile %q", profile.Name) return nil }
go
func (s *Server) EnsureDefaultStorage(profile *api.Profile, eTag string) error { // If there is already a "/" device, we have nothing to do. for _, dev := range profile.Devices { if dev["path"] == "/" { return nil } } // If there is a "default" pool, use it. // Otherwise if there are other pools available, choose the first. pools, err := s.GetStoragePoolNames() if err != nil { return errors.Trace(err) } poolName := "" for _, p := range pools { if p == "default" { poolName = p } } if poolName == "" && len(pools) > 0 { poolName = pools[0] } // We need to create a new storage pool. if poolName == "" { poolName = "default" req := api.StoragePoolsPost{ Name: poolName, Driver: "dir", } err := s.CreateStoragePool(req) if err != nil { return errors.Trace(err) } } // Create a new disk device in the input profile. if profile.Devices == nil { profile.Devices = map[string]device{} } profile.Devices["root"] = map[string]string{ "type": "disk", "path": "/", "pool": poolName, } if err := s.UpdateProfile(profile.Name, profile.Writable(), eTag); err != nil { return errors.Trace(err) } logger.Debugf("created new disk device \"root\" in profile %q", profile.Name) return nil }
[ "func", "(", "s", "*", "Server", ")", "EnsureDefaultStorage", "(", "profile", "*", "api", ".", "Profile", ",", "eTag", "string", ")", "error", "{", "// If there is already a \"/\" device, we have nothing to do.", "for", "_", ",", "dev", ":=", "range", "profile", ".", "Devices", "{", "if", "dev", "[", "\"", "\"", "]", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n", "}", "\n\n", "// If there is a \"default\" pool, use it.", "// Otherwise if there are other pools available, choose the first.", "pools", ",", "err", ":=", "s", ".", "GetStoragePoolNames", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "poolName", ":=", "\"", "\"", "\n", "for", "_", ",", "p", ":=", "range", "pools", "{", "if", "p", "==", "\"", "\"", "{", "poolName", "=", "p", "\n", "}", "\n", "}", "\n", "if", "poolName", "==", "\"", "\"", "&&", "len", "(", "pools", ")", ">", "0", "{", "poolName", "=", "pools", "[", "0", "]", "\n", "}", "\n\n", "// We need to create a new storage pool.", "if", "poolName", "==", "\"", "\"", "{", "poolName", "=", "\"", "\"", "\n", "req", ":=", "api", ".", "StoragePoolsPost", "{", "Name", ":", "poolName", ",", "Driver", ":", "\"", "\"", ",", "}", "\n", "err", ":=", "s", ".", "CreateStoragePool", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "// Create a new disk device in the input profile.", "if", "profile", ".", "Devices", "==", "nil", "{", "profile", ".", "Devices", "=", "map", "[", "string", "]", "device", "{", "}", "\n", "}", "\n", "profile", ".", "Devices", "[", "\"", "\"", "]", "=", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "poolName", ",", "}", "\n\n", "if", "err", ":=", "s", ".", "UpdateProfile", "(", "profile", ".", "Name", ",", "profile", ".", "Writable", "(", ")", ",", "eTag", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\\\"", "\\\"", "\"", ",", "profile", ".", "Name", ")", "\n", "return", "nil", "\n", "}" ]
// EnsureDefaultStorage ensures that the input profile is configured with a // disk device, creating a new storage pool and a device if required.
[ "EnsureDefaultStorage", "ensures", "that", "the", "input", "profile", "is", "configured", "with", "a", "disk", "device", "creating", "a", "new", "storage", "pool", "and", "a", "device", "if", "required", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/storage.go#L35-L87
157,024
juju/juju
apiserver/websocket/websocket.go
Serve
func Serve(w http.ResponseWriter, req *http.Request, handler func(ws *Conn)) { conn, err := websocketUpgrader.Upgrade(w, req, nil) if err != nil { logger.Errorf("problem initiating websocket: %v", err) return } handler(&Conn{conn}) }
go
func Serve(w http.ResponseWriter, req *http.Request, handler func(ws *Conn)) { conn, err := websocketUpgrader.Upgrade(w, req, nil) if err != nil { logger.Errorf("problem initiating websocket: %v", err) return } handler(&Conn{conn}) }
[ "func", "Serve", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ",", "handler", "func", "(", "ws", "*", "Conn", ")", ")", "{", "conn", ",", "err", ":=", "websocketUpgrader", ".", "Upgrade", "(", "w", ",", "req", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "handler", "(", "&", "Conn", "{", "conn", "}", ")", "\n", "}" ]
// Serve upgrades an HTTP connection to a websocket, and // serves the given handler.
[ "Serve", "upgrades", "an", "HTTP", "connection", "to", "a", "websocket", "and", "serves", "the", "given", "handler", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/websocket/websocket.go#L49-L56
157,025
juju/juju
apiserver/websocket/websocket.go
SendInitialErrorV0
func (conn *Conn) SendInitialErrorV0(err error) error { wrapped := &params.ErrorResult{ Error: common.ServerError(err), } body, err := json.Marshal(wrapped) if err != nil { errors.Annotatef(err, "cannot marshal error %#v", wrapped) return err } body = append(body, '\n') writer, err := conn.NextWriter(websocket.TextMessage) if err != nil { return errors.Annotate(err, "problem getting writer") } defer writer.Close() _, err = writer.Write(body) if wrapped.Error != nil { // Tell the other end we are closing. conn.WriteMessage(websocket.CloseMessage, []byte{}) } return errors.Trace(err) }
go
func (conn *Conn) SendInitialErrorV0(err error) error { wrapped := &params.ErrorResult{ Error: common.ServerError(err), } body, err := json.Marshal(wrapped) if err != nil { errors.Annotatef(err, "cannot marshal error %#v", wrapped) return err } body = append(body, '\n') writer, err := conn.NextWriter(websocket.TextMessage) if err != nil { return errors.Annotate(err, "problem getting writer") } defer writer.Close() _, err = writer.Write(body) if wrapped.Error != nil { // Tell the other end we are closing. conn.WriteMessage(websocket.CloseMessage, []byte{}) } return errors.Trace(err) }
[ "func", "(", "conn", "*", "Conn", ")", "SendInitialErrorV0", "(", "err", "error", ")", "error", "{", "wrapped", ":=", "&", "params", ".", "ErrorResult", "{", "Error", ":", "common", ".", "ServerError", "(", "err", ")", ",", "}", "\n\n", "body", ",", "err", ":=", "json", ".", "Marshal", "(", "wrapped", ")", "\n", "if", "err", "!=", "nil", "{", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "wrapped", ")", "\n", "return", "err", "\n", "}", "\n", "body", "=", "append", "(", "body", ",", "'\\n'", ")", "\n\n", "writer", ",", "err", ":=", "conn", ".", "NextWriter", "(", "websocket", ".", "TextMessage", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "defer", "writer", ".", "Close", "(", ")", "\n", "_", ",", "err", "=", "writer", ".", "Write", "(", "body", ")", "\n\n", "if", "wrapped", ".", "Error", "!=", "nil", "{", "// Tell the other end we are closing.", "conn", ".", "WriteMessage", "(", "websocket", ".", "CloseMessage", ",", "[", "]", "byte", "{", "}", ")", "\n", "}", "\n\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// SendInitialErrorV0 writes out the error as a params.ErrorResult serialized // with JSON with a new line character at the end. // // This is a hangover from the initial debug-log streaming endpoint where the // client read the first line, and then just got a stream of data. We should // look to version the streaming endpoints to get rid of the trailing newline // character for message based connections, which is all of them now.
[ "SendInitialErrorV0", "writes", "out", "the", "error", "as", "a", "params", ".", "ErrorResult", "serialized", "with", "JSON", "with", "a", "new", "line", "character", "at", "the", "end", ".", "This", "is", "a", "hangover", "from", "the", "initial", "debug", "-", "log", "streaming", "endpoint", "where", "the", "client", "read", "the", "first", "line", "and", "then", "just", "got", "a", "stream", "of", "data", ".", "We", "should", "look", "to", "version", "the", "streaming", "endpoints", "to", "get", "rid", "of", "the", "trailing", "newline", "character", "for", "message", "based", "connections", "which", "is", "all", "of", "them", "now", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/websocket/websocket.go#L65-L90
157,026
juju/juju
api/allwatcher.go
NewAllWatcher
func NewAllWatcher(caller base.APICaller, id *string) *AllWatcher { return newAllWatcher("AllWatcher", caller, id) }
go
func NewAllWatcher(caller base.APICaller, id *string) *AllWatcher { return newAllWatcher("AllWatcher", caller, id) }
[ "func", "NewAllWatcher", "(", "caller", "base", ".", "APICaller", ",", "id", "*", "string", ")", "*", "AllWatcher", "{", "return", "newAllWatcher", "(", "\"", "\"", ",", "caller", ",", "id", ")", "\n", "}" ]
// NewAllWatcher returns an AllWatcher instance which interacts with a // watcher created by the WatchAll API call. // // There should be no need to call this from outside of the api // package. It is only used by Client.WatchAll in this package.
[ "NewAllWatcher", "returns", "an", "AllWatcher", "instance", "which", "interacts", "with", "a", "watcher", "created", "by", "the", "WatchAll", "API", "call", ".", "There", "should", "be", "no", "need", "to", "call", "this", "from", "outside", "of", "the", "api", "package", ".", "It", "is", "only", "used", "by", "Client", ".", "WatchAll", "in", "this", "package", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/allwatcher.go#L28-L30
157,027
juju/juju
api/allwatcher.go
Next
func (watcher *AllWatcher) Next() ([]multiwatcher.Delta, error) { var info params.AllWatcherNextResults err := watcher.caller.APICall( watcher.objType, watcher.caller.BestFacadeVersion(watcher.objType), *watcher.id, "Next", nil, &info, ) // We'll order the deltas so relation changes come last. // This allows the callers like the GUI to process changes // in the right order. sort.Sort(orderedDeltas(info.Deltas)) return info.Deltas, err }
go
func (watcher *AllWatcher) Next() ([]multiwatcher.Delta, error) { var info params.AllWatcherNextResults err := watcher.caller.APICall( watcher.objType, watcher.caller.BestFacadeVersion(watcher.objType), *watcher.id, "Next", nil, &info, ) // We'll order the deltas so relation changes come last. // This allows the callers like the GUI to process changes // in the right order. sort.Sort(orderedDeltas(info.Deltas)) return info.Deltas, err }
[ "func", "(", "watcher", "*", "AllWatcher", ")", "Next", "(", ")", "(", "[", "]", "multiwatcher", ".", "Delta", ",", "error", ")", "{", "var", "info", "params", ".", "AllWatcherNextResults", "\n", "err", ":=", "watcher", ".", "caller", ".", "APICall", "(", "watcher", ".", "objType", ",", "watcher", ".", "caller", ".", "BestFacadeVersion", "(", "watcher", ".", "objType", ")", ",", "*", "watcher", ".", "id", ",", "\"", "\"", ",", "nil", ",", "&", "info", ",", ")", "\n", "// We'll order the deltas so relation changes come last.", "// This allows the callers like the GUI to process changes", "// in the right order.", "sort", ".", "Sort", "(", "orderedDeltas", "(", "info", ".", "Deltas", ")", ")", "\n", "return", "info", ".", "Deltas", ",", "err", "\n", "}" ]
// Next returns a new set of deltas from a watcher previously created // by the WatchAll or WatchAllModels API calls. It will block until // there are deltas to return.
[ "Next", "returns", "a", "new", "set", "of", "deltas", "from", "a", "watcher", "previously", "created", "by", "the", "WatchAll", "or", "WatchAllModels", "API", "calls", ".", "It", "will", "block", "until", "there", "are", "deltas", "to", "return", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/allwatcher.go#L53-L67
157,028
juju/juju
api/allwatcher.go
Stop
func (watcher *AllWatcher) Stop() error { return watcher.caller.APICall( watcher.objType, watcher.caller.BestFacadeVersion(watcher.objType), *watcher.id, "Stop", nil, nil, ) }
go
func (watcher *AllWatcher) Stop() error { return watcher.caller.APICall( watcher.objType, watcher.caller.BestFacadeVersion(watcher.objType), *watcher.id, "Stop", nil, nil, ) }
[ "func", "(", "watcher", "*", "AllWatcher", ")", "Stop", "(", ")", "error", "{", "return", "watcher", ".", "caller", ".", "APICall", "(", "watcher", ".", "objType", ",", "watcher", ".", "caller", ".", "BestFacadeVersion", "(", "watcher", ".", "objType", ")", ",", "*", "watcher", ".", "id", ",", "\"", "\"", ",", "nil", ",", "nil", ",", ")", "\n", "}" ]
// Stop shutdowns down a watcher previously created by the WatchAll or // WatchAllModels API calls
[ "Stop", "shutdowns", "down", "a", "watcher", "previously", "created", "by", "the", "WatchAll", "or", "WatchAllModels", "API", "calls" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/allwatcher.go#L104-L112
157,029
juju/juju
state/remoteentities.go
ImportRemoteEntity
func (r *RemoteEntities) ImportRemoteEntity(entity names.Tag, token string) error { if token == "" { return errors.NotValidf("empty token for %v", entity.Id()) } buildTxn := func(int) (ops []txn.Op, _ error) { remoteEntity, err := r.remoteEntityDoc(entity) if err != nil && err != mgo.ErrNotFound { return nil, errors.Trace(err) } if err == nil { // Same token already exists. if remoteEntity.Token == token { return nil, jujutxn.ErrNoOperations } // Token already exists, so remove first. ops = append(ops, r.removeRemoteEntityOps(entity)...) } ops = append(ops, r.importRemoteEntityOps(entity, token)...) return ops, nil } err := r.st.db().Run(buildTxn) return errors.Annotatef(err, "recording reference to %s", names.ReadableString(entity)) }
go
func (r *RemoteEntities) ImportRemoteEntity(entity names.Tag, token string) error { if token == "" { return errors.NotValidf("empty token for %v", entity.Id()) } buildTxn := func(int) (ops []txn.Op, _ error) { remoteEntity, err := r.remoteEntityDoc(entity) if err != nil && err != mgo.ErrNotFound { return nil, errors.Trace(err) } if err == nil { // Same token already exists. if remoteEntity.Token == token { return nil, jujutxn.ErrNoOperations } // Token already exists, so remove first. ops = append(ops, r.removeRemoteEntityOps(entity)...) } ops = append(ops, r.importRemoteEntityOps(entity, token)...) return ops, nil } err := r.st.db().Run(buildTxn) return errors.Annotatef(err, "recording reference to %s", names.ReadableString(entity)) }
[ "func", "(", "r", "*", "RemoteEntities", ")", "ImportRemoteEntity", "(", "entity", "names", ".", "Tag", ",", "token", "string", ")", "error", "{", "if", "token", "==", "\"", "\"", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "entity", ".", "Id", "(", ")", ")", "\n", "}", "\n", "buildTxn", ":=", "func", "(", "int", ")", "(", "ops", "[", "]", "txn", ".", "Op", ",", "_", "error", ")", "{", "remoteEntity", ",", "err", ":=", "r", ".", "remoteEntityDoc", "(", "entity", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "mgo", ".", "ErrNotFound", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", "==", "nil", "{", "// Same token already exists.", "if", "remoteEntity", ".", "Token", "==", "token", "{", "return", "nil", ",", "jujutxn", ".", "ErrNoOperations", "\n", "}", "\n", "// Token already exists, so remove first.", "ops", "=", "append", "(", "ops", ",", "r", ".", "removeRemoteEntityOps", "(", "entity", ")", "...", ")", "\n", "}", "\n", "ops", "=", "append", "(", "ops", ",", "r", ".", "importRemoteEntityOps", "(", "entity", ",", "token", ")", "...", ")", "\n", "return", "ops", ",", "nil", "\n", "}", "\n", "err", ":=", "r", ".", "st", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", "\n", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "names", ".", "ReadableString", "(", "entity", ")", ")", "\n", "}" ]
// ImportRemoteEntity adds an entity to the remote entities collection // with the specified opaque token. // If the entity already exists, its token will be overwritten. // This method assumes that the provided token is unique within the // source model, and does not perform any uniqueness checks on it.
[ "ImportRemoteEntity", "adds", "an", "entity", "to", "the", "remote", "entities", "collection", "with", "the", "specified", "opaque", "token", ".", "If", "the", "entity", "already", "exists", "its", "token", "will", "be", "overwritten", ".", "This", "method", "assumes", "that", "the", "provided", "token", "is", "unique", "within", "the", "source", "model", "and", "does", "not", "perform", "any", "uniqueness", "checks", "on", "it", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/remoteentities.go#L101-L123
157,030
juju/juju
state/remoteentities.go
RemoveRemoteEntity
func (r *RemoteEntities) RemoveRemoteEntity(entity names.Tag) error { ops := func(attempt int) ([]txn.Op, error) { ops := r.removeRemoteEntityOps(entity) return ops, nil } return r.st.db().Run(ops) }
go
func (r *RemoteEntities) RemoveRemoteEntity(entity names.Tag) error { ops := func(attempt int) ([]txn.Op, error) { ops := r.removeRemoteEntityOps(entity) return ops, nil } return r.st.db().Run(ops) }
[ "func", "(", "r", "*", "RemoteEntities", ")", "RemoveRemoteEntity", "(", "entity", "names", ".", "Tag", ")", "error", "{", "ops", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "ops", ":=", "r", ".", "removeRemoteEntityOps", "(", "entity", ")", "\n", "return", "ops", ",", "nil", "\n", "}", "\n", "return", "r", ".", "st", ".", "db", "(", ")", ".", "Run", "(", "ops", ")", "\n", "}" ]
// RemoveRemoteEntity removes the entity from the remote entities collection, // and releases the token if the entity belongs to the local model.
[ "RemoveRemoteEntity", "removes", "the", "entity", "from", "the", "remote", "entities", "collection", "and", "releases", "the", "token", "if", "the", "entity", "belongs", "to", "the", "local", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/remoteentities.go#L138-L144
157,031
juju/juju
state/remoteentities.go
removeRemoteEntityOps
func (r *RemoteEntities) removeRemoteEntityOps(entity names.Tag) []txn.Op { ops := []txn.Op{{ C: remoteEntitiesC, Id: entity.String(), Remove: true, }} return ops }
go
func (r *RemoteEntities) removeRemoteEntityOps(entity names.Tag) []txn.Op { ops := []txn.Op{{ C: remoteEntitiesC, Id: entity.String(), Remove: true, }} return ops }
[ "func", "(", "r", "*", "RemoteEntities", ")", "removeRemoteEntityOps", "(", "entity", "names", ".", "Tag", ")", "[", "]", "txn", ".", "Op", "{", "ops", ":=", "[", "]", "txn", ".", "Op", "{", "{", "C", ":", "remoteEntitiesC", ",", "Id", ":", "entity", ".", "String", "(", ")", ",", "Remove", ":", "true", ",", "}", "}", "\n", "return", "ops", "\n", "}" ]
// removeRemoteEntityOpa returns the txn.Ops to remove the remote entity // document. It also removes any token document for exported entities.
[ "removeRemoteEntityOpa", "returns", "the", "txn", ".", "Ops", "to", "remove", "the", "remote", "entity", "document", ".", "It", "also", "removes", "any", "token", "document", "for", "exported", "entities", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/remoteentities.go#L148-L155
157,032
juju/juju
state/remoteentities.go
GetToken
func (r *RemoteEntities) GetToken(entity names.Tag) (string, error) { remoteEntities, closer := r.st.db().GetCollection(remoteEntitiesC) defer closer() var doc remoteEntityDoc err := remoteEntities.FindId(entity.String()).One(&doc) if err == mgo.ErrNotFound { return "", errors.NotFoundf("token for %s", names.ReadableString(entity)) } if err != nil { return "", errors.Annotatef(err, "reading token for %s", names.ReadableString(entity)) } return doc.Token, nil }
go
func (r *RemoteEntities) GetToken(entity names.Tag) (string, error) { remoteEntities, closer := r.st.db().GetCollection(remoteEntitiesC) defer closer() var doc remoteEntityDoc err := remoteEntities.FindId(entity.String()).One(&doc) if err == mgo.ErrNotFound { return "", errors.NotFoundf("token for %s", names.ReadableString(entity)) } if err != nil { return "", errors.Annotatef(err, "reading token for %s", names.ReadableString(entity)) } return doc.Token, nil }
[ "func", "(", "r", "*", "RemoteEntities", ")", "GetToken", "(", "entity", "names", ".", "Tag", ")", "(", "string", ",", "error", ")", "{", "remoteEntities", ",", "closer", ":=", "r", ".", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "remoteEntitiesC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "var", "doc", "remoteEntityDoc", "\n", "err", ":=", "remoteEntities", ".", "FindId", "(", "entity", ".", "String", "(", ")", ")", ".", "One", "(", "&", "doc", ")", "\n", "if", "err", "==", "mgo", ".", "ErrNotFound", "{", "return", "\"", "\"", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "names", ".", "ReadableString", "(", "entity", ")", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "names", ".", "ReadableString", "(", "entity", ")", ")", "\n", "}", "\n", "return", "doc", ".", "Token", ",", "nil", "\n", "}" ]
// GetToken returns the token associated with the entity with the given tag // and model.
[ "GetToken", "returns", "the", "token", "associated", "with", "the", "entity", "with", "the", "given", "tag", "and", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/remoteentities.go#L159-L172
157,033
juju/juju
state/remoteentities.go
GetMacaroon
func (r *RemoteEntities) GetMacaroon(entity names.Tag) (*macaroon.Macaroon, error) { doc, err := r.remoteEntityDoc(entity) if err == mgo.ErrNotFound { return nil, errors.NotFoundf( "macaroon for %s", names.ReadableString(entity), ) } if err != nil { return nil, errors.Annotatef( err, "reading macaroon for %s", names.ReadableString(entity), ) } if doc.Macaroon == "" { return nil, nil } var mac macaroon.Macaroon if err := json.Unmarshal([]byte(doc.Macaroon), &mac); err != nil { return nil, errors.Annotatef(err, "unmarshalling macaroon for %s", names.ReadableString(entity)) } return &mac, nil }
go
func (r *RemoteEntities) GetMacaroon(entity names.Tag) (*macaroon.Macaroon, error) { doc, err := r.remoteEntityDoc(entity) if err == mgo.ErrNotFound { return nil, errors.NotFoundf( "macaroon for %s", names.ReadableString(entity), ) } if err != nil { return nil, errors.Annotatef( err, "reading macaroon for %s", names.ReadableString(entity), ) } if doc.Macaroon == "" { return nil, nil } var mac macaroon.Macaroon if err := json.Unmarshal([]byte(doc.Macaroon), &mac); err != nil { return nil, errors.Annotatef(err, "unmarshalling macaroon for %s", names.ReadableString(entity)) } return &mac, nil }
[ "func", "(", "r", "*", "RemoteEntities", ")", "GetMacaroon", "(", "entity", "names", ".", "Tag", ")", "(", "*", "macaroon", ".", "Macaroon", ",", "error", ")", "{", "doc", ",", "err", ":=", "r", ".", "remoteEntityDoc", "(", "entity", ")", "\n", "if", "err", "==", "mgo", ".", "ErrNotFound", "{", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "names", ".", "ReadableString", "(", "entity", ")", ",", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "names", ".", "ReadableString", "(", "entity", ")", ",", ")", "\n", "}", "\n", "if", "doc", ".", "Macaroon", "==", "\"", "\"", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "var", "mac", "macaroon", ".", "Macaroon", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "doc", ".", "Macaroon", ")", ",", "&", "mac", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "names", ".", "ReadableString", "(", "entity", ")", ")", "\n", "}", "\n", "return", "&", "mac", ",", "nil", "\n", "}" ]
// GetMacaroon returns the macaroon associated with the entity with the given tag // and model.
[ "GetMacaroon", "returns", "the", "macaroon", "associated", "with", "the", "entity", "with", "the", "given", "tag", "and", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/remoteentities.go#L185-L205
157,034
juju/juju
state/remoteentities.go
SaveMacaroon
func (r *RemoteEntities) SaveMacaroon(entity names.Tag, mac *macaroon.Macaroon) error { var macJSON string if mac != nil { b, err := json.Marshal(mac) if err != nil { return errors.Trace(err) } macJSON = string(b) } buildTxn := func(attempt int) ([]txn.Op, error) { ops := []txn.Op{{ C: remoteEntitiesC, Id: entity.String(), Assert: txn.DocExists, Update: bson.D{ {"$set", bson.D{{"macaroon", macJSON}}}, }, }} return ops, nil } return r.st.db().Run(buildTxn) }
go
func (r *RemoteEntities) SaveMacaroon(entity names.Tag, mac *macaroon.Macaroon) error { var macJSON string if mac != nil { b, err := json.Marshal(mac) if err != nil { return errors.Trace(err) } macJSON = string(b) } buildTxn := func(attempt int) ([]txn.Op, error) { ops := []txn.Op{{ C: remoteEntitiesC, Id: entity.String(), Assert: txn.DocExists, Update: bson.D{ {"$set", bson.D{{"macaroon", macJSON}}}, }, }} return ops, nil } return r.st.db().Run(buildTxn) }
[ "func", "(", "r", "*", "RemoteEntities", ")", "SaveMacaroon", "(", "entity", "names", ".", "Tag", ",", "mac", "*", "macaroon", ".", "Macaroon", ")", "error", "{", "var", "macJSON", "string", "\n", "if", "mac", "!=", "nil", "{", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "mac", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "macJSON", "=", "string", "(", "b", ")", "\n", "}", "\n", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "ops", ":=", "[", "]", "txn", ".", "Op", "{", "{", "C", ":", "remoteEntitiesC", ",", "Id", ":", "entity", ".", "String", "(", ")", ",", "Assert", ":", "txn", ".", "DocExists", ",", "Update", ":", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "macJSON", "}", "}", "}", ",", "}", ",", "}", "}", "\n", "return", "ops", ",", "nil", "\n", "}", "\n", "return", "r", ".", "st", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", "\n", "}" ]
// SaveMacaroon saves the given macaroon for the specified entity.
[ "SaveMacaroon", "saves", "the", "given", "macaroon", "for", "the", "specified", "entity", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/remoteentities.go#L208-L229
157,035
juju/juju
state/remoteentities.go
GetRemoteEntity
func (r *RemoteEntities) GetRemoteEntity(token string) (names.Tag, error) { remoteEntities, closer := r.st.db().GetCollection(remoteEntitiesC) defer closer() var doc remoteEntityDoc err := remoteEntities.Find(bson.D{ {"token", token}, }).One(&doc) if err == mgo.ErrNotFound { return nil, errors.NotFoundf("entity for token %q", token) } if err != nil { return nil, errors.Annotatef(err, "getting entity for token %q", token) } return names.ParseTag(r.st.localID(doc.DocID)) }
go
func (r *RemoteEntities) GetRemoteEntity(token string) (names.Tag, error) { remoteEntities, closer := r.st.db().GetCollection(remoteEntitiesC) defer closer() var doc remoteEntityDoc err := remoteEntities.Find(bson.D{ {"token", token}, }).One(&doc) if err == mgo.ErrNotFound { return nil, errors.NotFoundf("entity for token %q", token) } if err != nil { return nil, errors.Annotatef(err, "getting entity for token %q", token) } return names.ParseTag(r.st.localID(doc.DocID)) }
[ "func", "(", "r", "*", "RemoteEntities", ")", "GetRemoteEntity", "(", "token", "string", ")", "(", "names", ".", "Tag", ",", "error", ")", "{", "remoteEntities", ",", "closer", ":=", "r", ".", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "remoteEntitiesC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "var", "doc", "remoteEntityDoc", "\n", "err", ":=", "remoteEntities", ".", "Find", "(", "bson", ".", "D", "{", "{", "\"", "\"", ",", "token", "}", ",", "}", ")", ".", "One", "(", "&", "doc", ")", "\n", "if", "err", "==", "mgo", ".", "ErrNotFound", "{", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "token", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "token", ")", "\n", "}", "\n", "return", "names", ".", "ParseTag", "(", "r", ".", "st", ".", "localID", "(", "doc", ".", "DocID", ")", ")", "\n", "}" ]
// GetRemoteEntity returns the tag of the entity associated with the given token.
[ "GetRemoteEntity", "returns", "the", "tag", "of", "the", "entity", "associated", "with", "the", "given", "token", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/remoteentities.go#L232-L247
157,036
juju/juju
state/upgrade.go
ControllersReady
func (info *UpgradeInfo) ControllersReady() []string { result := make([]string, len(info.doc.ControllersReady)) copy(result, info.doc.ControllersReady) return result }
go
func (info *UpgradeInfo) ControllersReady() []string { result := make([]string, len(info.doc.ControllersReady)) copy(result, info.doc.ControllersReady) return result }
[ "func", "(", "info", "*", "UpgradeInfo", ")", "ControllersReady", "(", ")", "[", "]", "string", "{", "result", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "info", ".", "doc", ".", "ControllersReady", ")", ")", "\n", "copy", "(", "result", ",", "info", ".", "doc", ".", "ControllersReady", ")", "\n", "return", "result", "\n", "}" ]
// ControllersReady returns the machine ids for controllers that // have signalled that they are ready for upgrade.
[ "ControllersReady", "returns", "the", "machine", "ids", "for", "controllers", "that", "have", "signalled", "that", "they", "are", "ready", "for", "upgrade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrade.go#L118-L122
157,037
juju/juju
state/upgrade.go
Refresh
func (info *UpgradeInfo) Refresh() error { doc, err := currentUpgradeInfoDoc(info.st) if err != nil { return errors.Trace(err) } info.doc = *doc return nil }
go
func (info *UpgradeInfo) Refresh() error { doc, err := currentUpgradeInfoDoc(info.st) if err != nil { return errors.Trace(err) } info.doc = *doc return nil }
[ "func", "(", "info", "*", "UpgradeInfo", ")", "Refresh", "(", ")", "error", "{", "doc", ",", "err", ":=", "currentUpgradeInfoDoc", "(", "info", ".", "st", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "info", ".", "doc", "=", "*", "doc", "\n", "return", "nil", "\n", "}" ]
// Refresh updates the contents of the UpgradeInfo from underlying state.
[ "Refresh", "updates", "the", "contents", "of", "the", "UpgradeInfo", "from", "underlying", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrade.go#L133-L140
157,038
juju/juju
state/upgrade.go
AllProvisionedControllersReady
func (info *UpgradeInfo) AllProvisionedControllersReady() (bool, error) { provisioned, err := info.getProvisionedControllers() if err != nil { return false, errors.Trace(err) } ready := set.NewStrings(info.doc.ControllersReady...) missing := set.NewStrings(provisioned...).Difference(ready) return missing.IsEmpty(), nil }
go
func (info *UpgradeInfo) AllProvisionedControllersReady() (bool, error) { provisioned, err := info.getProvisionedControllers() if err != nil { return false, errors.Trace(err) } ready := set.NewStrings(info.doc.ControllersReady...) missing := set.NewStrings(provisioned...).Difference(ready) return missing.IsEmpty(), nil }
[ "func", "(", "info", "*", "UpgradeInfo", ")", "AllProvisionedControllersReady", "(", ")", "(", "bool", ",", "error", ")", "{", "provisioned", ",", "err", ":=", "info", ".", "getProvisionedControllers", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "ready", ":=", "set", ".", "NewStrings", "(", "info", ".", "doc", ".", "ControllersReady", "...", ")", "\n", "missing", ":=", "set", ".", "NewStrings", "(", "provisioned", "...", ")", ".", "Difference", "(", "ready", ")", "\n", "return", "missing", ".", "IsEmpty", "(", ")", ",", "nil", "\n", "}" ]
// AllProvisionedControllersReady returns true if and only if all controllers // that have been started by the provisioner have called EnsureUpgradeInfo with // matching versions. // // When this returns true the master state controller can begin it's // own upgrade.
[ "AllProvisionedControllersReady", "returns", "true", "if", "and", "only", "if", "all", "controllers", "that", "have", "been", "started", "by", "the", "provisioner", "have", "called", "EnsureUpgradeInfo", "with", "matching", "versions", ".", "When", "this", "returns", "true", "the", "master", "state", "controller", "can", "begin", "it", "s", "own", "upgrade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrade.go#L154-L162
157,039
juju/juju
state/upgrade.go
upgradeStatusHistoryAndOps
func upgradeStatusHistoryAndOps(mb modelBackend, upgradeStatus UpgradeStatus, now time.Time) ([]txn.Op, error) { var modelStatus status.Status var msg string switch upgradeStatus { case UpgradeComplete: modelStatus = status.Available msg = fmt.Sprintf("upgraded on %q", now.UTC().Format(time.RFC3339)) case UpgradeRunning: modelStatus = status.Busy msg = fmt.Sprintf("upgrade in progress since %q", now.UTC().Format(time.RFC3339)) case UpgradeAborted: modelStatus = status.Available msg = fmt.Sprintf("last upgrade aborted on %q", now.UTC().Format(time.RFC3339)) default: return []txn.Op{}, nil } doc := statusDoc{ Status: modelStatus, StatusInfo: msg, Updated: now.UnixNano(), } ops, err := statusSetOps(mb.db(), doc, modelGlobalKey) if err != nil { return nil, errors.Trace(err) } probablyUpdateStatusHistory(mb.db(), modelGlobalKey, doc) return ops, nil }
go
func upgradeStatusHistoryAndOps(mb modelBackend, upgradeStatus UpgradeStatus, now time.Time) ([]txn.Op, error) { var modelStatus status.Status var msg string switch upgradeStatus { case UpgradeComplete: modelStatus = status.Available msg = fmt.Sprintf("upgraded on %q", now.UTC().Format(time.RFC3339)) case UpgradeRunning: modelStatus = status.Busy msg = fmt.Sprintf("upgrade in progress since %q", now.UTC().Format(time.RFC3339)) case UpgradeAborted: modelStatus = status.Available msg = fmt.Sprintf("last upgrade aborted on %q", now.UTC().Format(time.RFC3339)) default: return []txn.Op{}, nil } doc := statusDoc{ Status: modelStatus, StatusInfo: msg, Updated: now.UnixNano(), } ops, err := statusSetOps(mb.db(), doc, modelGlobalKey) if err != nil { return nil, errors.Trace(err) } probablyUpdateStatusHistory(mb.db(), modelGlobalKey, doc) return ops, nil }
[ "func", "upgradeStatusHistoryAndOps", "(", "mb", "modelBackend", ",", "upgradeStatus", "UpgradeStatus", ",", "now", "time", ".", "Time", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "var", "modelStatus", "status", ".", "Status", "\n", "var", "msg", "string", "\n", "switch", "upgradeStatus", "{", "case", "UpgradeComplete", ":", "modelStatus", "=", "status", ".", "Available", "\n", "msg", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "now", ".", "UTC", "(", ")", ".", "Format", "(", "time", ".", "RFC3339", ")", ")", "\n", "case", "UpgradeRunning", ":", "modelStatus", "=", "status", ".", "Busy", "\n", "msg", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "now", ".", "UTC", "(", ")", ".", "Format", "(", "time", ".", "RFC3339", ")", ")", "\n", "case", "UpgradeAborted", ":", "modelStatus", "=", "status", ".", "Available", "\n", "msg", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "now", ".", "UTC", "(", ")", ".", "Format", "(", "time", ".", "RFC3339", ")", ")", "\n", "default", ":", "return", "[", "]", "txn", ".", "Op", "{", "}", ",", "nil", "\n", "}", "\n", "doc", ":=", "statusDoc", "{", "Status", ":", "modelStatus", ",", "StatusInfo", ":", "msg", ",", "Updated", ":", "now", ".", "UnixNano", "(", ")", ",", "}", "\n", "ops", ",", "err", ":=", "statusSetOps", "(", "mb", ".", "db", "(", ")", ",", "doc", ",", "modelGlobalKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "probablyUpdateStatusHistory", "(", "mb", ".", "db", "(", ")", ",", "modelGlobalKey", ",", "doc", ")", "\n", "return", "ops", ",", "nil", "\n", "}" ]
// upgradeStatusHistoryAndOps sets the model's status history and returns ops for // setting model status according to the UpgradeStatus.
[ "upgradeStatusHistoryAndOps", "sets", "the", "model", "s", "status", "history", "and", "returns", "ops", "for", "setting", "model", "status", "according", "to", "the", "UpgradeStatus", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrade.go#L194-L221
157,040
juju/juju
state/upgrade.go
SetStatus
func (info *UpgradeInfo) SetStatus(status UpgradeStatus) error { var assertSane bson.D switch status { case UpgradePending, UpgradeComplete, UpgradeAborted: return errors.Errorf("cannot explicitly set upgrade status to \"%s\"", status) case UpgradeRunning: assertSane = bson.D{{"status", bson.D{{"$in", []UpgradeStatus{UpgradePending, UpgradeRunning}, }}}} case UpgradeFinishing: assertSane = bson.D{{"status", bson.D{{"$in", []UpgradeStatus{UpgradeRunning, UpgradeFinishing}, }}}} default: return errors.Errorf("unknown upgrade status: %s", status) } if info.doc.Id != currentUpgradeId { return errors.New("cannot set status on non-current upgrade") } ops := []txn.Op{{ C: upgradeInfoC, Id: currentUpgradeId, Assert: append(bson.D{{ "previousVersion", info.doc.PreviousVersion, }, { "targetVersion", info.doc.TargetVersion, }}, assertSane...), Update: bson.D{{"$set", bson.D{{"status", status}}}}, }} extraOps, err := upgradeStatusHistoryAndOps(info.st, status, info.st.clock().Now()) if err != nil { return errors.Trace(err) } if len(extraOps) > 0 { ops = append(ops, extraOps...) } err = info.st.db().RunTransaction(ops) if err == txn.ErrAborted { return errors.Errorf("cannot set upgrade status to %q: Another "+ "status change may have occurred concurrently", status) } return errors.Annotate(err, "cannot set upgrade status") }
go
func (info *UpgradeInfo) SetStatus(status UpgradeStatus) error { var assertSane bson.D switch status { case UpgradePending, UpgradeComplete, UpgradeAborted: return errors.Errorf("cannot explicitly set upgrade status to \"%s\"", status) case UpgradeRunning: assertSane = bson.D{{"status", bson.D{{"$in", []UpgradeStatus{UpgradePending, UpgradeRunning}, }}}} case UpgradeFinishing: assertSane = bson.D{{"status", bson.D{{"$in", []UpgradeStatus{UpgradeRunning, UpgradeFinishing}, }}}} default: return errors.Errorf("unknown upgrade status: %s", status) } if info.doc.Id != currentUpgradeId { return errors.New("cannot set status on non-current upgrade") } ops := []txn.Op{{ C: upgradeInfoC, Id: currentUpgradeId, Assert: append(bson.D{{ "previousVersion", info.doc.PreviousVersion, }, { "targetVersion", info.doc.TargetVersion, }}, assertSane...), Update: bson.D{{"$set", bson.D{{"status", status}}}}, }} extraOps, err := upgradeStatusHistoryAndOps(info.st, status, info.st.clock().Now()) if err != nil { return errors.Trace(err) } if len(extraOps) > 0 { ops = append(ops, extraOps...) } err = info.st.db().RunTransaction(ops) if err == txn.ErrAborted { return errors.Errorf("cannot set upgrade status to %q: Another "+ "status change may have occurred concurrently", status) } return errors.Annotate(err, "cannot set upgrade status") }
[ "func", "(", "info", "*", "UpgradeInfo", ")", "SetStatus", "(", "status", "UpgradeStatus", ")", "error", "{", "var", "assertSane", "bson", ".", "D", "\n", "switch", "status", "{", "case", "UpgradePending", ",", "UpgradeComplete", ",", "UpgradeAborted", ":", "return", "errors", ".", "Errorf", "(", "\"", "\\\"", "\\\"", "\"", ",", "status", ")", "\n", "case", "UpgradeRunning", ":", "assertSane", "=", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "[", "]", "UpgradeStatus", "{", "UpgradePending", ",", "UpgradeRunning", "}", ",", "}", "}", "}", "}", "\n", "case", "UpgradeFinishing", ":", "assertSane", "=", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "[", "]", "UpgradeStatus", "{", "UpgradeRunning", ",", "UpgradeFinishing", "}", ",", "}", "}", "}", "}", "\n", "default", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "status", ")", "\n", "}", "\n", "if", "info", ".", "doc", ".", "Id", "!=", "currentUpgradeId", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "ops", ":=", "[", "]", "txn", ".", "Op", "{", "{", "C", ":", "upgradeInfoC", ",", "Id", ":", "currentUpgradeId", ",", "Assert", ":", "append", "(", "bson", ".", "D", "{", "{", "\"", "\"", ",", "info", ".", "doc", ".", "PreviousVersion", ",", "}", ",", "{", "\"", "\"", ",", "info", ".", "doc", ".", "TargetVersion", ",", "}", "}", ",", "assertSane", "...", ")", ",", "Update", ":", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "status", "}", "}", "}", "}", ",", "}", "}", "\n\n", "extraOps", ",", "err", ":=", "upgradeStatusHistoryAndOps", "(", "info", ".", "st", ",", "status", ",", "info", ".", "st", ".", "clock", "(", ")", ".", "Now", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "extraOps", ")", ">", "0", "{", "ops", "=", "append", "(", "ops", ",", "extraOps", "...", ")", "\n", "}", "\n", "err", "=", "info", ".", "st", ".", "db", "(", ")", ".", "RunTransaction", "(", "ops", ")", "\n", "if", "err", "==", "txn", ".", "ErrAborted", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "status", ")", "\n", "}", "\n", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}" ]
// SetStatus sets the status of the current upgrade. Checks are made // to ensure that status changes are performed in the correct order.
[ "SetStatus", "sets", "the", "status", "of", "the", "current", "upgrade", ".", "Checks", "are", "made", "to", "ensure", "that", "status", "changes", "are", "performed", "in", "the", "correct", "order", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrade.go#L225-L269
157,041
juju/juju
state/upgrade.go
EnsureUpgradeInfo
func (st *State) EnsureUpgradeInfo(machineId string, previousVersion, targetVersion version.Number) (*UpgradeInfo, error) { assertSanity, err := checkUpgradeInfoSanity(st, machineId, previousVersion, targetVersion) if err != nil { return nil, errors.Trace(err) } doc := upgradeInfoDoc{ Id: currentUpgradeId, PreviousVersion: previousVersion, TargetVersion: targetVersion, Status: UpgradePending, Started: st.clock().Now().UTC(), ControllersReady: []string{machineId}, } machine, err := st.Machine(machineId) if err != nil { return nil, errors.Trace(err) } ops := []txn.Op{{ C: upgradeInfoC, Id: currentUpgradeId, Assert: txn.DocMissing, Insert: doc, }, { C: instanceDataC, Id: machine.doc.DocID, Assert: txn.DocExists, }} if err := st.runRawTransaction(ops); err == nil { return &UpgradeInfo{st: st, doc: doc}, nil } else if err != txn.ErrAborted { return nil, errors.Annotate(err, "cannot create upgrade info") } if provisioned, err := st.isMachineProvisioned(machineId); err != nil { return nil, errors.Trace(err) } else if !provisioned { return nil, errors.Errorf( "machine %s is not provisioned and should not be participating in upgrades", machineId) } if info, err := ensureUpgradeInfoUpdated(st, machineId, previousVersion, targetVersion); err == nil { return info, nil } else if errors.Cause(err) != errUpgradeInfoNotUpdated { return nil, errors.Trace(err) } ops = []txn.Op{{ C: upgradeInfoC, Id: currentUpgradeId, Assert: assertSanity, Update: bson.D{{ "$addToSet", bson.D{{"controllersReady", machineId}}, }}, }} switch err := st.db().RunTransaction(ops); err { case nil: return ensureUpgradeInfoUpdated(st, machineId, previousVersion, targetVersion) case txn.ErrAborted: return nil, errors.New("upgrade info changed during update") } return nil, errors.Annotate(err, "cannot update upgrade info") }
go
func (st *State) EnsureUpgradeInfo(machineId string, previousVersion, targetVersion version.Number) (*UpgradeInfo, error) { assertSanity, err := checkUpgradeInfoSanity(st, machineId, previousVersion, targetVersion) if err != nil { return nil, errors.Trace(err) } doc := upgradeInfoDoc{ Id: currentUpgradeId, PreviousVersion: previousVersion, TargetVersion: targetVersion, Status: UpgradePending, Started: st.clock().Now().UTC(), ControllersReady: []string{machineId}, } machine, err := st.Machine(machineId) if err != nil { return nil, errors.Trace(err) } ops := []txn.Op{{ C: upgradeInfoC, Id: currentUpgradeId, Assert: txn.DocMissing, Insert: doc, }, { C: instanceDataC, Id: machine.doc.DocID, Assert: txn.DocExists, }} if err := st.runRawTransaction(ops); err == nil { return &UpgradeInfo{st: st, doc: doc}, nil } else if err != txn.ErrAborted { return nil, errors.Annotate(err, "cannot create upgrade info") } if provisioned, err := st.isMachineProvisioned(machineId); err != nil { return nil, errors.Trace(err) } else if !provisioned { return nil, errors.Errorf( "machine %s is not provisioned and should not be participating in upgrades", machineId) } if info, err := ensureUpgradeInfoUpdated(st, machineId, previousVersion, targetVersion); err == nil { return info, nil } else if errors.Cause(err) != errUpgradeInfoNotUpdated { return nil, errors.Trace(err) } ops = []txn.Op{{ C: upgradeInfoC, Id: currentUpgradeId, Assert: assertSanity, Update: bson.D{{ "$addToSet", bson.D{{"controllersReady", machineId}}, }}, }} switch err := st.db().RunTransaction(ops); err { case nil: return ensureUpgradeInfoUpdated(st, machineId, previousVersion, targetVersion) case txn.ErrAborted: return nil, errors.New("upgrade info changed during update") } return nil, errors.Annotate(err, "cannot update upgrade info") }
[ "func", "(", "st", "*", "State", ")", "EnsureUpgradeInfo", "(", "machineId", "string", ",", "previousVersion", ",", "targetVersion", "version", ".", "Number", ")", "(", "*", "UpgradeInfo", ",", "error", ")", "{", "assertSanity", ",", "err", ":=", "checkUpgradeInfoSanity", "(", "st", ",", "machineId", ",", "previousVersion", ",", "targetVersion", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "doc", ":=", "upgradeInfoDoc", "{", "Id", ":", "currentUpgradeId", ",", "PreviousVersion", ":", "previousVersion", ",", "TargetVersion", ":", "targetVersion", ",", "Status", ":", "UpgradePending", ",", "Started", ":", "st", ".", "clock", "(", ")", ".", "Now", "(", ")", ".", "UTC", "(", ")", ",", "ControllersReady", ":", "[", "]", "string", "{", "machineId", "}", ",", "}", "\n\n", "machine", ",", "err", ":=", "st", ".", "Machine", "(", "machineId", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "ops", ":=", "[", "]", "txn", ".", "Op", "{", "{", "C", ":", "upgradeInfoC", ",", "Id", ":", "currentUpgradeId", ",", "Assert", ":", "txn", ".", "DocMissing", ",", "Insert", ":", "doc", ",", "}", ",", "{", "C", ":", "instanceDataC", ",", "Id", ":", "machine", ".", "doc", ".", "DocID", ",", "Assert", ":", "txn", ".", "DocExists", ",", "}", "}", "\n", "if", "err", ":=", "st", ".", "runRawTransaction", "(", "ops", ")", ";", "err", "==", "nil", "{", "return", "&", "UpgradeInfo", "{", "st", ":", "st", ",", "doc", ":", "doc", "}", ",", "nil", "\n", "}", "else", "if", "err", "!=", "txn", ".", "ErrAborted", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "provisioned", ",", "err", ":=", "st", ".", "isMachineProvisioned", "(", "machineId", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "else", "if", "!", "provisioned", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "machineId", ")", "\n", "}", "\n\n", "if", "info", ",", "err", ":=", "ensureUpgradeInfoUpdated", "(", "st", ",", "machineId", ",", "previousVersion", ",", "targetVersion", ")", ";", "err", "==", "nil", "{", "return", "info", ",", "nil", "\n", "}", "else", "if", "errors", ".", "Cause", "(", "err", ")", "!=", "errUpgradeInfoNotUpdated", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "ops", "=", "[", "]", "txn", ".", "Op", "{", "{", "C", ":", "upgradeInfoC", ",", "Id", ":", "currentUpgradeId", ",", "Assert", ":", "assertSanity", ",", "Update", ":", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "machineId", "}", "}", ",", "}", "}", ",", "}", "}", "\n", "switch", "err", ":=", "st", ".", "db", "(", ")", ".", "RunTransaction", "(", "ops", ")", ";", "err", "{", "case", "nil", ":", "return", "ensureUpgradeInfoUpdated", "(", "st", ",", "machineId", ",", "previousVersion", ",", "targetVersion", ")", "\n", "case", "txn", ".", "ErrAborted", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}" ]
// EnsureUpgradeInfo returns an UpgradeInfo describing a current upgrade between the // supplied versions. If a matching upgrade is in progress, that upgrade is returned; // if there's a mismatch, an error is returned. The supplied machine id must correspond // to a current controller.
[ "EnsureUpgradeInfo", "returns", "an", "UpgradeInfo", "describing", "a", "current", "upgrade", "between", "the", "supplied", "versions", ".", "If", "a", "matching", "upgrade", "is", "in", "progress", "that", "upgrade", "is", "returned", ";", "if", "there", "s", "a", "mismatch", "an", "error", "is", "returned", ".", "The", "supplied", "machine", "id", "must", "correspond", "to", "a", "current", "controller", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrade.go#L275-L341
157,042
juju/juju
state/upgrade.go
SetControllerDone
func (info *UpgradeInfo) SetControllerDone(machineId string) error { assertSanity, err := checkUpgradeInfoSanity(info.st, machineId, info.doc.PreviousVersion, info.doc.TargetVersion) if err != nil { return errors.Trace(err) } buildTxn := func(attempt int) ([]txn.Op, error) { doc, err := currentUpgradeInfoDoc(info.st) if errors.IsNotFound(err) { return nil, jujutxn.ErrNoOperations } else if err != nil { return nil, errors.Trace(err) } switch doc.Status { case UpgradePending, UpgradeRunning: return nil, errors.New("upgrade has not yet run") } controllersDone := set.NewStrings(doc.ControllersDone...) if controllersDone.Contains(machineId) { return nil, jujutxn.ErrNoOperations } controllersDone.Add(machineId) controllersReady := set.NewStrings(doc.ControllersReady...) controllersNotDone := controllersReady.Difference(controllersDone) if controllersNotDone.IsEmpty() { // This is the last controller. Archive the current // upgradeInfo document. doc.ControllersDone = controllersDone.SortedValues() ops := info.makeArchiveOps(doc, UpgradeComplete) extraOps, err := upgradeStatusHistoryAndOps(info.st, UpgradeComplete, info.st.clock().Now()) if err != nil { return nil, errors.Trace(err) } if len(extraOps) > 0 { ops = append(ops, extraOps...) } return ops, nil } return []txn.Op{{ C: upgradeInfoC, Id: currentUpgradeId, // This is not the last controller, but we need to be // sure it still isn't when we run this. Assert: append(assertSanity, bson.D{{ "controllersDone", bson.D{{"$nin", controllersNotDone.Values()}}, }}...), Update: bson.D{{"$addToSet", bson.D{{"controllersDone", machineId}}}}, }}, nil } err = info.st.db().Run(buildTxn) return errors.Annotate(err, "cannot complete upgrade") }
go
func (info *UpgradeInfo) SetControllerDone(machineId string) error { assertSanity, err := checkUpgradeInfoSanity(info.st, machineId, info.doc.PreviousVersion, info.doc.TargetVersion) if err != nil { return errors.Trace(err) } buildTxn := func(attempt int) ([]txn.Op, error) { doc, err := currentUpgradeInfoDoc(info.st) if errors.IsNotFound(err) { return nil, jujutxn.ErrNoOperations } else if err != nil { return nil, errors.Trace(err) } switch doc.Status { case UpgradePending, UpgradeRunning: return nil, errors.New("upgrade has not yet run") } controllersDone := set.NewStrings(doc.ControllersDone...) if controllersDone.Contains(machineId) { return nil, jujutxn.ErrNoOperations } controllersDone.Add(machineId) controllersReady := set.NewStrings(doc.ControllersReady...) controllersNotDone := controllersReady.Difference(controllersDone) if controllersNotDone.IsEmpty() { // This is the last controller. Archive the current // upgradeInfo document. doc.ControllersDone = controllersDone.SortedValues() ops := info.makeArchiveOps(doc, UpgradeComplete) extraOps, err := upgradeStatusHistoryAndOps(info.st, UpgradeComplete, info.st.clock().Now()) if err != nil { return nil, errors.Trace(err) } if len(extraOps) > 0 { ops = append(ops, extraOps...) } return ops, nil } return []txn.Op{{ C: upgradeInfoC, Id: currentUpgradeId, // This is not the last controller, but we need to be // sure it still isn't when we run this. Assert: append(assertSanity, bson.D{{ "controllersDone", bson.D{{"$nin", controllersNotDone.Values()}}, }}...), Update: bson.D{{"$addToSet", bson.D{{"controllersDone", machineId}}}}, }}, nil } err = info.st.db().Run(buildTxn) return errors.Annotate(err, "cannot complete upgrade") }
[ "func", "(", "info", "*", "UpgradeInfo", ")", "SetControllerDone", "(", "machineId", "string", ")", "error", "{", "assertSanity", ",", "err", ":=", "checkUpgradeInfoSanity", "(", "info", ".", "st", ",", "machineId", ",", "info", ".", "doc", ".", "PreviousVersion", ",", "info", ".", "doc", ".", "TargetVersion", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "doc", ",", "err", ":=", "currentUpgradeInfoDoc", "(", "info", ".", "st", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "jujutxn", ".", "ErrNoOperations", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "switch", "doc", ".", "Status", "{", "case", "UpgradePending", ",", "UpgradeRunning", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "controllersDone", ":=", "set", ".", "NewStrings", "(", "doc", ".", "ControllersDone", "...", ")", "\n", "if", "controllersDone", ".", "Contains", "(", "machineId", ")", "{", "return", "nil", ",", "jujutxn", ".", "ErrNoOperations", "\n", "}", "\n", "controllersDone", ".", "Add", "(", "machineId", ")", "\n\n", "controllersReady", ":=", "set", ".", "NewStrings", "(", "doc", ".", "ControllersReady", "...", ")", "\n", "controllersNotDone", ":=", "controllersReady", ".", "Difference", "(", "controllersDone", ")", "\n", "if", "controllersNotDone", ".", "IsEmpty", "(", ")", "{", "// This is the last controller. Archive the current", "// upgradeInfo document.", "doc", ".", "ControllersDone", "=", "controllersDone", ".", "SortedValues", "(", ")", "\n\n", "ops", ":=", "info", ".", "makeArchiveOps", "(", "doc", ",", "UpgradeComplete", ")", "\n", "extraOps", ",", "err", ":=", "upgradeStatusHistoryAndOps", "(", "info", ".", "st", ",", "UpgradeComplete", ",", "info", ".", "st", ".", "clock", "(", ")", ".", "Now", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "extraOps", ")", ">", "0", "{", "ops", "=", "append", "(", "ops", ",", "extraOps", "...", ")", "\n", "}", "\n\n", "return", "ops", ",", "nil", "\n", "}", "\n\n", "return", "[", "]", "txn", ".", "Op", "{", "{", "C", ":", "upgradeInfoC", ",", "Id", ":", "currentUpgradeId", ",", "// This is not the last controller, but we need to be", "// sure it still isn't when we run this.", "Assert", ":", "append", "(", "assertSanity", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "controllersNotDone", ".", "Values", "(", ")", "}", "}", ",", "}", "}", "...", ")", ",", "Update", ":", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "{", "{", "\"", "\"", ",", "machineId", "}", "}", "}", "}", ",", "}", "}", ",", "nil", "\n", "}", "\n", "err", "=", "info", ".", "st", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", "\n", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}" ]
// SetControllerDone marks the supplied state machineId as having // completed its upgrades. When SetControllerDone is called by the // last provisioned controller, the current upgrade info document // will be archived with a status of UpgradeComplete.
[ "SetControllerDone", "marks", "the", "supplied", "state", "machineId", "as", "having", "completed", "its", "upgrades", ".", "When", "SetControllerDone", "is", "called", "by", "the", "last", "provisioned", "controller", "the", "current", "upgrade", "info", "document", "will", "be", "archived", "with", "a", "status", "of", "UpgradeComplete", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrade.go#L391-L448
157,043
juju/juju
state/upgrade.go
Abort
func (info *UpgradeInfo) Abort() error { buildTxn := func(attempt int) ([]txn.Op, error) { doc, err := currentUpgradeInfoDoc(info.st) if errors.IsNotFound(err) { return nil, jujutxn.ErrNoOperations } else if err != nil { return nil, errors.Trace(err) } ops := info.makeArchiveOps(doc, UpgradeAborted) extraOps, err := upgradeStatusHistoryAndOps(info.st, UpgradeAborted, info.st.clock().Now()) if err != nil { return nil, errors.Trace(err) } if len(extraOps) > 0 { ops = append(ops, extraOps...) } return ops, nil } err := info.st.db().Run(buildTxn) return errors.Annotate(err, "cannot abort upgrade") }
go
func (info *UpgradeInfo) Abort() error { buildTxn := func(attempt int) ([]txn.Op, error) { doc, err := currentUpgradeInfoDoc(info.st) if errors.IsNotFound(err) { return nil, jujutxn.ErrNoOperations } else if err != nil { return nil, errors.Trace(err) } ops := info.makeArchiveOps(doc, UpgradeAborted) extraOps, err := upgradeStatusHistoryAndOps(info.st, UpgradeAborted, info.st.clock().Now()) if err != nil { return nil, errors.Trace(err) } if len(extraOps) > 0 { ops = append(ops, extraOps...) } return ops, nil } err := info.st.db().Run(buildTxn) return errors.Annotate(err, "cannot abort upgrade") }
[ "func", "(", "info", "*", "UpgradeInfo", ")", "Abort", "(", ")", "error", "{", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "doc", ",", "err", ":=", "currentUpgradeInfoDoc", "(", "info", ".", "st", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "jujutxn", ".", "ErrNoOperations", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "ops", ":=", "info", ".", "makeArchiveOps", "(", "doc", ",", "UpgradeAborted", ")", "\n", "extraOps", ",", "err", ":=", "upgradeStatusHistoryAndOps", "(", "info", ".", "st", ",", "UpgradeAborted", ",", "info", ".", "st", ".", "clock", "(", ")", ".", "Now", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "extraOps", ")", ">", "0", "{", "ops", "=", "append", "(", "ops", ",", "extraOps", "...", ")", "\n", "}", "\n\n", "return", "ops", ",", "nil", "\n", "}", "\n", "err", ":=", "info", ".", "st", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", "\n", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}" ]
// Abort marks the current upgrade as aborted. It should be called if // the upgrade can't be completed for some reason.
[ "Abort", "marks", "the", "current", "upgrade", "as", "aborted", ".", "It", "should", "be", "called", "if", "the", "upgrade", "can", "t", "be", "completed", "for", "some", "reason", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrade.go#L452-L473
157,044
juju/juju
state/upgrade.go
IsUpgrading
func (st *State) IsUpgrading() (bool, error) { doc, err := currentUpgradeInfoDoc(st) if doc != nil && err == nil { return true, nil } else if errors.IsNotFound(err) { return false, nil } else { return false, errors.Trace(err) } }
go
func (st *State) IsUpgrading() (bool, error) { doc, err := currentUpgradeInfoDoc(st) if doc != nil && err == nil { return true, nil } else if errors.IsNotFound(err) { return false, nil } else { return false, errors.Trace(err) } }
[ "func", "(", "st", "*", "State", ")", "IsUpgrading", "(", ")", "(", "bool", ",", "error", ")", "{", "doc", ",", "err", ":=", "currentUpgradeInfoDoc", "(", "st", ")", "\n", "if", "doc", "!=", "nil", "&&", "err", "==", "nil", "{", "return", "true", ",", "nil", "\n", "}", "else", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "false", ",", "nil", "\n", "}", "else", "{", "return", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}" ]
// IsUpgrading returns true if an upgrade is currently in progress.
[ "IsUpgrading", "returns", "true", "if", "an", "upgrade", "is", "currently", "in", "progress", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrade.go#L492-L501
157,045
juju/juju
state/upgrade.go
AbortCurrentUpgrade
func (st *State) AbortCurrentUpgrade() error { doc, err := currentUpgradeInfoDoc(st) if err != nil { if errors.IsNotFound(err) { return nil } return errors.Trace(err) } info := &UpgradeInfo{st: st, doc: *doc} return errors.Trace(info.Abort()) }
go
func (st *State) AbortCurrentUpgrade() error { doc, err := currentUpgradeInfoDoc(st) if err != nil { if errors.IsNotFound(err) { return nil } return errors.Trace(err) } info := &UpgradeInfo{st: st, doc: *doc} return errors.Trace(info.Abort()) }
[ "func", "(", "st", "*", "State", ")", "AbortCurrentUpgrade", "(", ")", "error", "{", "doc", ",", "err", ":=", "currentUpgradeInfoDoc", "(", "st", ")", "\n", "if", "err", "!=", "nil", "{", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "info", ":=", "&", "UpgradeInfo", "{", "st", ":", "st", ",", "doc", ":", "*", "doc", "}", "\n", "return", "errors", ".", "Trace", "(", "info", ".", "Abort", "(", ")", ")", "\n\n", "}" ]
// AbortCurrentUpgrade archives any current UpgradeInfo and sets its // status to UpgradeAborted. Nothing happens if there's no current // UpgradeInfo.
[ "AbortCurrentUpgrade", "archives", "any", "current", "UpgradeInfo", "and", "sets", "its", "status", "to", "UpgradeAborted", ".", "Nothing", "happens", "if", "there", "s", "no", "current", "UpgradeInfo", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrade.go#L506-L517
157,046
juju/juju
state/upgrade.go
ClearUpgradeInfo
func (st *State) ClearUpgradeInfo() error { ops := []txn.Op{{ C: upgradeInfoC, Id: currentUpgradeId, Assert: txn.DocExists, Remove: true, }} err := st.db().RunTransaction(ops) return errors.Annotate(err, "cannot clear upgrade info") }
go
func (st *State) ClearUpgradeInfo() error { ops := []txn.Op{{ C: upgradeInfoC, Id: currentUpgradeId, Assert: txn.DocExists, Remove: true, }} err := st.db().RunTransaction(ops) return errors.Annotate(err, "cannot clear upgrade info") }
[ "func", "(", "st", "*", "State", ")", "ClearUpgradeInfo", "(", ")", "error", "{", "ops", ":=", "[", "]", "txn", ".", "Op", "{", "{", "C", ":", "upgradeInfoC", ",", "Id", ":", "currentUpgradeId", ",", "Assert", ":", "txn", ".", "DocExists", ",", "Remove", ":", "true", ",", "}", "}", "\n", "err", ":=", "st", ".", "db", "(", ")", ".", "RunTransaction", "(", "ops", ")", "\n", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}" ]
// ClearUpgradeInfo clears information about an upgrade in progress. It returns // an error if no upgrade is current.
[ "ClearUpgradeInfo", "clears", "information", "about", "an", "upgrade", "in", "progress", ".", "It", "returns", "an", "error", "if", "no", "upgrade", "is", "current", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/upgrade.go#L556-L565
157,047
juju/juju
worker/uniter/runner/context/cache.go
NewRelationCache
func NewRelationCache(readSettings SettingsFunc, memberNames []string) *RelationCache { cache := &RelationCache{ readSettings: readSettings, } cache.Prune(memberNames) return cache }
go
func NewRelationCache(readSettings SettingsFunc, memberNames []string) *RelationCache { cache := &RelationCache{ readSettings: readSettings, } cache.Prune(memberNames) return cache }
[ "func", "NewRelationCache", "(", "readSettings", "SettingsFunc", ",", "memberNames", "[", "]", "string", ")", "*", "RelationCache", "{", "cache", ":=", "&", "RelationCache", "{", "readSettings", ":", "readSettings", ",", "}", "\n", "cache", ".", "Prune", "(", "memberNames", ")", "\n", "return", "cache", "\n", "}" ]
// NewRelationCache creates a new RelationCache that will use the supplied // SettingsFunc to populate itself on demand. Initial membership is determined // by memberNames.
[ "NewRelationCache", "creates", "a", "new", "RelationCache", "that", "will", "use", "the", "supplied", "SettingsFunc", "to", "populate", "itself", "on", "demand", ".", "Initial", "membership", "is", "determined", "by", "memberNames", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/context/cache.go#L34-L40
157,048
juju/juju
worker/uniter/runner/context/cache.go
Prune
func (cache *RelationCache) Prune(memberNames []string) { newMembers := SettingsMap{} for _, memberName := range memberNames { newMembers[memberName] = cache.members[memberName] } cache.members = newMembers cache.others = SettingsMap{} }
go
func (cache *RelationCache) Prune(memberNames []string) { newMembers := SettingsMap{} for _, memberName := range memberNames { newMembers[memberName] = cache.members[memberName] } cache.members = newMembers cache.others = SettingsMap{} }
[ "func", "(", "cache", "*", "RelationCache", ")", "Prune", "(", "memberNames", "[", "]", "string", ")", "{", "newMembers", ":=", "SettingsMap", "{", "}", "\n", "for", "_", ",", "memberName", ":=", "range", "memberNames", "{", "newMembers", "[", "memberName", "]", "=", "cache", ".", "members", "[", "memberName", "]", "\n", "}", "\n", "cache", ".", "members", "=", "newMembers", "\n", "cache", ".", "others", "=", "SettingsMap", "{", "}", "\n", "}" ]
// Prune resets the membership to the supplied list, and discards the settings // of all non-member units.
[ "Prune", "resets", "the", "membership", "to", "the", "supplied", "list", "and", "discards", "the", "settings", "of", "all", "non", "-", "member", "units", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/context/cache.go#L44-L51
157,049
juju/juju
worker/uniter/runner/context/cache.go
MemberNames
func (cache *RelationCache) MemberNames() (memberNames []string) { for memberName := range cache.members { memberNames = append(memberNames, memberName) } sort.Strings(memberNames) return memberNames }
go
func (cache *RelationCache) MemberNames() (memberNames []string) { for memberName := range cache.members { memberNames = append(memberNames, memberName) } sort.Strings(memberNames) return memberNames }
[ "func", "(", "cache", "*", "RelationCache", ")", "MemberNames", "(", ")", "(", "memberNames", "[", "]", "string", ")", "{", "for", "memberName", ":=", "range", "cache", ".", "members", "{", "memberNames", "=", "append", "(", "memberNames", ",", "memberName", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "memberNames", ")", "\n", "return", "memberNames", "\n", "}" ]
// MemberNames returns the names of the remote units present in the relation.
[ "MemberNames", "returns", "the", "names", "of", "the", "remote", "units", "present", "in", "the", "relation", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/context/cache.go#L54-L60
157,050
juju/juju
worker/uniter/runner/context/cache.go
Settings
func (cache *RelationCache) Settings(unitName string) (params.Settings, error) { settings, isMember := cache.members[unitName] if settings == nil { if !isMember { settings = cache.others[unitName] } if settings == nil { var err error settings, err = cache.readSettings(unitName) if err != nil { return nil, err } } } if isMember { cache.members[unitName] = settings } else { cache.others[unitName] = settings } return settings, nil }
go
func (cache *RelationCache) Settings(unitName string) (params.Settings, error) { settings, isMember := cache.members[unitName] if settings == nil { if !isMember { settings = cache.others[unitName] } if settings == nil { var err error settings, err = cache.readSettings(unitName) if err != nil { return nil, err } } } if isMember { cache.members[unitName] = settings } else { cache.others[unitName] = settings } return settings, nil }
[ "func", "(", "cache", "*", "RelationCache", ")", "Settings", "(", "unitName", "string", ")", "(", "params", ".", "Settings", ",", "error", ")", "{", "settings", ",", "isMember", ":=", "cache", ".", "members", "[", "unitName", "]", "\n", "if", "settings", "==", "nil", "{", "if", "!", "isMember", "{", "settings", "=", "cache", ".", "others", "[", "unitName", "]", "\n", "}", "\n", "if", "settings", "==", "nil", "{", "var", "err", "error", "\n", "settings", ",", "err", "=", "cache", ".", "readSettings", "(", "unitName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "isMember", "{", "cache", ".", "members", "[", "unitName", "]", "=", "settings", "\n", "}", "else", "{", "cache", ".", "others", "[", "unitName", "]", "=", "settings", "\n", "}", "\n", "return", "settings", ",", "nil", "\n", "}" ]
// Settings returns the settings of the named remote unit. It's valid to get // the settings of any unit that has ever been in the relation.
[ "Settings", "returns", "the", "settings", "of", "the", "named", "remote", "unit", ".", "It", "s", "valid", "to", "get", "the", "settings", "of", "any", "unit", "that", "has", "ever", "been", "in", "the", "relation", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/context/cache.go#L64-L84
157,051
juju/juju
apiserver/common/modelmanagerinterface.go
NewModelManagerBackend
func NewModelManagerBackend(m *state.Model, pool *state.StatePool) ModelManagerBackend { return modelManagerStateShim{m.State(), m, pool} }
go
func NewModelManagerBackend(m *state.Model, pool *state.StatePool) ModelManagerBackend { return modelManagerStateShim{m.State(), m, pool} }
[ "func", "NewModelManagerBackend", "(", "m", "*", "state", ".", "Model", ",", "pool", "*", "state", ".", "StatePool", ")", "ModelManagerBackend", "{", "return", "modelManagerStateShim", "{", "m", ".", "State", "(", ")", ",", "m", ",", "pool", "}", "\n", "}" ]
// NewModelManagerBackend returns a modelManagerStateShim wrapping the passed // state, which implements ModelManagerBackend.
[ "NewModelManagerBackend", "returns", "a", "modelManagerStateShim", "wrapping", "the", "passed", "state", "which", "implements", "ModelManagerBackend", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/modelmanagerinterface.go#L118-L120
157,052
juju/juju
apiserver/common/modelmanagerinterface.go
NewModel
func (st modelManagerStateShim) NewModel(args state.ModelArgs) (Model, ModelManagerBackend, error) { controller := state.NewController(st.pool) otherModel, otherState, err := controller.NewModel(args) if err != nil { return nil, nil, err } return modelShim{otherModel}, modelManagerStateShim{otherState, otherModel, st.pool}, nil }
go
func (st modelManagerStateShim) NewModel(args state.ModelArgs) (Model, ModelManagerBackend, error) { controller := state.NewController(st.pool) otherModel, otherState, err := controller.NewModel(args) if err != nil { return nil, nil, err } return modelShim{otherModel}, modelManagerStateShim{otherState, otherModel, st.pool}, nil }
[ "func", "(", "st", "modelManagerStateShim", ")", "NewModel", "(", "args", "state", ".", "ModelArgs", ")", "(", "Model", ",", "ModelManagerBackend", ",", "error", ")", "{", "controller", ":=", "state", ".", "NewController", "(", "st", ".", "pool", ")", "\n", "otherModel", ",", "otherState", ",", "err", ":=", "controller", ".", "NewModel", "(", "args", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "return", "modelShim", "{", "otherModel", "}", ",", "modelManagerStateShim", "{", "otherState", ",", "otherModel", ",", "st", ".", "pool", "}", ",", "nil", "\n", "}" ]
// NewModel implements ModelManagerBackend.
[ "NewModel", "implements", "ModelManagerBackend", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/modelmanagerinterface.go#L123-L130
157,053
juju/juju
apiserver/common/modelmanagerinterface.go
UpdateModelConfigDefaultValues
func (st modelManagerStateShim) UpdateModelConfigDefaultValues(update map[string]interface{}, remove []string, regionSpec *environs.CloudRegionSpec) error { return st.State.UpdateModelConfigDefaultValues(update, remove, regionSpec) }
go
func (st modelManagerStateShim) UpdateModelConfigDefaultValues(update map[string]interface{}, remove []string, regionSpec *environs.CloudRegionSpec) error { return st.State.UpdateModelConfigDefaultValues(update, remove, regionSpec) }
[ "func", "(", "st", "modelManagerStateShim", ")", "UpdateModelConfigDefaultValues", "(", "update", "map", "[", "string", "]", "interface", "{", "}", ",", "remove", "[", "]", "string", ",", "regionSpec", "*", "environs", ".", "CloudRegionSpec", ")", "error", "{", "return", "st", ".", "State", ".", "UpdateModelConfigDefaultValues", "(", "update", ",", "remove", ",", "regionSpec", ")", "\n", "}" ]
// UpdateModelConfigDefaultValues implements the ModelManagerBackend method.
[ "UpdateModelConfigDefaultValues", "implements", "the", "ModelManagerBackend", "method", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/modelmanagerinterface.go#L137-L139
157,054
juju/juju
apiserver/common/modelmanagerinterface.go
GetBackend
func (st modelManagerStateShim) GetBackend(modelUUID string) (ModelManagerBackend, func() bool, error) { otherState, err := st.pool.Get(modelUUID) if err != nil { return nil, nil, errors.Trace(err) } otherModel, err := otherState.Model() if err != nil { otherState.Release() return nil, nil, err } return modelManagerStateShim{otherState.State, otherModel, st.pool}, otherState.Release, nil }
go
func (st modelManagerStateShim) GetBackend(modelUUID string) (ModelManagerBackend, func() bool, error) { otherState, err := st.pool.Get(modelUUID) if err != nil { return nil, nil, errors.Trace(err) } otherModel, err := otherState.Model() if err != nil { otherState.Release() return nil, nil, err } return modelManagerStateShim{otherState.State, otherModel, st.pool}, otherState.Release, nil }
[ "func", "(", "st", "modelManagerStateShim", ")", "GetBackend", "(", "modelUUID", "string", ")", "(", "ModelManagerBackend", ",", "func", "(", ")", "bool", ",", "error", ")", "{", "otherState", ",", "err", ":=", "st", ".", "pool", ".", "Get", "(", "modelUUID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "otherModel", ",", "err", ":=", "otherState", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "otherState", ".", "Release", "(", ")", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "return", "modelManagerStateShim", "{", "otherState", ".", "State", ",", "otherModel", ",", "st", ".", "pool", "}", ",", "otherState", ".", "Release", ",", "nil", "\n", "}" ]
// GetBackend implements ModelManagerBackend.
[ "GetBackend", "implements", "ModelManagerBackend", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/modelmanagerinterface.go#L147-L158
157,055
juju/juju
apiserver/common/modelmanagerinterface.go
GetModel
func (st modelManagerStateShim) GetModel(modelUUID string) (Model, func() bool, error) { model, hp, err := st.pool.GetModel(modelUUID) if err != nil { return nil, nil, errors.Trace(err) } return modelShim{model}, hp.Release, nil }
go
func (st modelManagerStateShim) GetModel(modelUUID string) (Model, func() bool, error) { model, hp, err := st.pool.GetModel(modelUUID) if err != nil { return nil, nil, errors.Trace(err) } return modelShim{model}, hp.Release, nil }
[ "func", "(", "st", "modelManagerStateShim", ")", "GetModel", "(", "modelUUID", "string", ")", "(", "Model", ",", "func", "(", ")", "bool", ",", "error", ")", "{", "model", ",", "hp", ",", "err", ":=", "st", ".", "pool", ".", "GetModel", "(", "modelUUID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "modelShim", "{", "model", "}", ",", "hp", ".", "Release", ",", "nil", "\n", "}" ]
// GetModel implements ModelManagerBackend.
[ "GetModel", "implements", "ModelManagerBackend", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/modelmanagerinterface.go#L161-L167
157,056
juju/juju
apiserver/common/modelmanagerinterface.go
Users
func (m modelShim) Users() ([]permission.UserAccess, error) { stateUsers, err := m.Model.Users() if err != nil { return nil, err } users := make([]permission.UserAccess, len(stateUsers)) for i, user := range stateUsers { users[i] = user } return users, nil }
go
func (m modelShim) Users() ([]permission.UserAccess, error) { stateUsers, err := m.Model.Users() if err != nil { return nil, err } users := make([]permission.UserAccess, len(stateUsers)) for i, user := range stateUsers { users[i] = user } return users, nil }
[ "func", "(", "m", "modelShim", ")", "Users", "(", ")", "(", "[", "]", "permission", ".", "UserAccess", ",", "error", ")", "{", "stateUsers", ",", "err", ":=", "m", ".", "Model", ".", "Users", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "users", ":=", "make", "(", "[", "]", "permission", ".", "UserAccess", ",", "len", "(", "stateUsers", ")", ")", "\n", "for", "i", ",", "user", ":=", "range", "stateUsers", "{", "users", "[", "i", "]", "=", "user", "\n", "}", "\n", "return", "users", ",", "nil", "\n", "}" ]
// Users implements ModelManagerBackend.
[ "Users", "implements", "ModelManagerBackend", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/modelmanagerinterface.go#L190-L200
157,057
juju/juju
apiserver/common/modelmanagerinterface.go
ModelConfig
func (st modelManagerStateShim) ModelConfig() (*config.Config, error) { model, err := st.State.Model() if err != nil { return nil, errors.Trace(err) } return model.ModelConfig() }
go
func (st modelManagerStateShim) ModelConfig() (*config.Config, error) { model, err := st.State.Model() if err != nil { return nil, errors.Trace(err) } return model.ModelConfig() }
[ "func", "(", "st", "modelManagerStateShim", ")", "ModelConfig", "(", ")", "(", "*", "config", ".", "Config", ",", "error", ")", "{", "model", ",", "err", ":=", "st", ".", "State", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "model", ".", "ModelConfig", "(", ")", "\n", "}" ]
// ModelConfig returns the underlying model's config. Exposed here to satisfy the // ModelBackend interface.
[ "ModelConfig", "returns", "the", "underlying", "model", "s", "config", ".", "Exposed", "here", "to", "satisfy", "the", "ModelBackend", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/modelmanagerinterface.go#L257-L263
157,058
juju/juju
provider/common/bootstrap.go
Bootstrap
func Bootstrap( ctx environs.BootstrapContext, env environs.Environ, callCtx context.ProviderCallContext, args environs.BootstrapParams, ) (*environs.BootstrapResult, error) { result, series, finalizer, err := BootstrapInstance(ctx, env, callCtx, args) if err != nil { return nil, errors.Trace(err) } bsResult := &environs.BootstrapResult{ Arch: *result.Hardware.Arch, Series: series, CloudBootstrapFinalizer: finalizer, } return bsResult, nil }
go
func Bootstrap( ctx environs.BootstrapContext, env environs.Environ, callCtx context.ProviderCallContext, args environs.BootstrapParams, ) (*environs.BootstrapResult, error) { result, series, finalizer, err := BootstrapInstance(ctx, env, callCtx, args) if err != nil { return nil, errors.Trace(err) } bsResult := &environs.BootstrapResult{ Arch: *result.Hardware.Arch, Series: series, CloudBootstrapFinalizer: finalizer, } return bsResult, nil }
[ "func", "Bootstrap", "(", "ctx", "environs", ".", "BootstrapContext", ",", "env", "environs", ".", "Environ", ",", "callCtx", "context", ".", "ProviderCallContext", ",", "args", "environs", ".", "BootstrapParams", ",", ")", "(", "*", "environs", ".", "BootstrapResult", ",", "error", ")", "{", "result", ",", "series", ",", "finalizer", ",", "err", ":=", "BootstrapInstance", "(", "ctx", ",", "env", ",", "callCtx", ",", "args", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "bsResult", ":=", "&", "environs", ".", "BootstrapResult", "{", "Arch", ":", "*", "result", ".", "Hardware", ".", "Arch", ",", "Series", ":", "series", ",", "CloudBootstrapFinalizer", ":", "finalizer", ",", "}", "\n", "return", "bsResult", ",", "nil", "\n", "}" ]
// Bootstrap is a common implementation of the Bootstrap method defined on // environs.Environ; we strongly recommend that this implementation be used // when writing a new provider.
[ "Bootstrap", "is", "a", "common", "implementation", "of", "the", "Bootstrap", "method", "defined", "on", "environs", ".", "Environ", ";", "we", "strongly", "recommend", "that", "this", "implementation", "be", "used", "when", "writing", "a", "new", "provider", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/common/bootstrap.go#L48-L65
157,059
juju/juju
provider/common/bootstrap.go
bootstrapSSHOptionsFunc
func bootstrapSSHOptionsFunc(instanceConfig *instancecfg.InstanceConfig) HostSSHOptionsFunc { return func(host string) (*ssh.Options, func(), error) { return hostBootstrapSSHOptions(host, instanceConfig) } }
go
func bootstrapSSHOptionsFunc(instanceConfig *instancecfg.InstanceConfig) HostSSHOptionsFunc { return func(host string) (*ssh.Options, func(), error) { return hostBootstrapSSHOptions(host, instanceConfig) } }
[ "func", "bootstrapSSHOptionsFunc", "(", "instanceConfig", "*", "instancecfg", ".", "InstanceConfig", ")", "HostSSHOptionsFunc", "{", "return", "func", "(", "host", "string", ")", "(", "*", "ssh", ".", "Options", ",", "func", "(", ")", ",", "error", ")", "{", "return", "hostBootstrapSSHOptions", "(", "host", ",", "instanceConfig", ")", "\n", "}", "\n", "}" ]
// bootstrapSSHOptionsFunc that takes a bootstrap machine's InstanceConfig // and returns a HostSSHOptionsFunc.
[ "bootstrapSSHOptionsFunc", "that", "takes", "a", "bootstrap", "machine", "s", "InstanceConfig", "and", "returns", "a", "HostSSHOptionsFunc", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/common/bootstrap.go#L438-L442
157,060
juju/juju
provider/common/bootstrap.go
Refresh
func (i *RefreshableInstance) Refresh(ctx context.ProviderCallContext) error { instances, err := i.Env.Instances(ctx, []instance.Id{i.Id()}) if err != nil { return errors.Trace(err) } i.Instance = instances[0] return nil }
go
func (i *RefreshableInstance) Refresh(ctx context.ProviderCallContext) error { instances, err := i.Env.Instances(ctx, []instance.Id{i.Id()}) if err != nil { return errors.Trace(err) } i.Instance = instances[0] return nil }
[ "func", "(", "i", "*", "RefreshableInstance", ")", "Refresh", "(", "ctx", "context", ".", "ProviderCallContext", ")", "error", "{", "instances", ",", "err", ":=", "i", ".", "Env", ".", "Instances", "(", "ctx", ",", "[", "]", "instance", ".", "Id", "{", "i", ".", "Id", "(", ")", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "i", ".", "Instance", "=", "instances", "[", "0", "]", "\n", "return", "nil", "\n", "}" ]
// Refresh refreshes the addresses for the instance.
[ "Refresh", "refreshes", "the", "addresses", "for", "the", "instance", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/common/bootstrap.go#L516-L523
157,061
juju/juju
provider/common/bootstrap.go
Close
func (p *parallelHostChecker) Close() error { // We signal each checker to stop and wait for them // each to complete; this allows us to get the error, // as opposed to when using try.Kill which does not // wait for the functions to complete. p.Try.Close() for _, ch := range p.active { close(ch) } return nil }
go
func (p *parallelHostChecker) Close() error { // We signal each checker to stop and wait for them // each to complete; this allows us to get the error, // as opposed to when using try.Kill which does not // wait for the functions to complete. p.Try.Close() for _, ch := range p.active { close(ch) } return nil }
[ "func", "(", "p", "*", "parallelHostChecker", ")", "Close", "(", ")", "error", "{", "// We signal each checker to stop and wait for them", "// each to complete; this allows us to get the error,", "// as opposed to when using try.Kill which does not", "// wait for the functions to complete.", "p", ".", "Try", ".", "Close", "(", ")", "\n", "for", "_", ",", "ch", ":=", "range", "p", ".", "active", "{", "close", "(", "ch", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close prevents additional functions from being added to // the Try, and tells each active hostChecker to exit.
[ "Close", "prevents", "additional", "functions", "from", "being", "added", "to", "the", "Try", "and", "tells", "each", "active", "hostChecker", "to", "exit", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/common/bootstrap.go#L632-L642
157,062
juju/juju
provider/common/bootstrap.go
WaitSSH
func WaitSSH( stdErr io.Writer, interrupted <-chan os.Signal, client ssh.Client, checkHostScript string, inst InstanceRefresher, ctx context.ProviderCallContext, opts environs.BootstrapDialOpts, hostSSHOptions HostSSHOptionsFunc, ) (addr string, err error) { globalTimeout := time.After(opts.Timeout) pollAddresses := time.NewTimer(0) // checker checks each address in a loop, in parallel, // until one succeeds, the global timeout is reached, // or the tomb is killed. checker := parallelHostChecker{ Try: parallel.NewTry(0, nil), client: client, stderr: stdErr, active: make(map[network.Address]chan struct{}), checkDelay: opts.RetryDelay, checkHostScript: checkHostScript, hostSSHOptions: hostSSHOptions, } defer checker.wg.Wait() defer checker.Kill() fmt.Fprintln(stdErr, "Waiting for address") for { select { case <-pollAddresses.C: pollAddresses.Reset(opts.AddressesDelay) if err := inst.Refresh(ctx); err != nil { return "", fmt.Errorf("refreshing addresses: %v", err) } instanceStatus := inst.Status(ctx) if instanceStatus.Status == status.ProvisioningError { if instanceStatus.Message != "" { return "", errors.Errorf("instance provisioning failed (%v)", instanceStatus.Message) } return "", errors.Errorf("instance provisioning failed") } addresses, err := inst.Addresses(ctx) if err != nil { return "", fmt.Errorf("getting addresses: %v", err) } checker.UpdateAddresses(addresses) case <-globalTimeout: checker.Close() lastErr := checker.Wait() format := "waited for %v " args := []interface{}{opts.Timeout} if len(checker.active) == 0 { format += "without getting any addresses" } else { format += "without being able to connect" } if lastErr != nil && lastErr != parallel.ErrStopped { format += ": %v" args = append(args, lastErr) } return "", fmt.Errorf(format, args...) case <-interrupted: return "", fmt.Errorf("interrupted") case <-checker.Dead(): result, err := checker.Result() if err != nil { return "", err } return result.(*hostChecker).addr.Value, nil } } }
go
func WaitSSH( stdErr io.Writer, interrupted <-chan os.Signal, client ssh.Client, checkHostScript string, inst InstanceRefresher, ctx context.ProviderCallContext, opts environs.BootstrapDialOpts, hostSSHOptions HostSSHOptionsFunc, ) (addr string, err error) { globalTimeout := time.After(opts.Timeout) pollAddresses := time.NewTimer(0) // checker checks each address in a loop, in parallel, // until one succeeds, the global timeout is reached, // or the tomb is killed. checker := parallelHostChecker{ Try: parallel.NewTry(0, nil), client: client, stderr: stdErr, active: make(map[network.Address]chan struct{}), checkDelay: opts.RetryDelay, checkHostScript: checkHostScript, hostSSHOptions: hostSSHOptions, } defer checker.wg.Wait() defer checker.Kill() fmt.Fprintln(stdErr, "Waiting for address") for { select { case <-pollAddresses.C: pollAddresses.Reset(opts.AddressesDelay) if err := inst.Refresh(ctx); err != nil { return "", fmt.Errorf("refreshing addresses: %v", err) } instanceStatus := inst.Status(ctx) if instanceStatus.Status == status.ProvisioningError { if instanceStatus.Message != "" { return "", errors.Errorf("instance provisioning failed (%v)", instanceStatus.Message) } return "", errors.Errorf("instance provisioning failed") } addresses, err := inst.Addresses(ctx) if err != nil { return "", fmt.Errorf("getting addresses: %v", err) } checker.UpdateAddresses(addresses) case <-globalTimeout: checker.Close() lastErr := checker.Wait() format := "waited for %v " args := []interface{}{opts.Timeout} if len(checker.active) == 0 { format += "without getting any addresses" } else { format += "without being able to connect" } if lastErr != nil && lastErr != parallel.ErrStopped { format += ": %v" args = append(args, lastErr) } return "", fmt.Errorf(format, args...) case <-interrupted: return "", fmt.Errorf("interrupted") case <-checker.Dead(): result, err := checker.Result() if err != nil { return "", err } return result.(*hostChecker).addr.Value, nil } } }
[ "func", "WaitSSH", "(", "stdErr", "io", ".", "Writer", ",", "interrupted", "<-", "chan", "os", ".", "Signal", ",", "client", "ssh", ".", "Client", ",", "checkHostScript", "string", ",", "inst", "InstanceRefresher", ",", "ctx", "context", ".", "ProviderCallContext", ",", "opts", "environs", ".", "BootstrapDialOpts", ",", "hostSSHOptions", "HostSSHOptionsFunc", ",", ")", "(", "addr", "string", ",", "err", "error", ")", "{", "globalTimeout", ":=", "time", ".", "After", "(", "opts", ".", "Timeout", ")", "\n", "pollAddresses", ":=", "time", ".", "NewTimer", "(", "0", ")", "\n\n", "// checker checks each address in a loop, in parallel,", "// until one succeeds, the global timeout is reached,", "// or the tomb is killed.", "checker", ":=", "parallelHostChecker", "{", "Try", ":", "parallel", ".", "NewTry", "(", "0", ",", "nil", ")", ",", "client", ":", "client", ",", "stderr", ":", "stdErr", ",", "active", ":", "make", "(", "map", "[", "network", ".", "Address", "]", "chan", "struct", "{", "}", ")", ",", "checkDelay", ":", "opts", ".", "RetryDelay", ",", "checkHostScript", ":", "checkHostScript", ",", "hostSSHOptions", ":", "hostSSHOptions", ",", "}", "\n", "defer", "checker", ".", "wg", ".", "Wait", "(", ")", "\n", "defer", "checker", ".", "Kill", "(", ")", "\n\n", "fmt", ".", "Fprintln", "(", "stdErr", ",", "\"", "\"", ")", "\n", "for", "{", "select", "{", "case", "<-", "pollAddresses", ".", "C", ":", "pollAddresses", ".", "Reset", "(", "opts", ".", "AddressesDelay", ")", "\n", "if", "err", ":=", "inst", ".", "Refresh", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "instanceStatus", ":=", "inst", ".", "Status", "(", "ctx", ")", "\n", "if", "instanceStatus", ".", "Status", "==", "status", ".", "ProvisioningError", "{", "if", "instanceStatus", ".", "Message", "!=", "\"", "\"", "{", "return", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "instanceStatus", ".", "Message", ")", "\n", "}", "\n", "return", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "addresses", ",", "err", ":=", "inst", ".", "Addresses", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "checker", ".", "UpdateAddresses", "(", "addresses", ")", "\n", "case", "<-", "globalTimeout", ":", "checker", ".", "Close", "(", ")", "\n", "lastErr", ":=", "checker", ".", "Wait", "(", ")", "\n", "format", ":=", "\"", "\"", "\n", "args", ":=", "[", "]", "interface", "{", "}", "{", "opts", ".", "Timeout", "}", "\n", "if", "len", "(", "checker", ".", "active", ")", "==", "0", "{", "format", "+=", "\"", "\"", "\n", "}", "else", "{", "format", "+=", "\"", "\"", "\n", "}", "\n", "if", "lastErr", "!=", "nil", "&&", "lastErr", "!=", "parallel", ".", "ErrStopped", "{", "format", "+=", "\"", "\"", "\n", "args", "=", "append", "(", "args", ",", "lastErr", ")", "\n", "}", "\n", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "format", ",", "args", "...", ")", "\n", "case", "<-", "interrupted", ":", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "case", "<-", "checker", ".", "Dead", "(", ")", ":", "result", ",", "err", ":=", "checker", ".", "Result", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "result", ".", "(", "*", "hostChecker", ")", ".", "addr", ".", "Value", ",", "nil", "\n", "}", "\n", "}", "\n", "}" ]
// WaitSSH waits for the instance to be assigned a routable // address, then waits until we can connect to it via SSH. // // waitSSH attempts on all addresses returned by the instance // in parallel; the first succeeding one wins. We ensure that // private addresses are for the correct machine by checking // the presence of a file on the machine that contains the // machine's nonce. The "checkHostScript" is a bash script // that performs this file check.
[ "WaitSSH", "waits", "for", "the", "instance", "to", "be", "assigned", "a", "routable", "address", "then", "waits", "until", "we", "can", "connect", "to", "it", "via", "SSH", ".", "waitSSH", "attempts", "on", "all", "addresses", "returned", "by", "the", "instance", "in", "parallel", ";", "the", "first", "succeeding", "one", "wins", ".", "We", "ensure", "that", "private", "addresses", "are", "for", "the", "correct", "machine", "by", "checking", "the", "presence", "of", "a", "file", "on", "the", "machine", "that", "contains", "the", "machine", "s", "nonce", ".", "The", "checkHostScript", "is", "a", "bash", "script", "that", "performs", "this", "file", "check", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/common/bootstrap.go#L665-L738
157,063
juju/juju
state/remoteapplication.go
SourceModel
func (s *RemoteApplication) SourceModel() names.ModelTag { return names.NewModelTag(s.doc.SourceModelUUID) }
go
func (s *RemoteApplication) SourceModel() names.ModelTag { return names.NewModelTag(s.doc.SourceModelUUID) }
[ "func", "(", "s", "*", "RemoteApplication", ")", "SourceModel", "(", ")", "names", ".", "ModelTag", "{", "return", "names", ".", "NewModelTag", "(", "s", ".", "doc", ".", "SourceModelUUID", ")", "\n", "}" ]
// SourceModel returns the tag of the model to which the application belongs.
[ "SourceModel", "returns", "the", "tag", "of", "the", "model", "to", "which", "the", "application", "belongs", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/remoteapplication.go#L131-L133
157,064
juju/juju
state/remoteapplication.go
URL
func (s *RemoteApplication) URL() (string, bool) { return s.doc.URL, s.doc.URL != "" }
go
func (s *RemoteApplication) URL() (string, bool) { return s.doc.URL, s.doc.URL != "" }
[ "func", "(", "s", "*", "RemoteApplication", ")", "URL", "(", ")", "(", "string", ",", "bool", ")", "{", "return", "s", ".", "doc", ".", "URL", ",", "s", ".", "doc", ".", "URL", "!=", "\"", "\"", "\n", "}" ]
// URL returns the remote application URL, and a boolean indicating whether or not // a URL is known for the remote application. A URL will only be available for the // consumer of an offered application.
[ "URL", "returns", "the", "remote", "application", "URL", "and", "a", "boolean", "indicating", "whether", "or", "not", "a", "URL", "is", "known", "for", "the", "remote", "application", ".", "A", "URL", "will", "only", "be", "available", "for", "the", "consumer", "of", "an", "offered", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/remoteapplication.go#L154-L156
157,065
juju/juju
state/remoteapplication.go
Token
func (s *RemoteApplication) Token() (string, error) { r := s.st.RemoteEntities() return r.GetToken(s.Tag()) }
go
func (s *RemoteApplication) Token() (string, error) { r := s.st.RemoteEntities() return r.GetToken(s.Tag()) }
[ "func", "(", "s", "*", "RemoteApplication", ")", "Token", "(", ")", "(", "string", ",", "error", ")", "{", "r", ":=", "s", ".", "st", ".", "RemoteEntities", "(", ")", "\n", "return", "r", ".", "GetToken", "(", "s", ".", "Tag", "(", ")", ")", "\n", "}" ]
// Token returns the token for the remote application, provided by the remote // model to identify the application in future communications.
[ "Token", "returns", "the", "token", "for", "the", "remote", "application", "provided", "by", "the", "remote", "model", "to", "identify", "the", "application", "in", "future", "communications", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/remoteapplication.go#L160-L163
157,066
juju/juju
state/remoteapplication.go
Spaces
func (s *RemoteApplication) Spaces() []RemoteSpace { var result []RemoteSpace for _, space := range s.doc.Spaces { result = append(result, remoteSpaceFromDoc(space)) } return result }
go
func (s *RemoteApplication) Spaces() []RemoteSpace { var result []RemoteSpace for _, space := range s.doc.Spaces { result = append(result, remoteSpaceFromDoc(space)) } return result }
[ "func", "(", "s", "*", "RemoteApplication", ")", "Spaces", "(", ")", "[", "]", "RemoteSpace", "{", "var", "result", "[", "]", "RemoteSpace", "\n", "for", "_", ",", "space", ":=", "range", "s", ".", "doc", ".", "Spaces", "{", "result", "=", "append", "(", "result", ",", "remoteSpaceFromDoc", "(", "space", ")", ")", "\n", "}", "\n", "return", "result", "\n", "}" ]
// Spaces returns the remote spaces this application is connected to.
[ "Spaces", "returns", "the", "remote", "spaces", "this", "application", "is", "connected", "to", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/remoteapplication.go#L176-L182
157,067
juju/juju
state/remoteapplication.go
Bindings
func (s *RemoteApplication) Bindings() map[string]string { result := make(map[string]string) for epName, spName := range s.doc.Bindings { result[epName] = spName } return result }
go
func (s *RemoteApplication) Bindings() map[string]string { result := make(map[string]string) for epName, spName := range s.doc.Bindings { result[epName] = spName } return result }
[ "func", "(", "s", "*", "RemoteApplication", ")", "Bindings", "(", ")", "map", "[", "string", "]", "string", "{", "result", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "for", "epName", ",", "spName", ":=", "range", "s", ".", "doc", ".", "Bindings", "{", "result", "[", "epName", "]", "=", "spName", "\n", "}", "\n", "return", "result", "\n", "}" ]
// Bindings returns the endpoint->space bindings for the application.
[ "Bindings", "returns", "the", "endpoint", "-", ">", "space", "bindings", "for", "the", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/remoteapplication.go#L185-L191
157,068
juju/juju
state/remoteapplication.go
SpaceForEndpoint
func (s *RemoteApplication) SpaceForEndpoint(endpointName string) (RemoteSpace, bool) { spaceName, ok := s.doc.Bindings[endpointName] if !ok { return RemoteSpace{}, false } for _, space := range s.doc.Spaces { if space.Name == spaceName { return remoteSpaceFromDoc(space), true } } return RemoteSpace{}, false }
go
func (s *RemoteApplication) SpaceForEndpoint(endpointName string) (RemoteSpace, bool) { spaceName, ok := s.doc.Bindings[endpointName] if !ok { return RemoteSpace{}, false } for _, space := range s.doc.Spaces { if space.Name == spaceName { return remoteSpaceFromDoc(space), true } } return RemoteSpace{}, false }
[ "func", "(", "s", "*", "RemoteApplication", ")", "SpaceForEndpoint", "(", "endpointName", "string", ")", "(", "RemoteSpace", ",", "bool", ")", "{", "spaceName", ",", "ok", ":=", "s", ".", "doc", ".", "Bindings", "[", "endpointName", "]", "\n", "if", "!", "ok", "{", "return", "RemoteSpace", "{", "}", ",", "false", "\n", "}", "\n", "for", "_", ",", "space", ":=", "range", "s", ".", "doc", ".", "Spaces", "{", "if", "space", ".", "Name", "==", "spaceName", "{", "return", "remoteSpaceFromDoc", "(", "space", ")", ",", "true", "\n", "}", "\n", "}", "\n", "return", "RemoteSpace", "{", "}", ",", "false", "\n", "}" ]
// SpaceForEndpoint returns the remote space an endpoint is bound to, // if one is found.
[ "SpaceForEndpoint", "returns", "the", "remote", "space", "an", "endpoint", "is", "bound", "to", "if", "one", "is", "found", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/remoteapplication.go#L195-L206
157,069
juju/juju
state/remoteapplication.go
DestroyRemoteApplicationOperation
func (s *RemoteApplication) DestroyRemoteApplicationOperation(force bool) *DestroyRemoteApplicationOperation { return &DestroyRemoteApplicationOperation{ app: &RemoteApplication{st: s.st, doc: s.doc}, ForcedOperation: ForcedOperation{Force: force}, } }
go
func (s *RemoteApplication) DestroyRemoteApplicationOperation(force bool) *DestroyRemoteApplicationOperation { return &DestroyRemoteApplicationOperation{ app: &RemoteApplication{st: s.st, doc: s.doc}, ForcedOperation: ForcedOperation{Force: force}, } }
[ "func", "(", "s", "*", "RemoteApplication", ")", "DestroyRemoteApplicationOperation", "(", "force", "bool", ")", "*", "DestroyRemoteApplicationOperation", "{", "return", "&", "DestroyRemoteApplicationOperation", "{", "app", ":", "&", "RemoteApplication", "{", "st", ":", "s", ".", "st", ",", "doc", ":", "s", ".", "doc", "}", ",", "ForcedOperation", ":", "ForcedOperation", "{", "Force", ":", "force", "}", ",", "}", "\n", "}" ]
// DestroyRemoteApplicationOperation returns a model operation to destroy remote application.
[ "DestroyRemoteApplicationOperation", "returns", "a", "model", "operation", "to", "destroy", "remote", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/remoteapplication.go#L253-L258
157,070
juju/juju
state/remoteapplication.go
Destroy
func (s *RemoteApplication) Destroy() error { _, err := s.DestroyWithForce(false, time.Duration(0)) return err }
go
func (s *RemoteApplication) Destroy() error { _, err := s.DestroyWithForce(false, time.Duration(0)) return err }
[ "func", "(", "s", "*", "RemoteApplication", ")", "Destroy", "(", ")", "error", "{", "_", ",", "err", ":=", "s", ".", "DestroyWithForce", "(", "false", ",", "time", ".", "Duration", "(", "0", ")", ")", "\n", "return", "err", "\n", "}" ]
// Destroy ensures that this remote application reference and all its relations // will be removed at some point; if no relation involving the // application has any units in scope, they are all removed immediately.
[ "Destroy", "ensures", "that", "this", "remote", "application", "reference", "and", "all", "its", "relations", "will", "be", "removed", "at", "some", "point", ";", "if", "no", "relation", "involving", "the", "application", "has", "any", "units", "in", "scope", "they", "are", "all", "removed", "immediately", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/remoteapplication.go#L326-L329
157,071
juju/juju
state/remoteapplication.go
removeOps
func (s *RemoteApplication) removeOps(asserts bson.D) ([]txn.Op, error) { r := s.st.RemoteEntities() ops := []txn.Op{ { C: remoteApplicationsC, Id: s.doc.DocID, Assert: asserts, Remove: true, }, removeStatusOp(s.st, s.globalKey()), } tokenOps := r.removeRemoteEntityOps(s.Tag()) ops = append(ops, tokenOps...) return ops, nil }
go
func (s *RemoteApplication) removeOps(asserts bson.D) ([]txn.Op, error) { r := s.st.RemoteEntities() ops := []txn.Op{ { C: remoteApplicationsC, Id: s.doc.DocID, Assert: asserts, Remove: true, }, removeStatusOp(s.st, s.globalKey()), } tokenOps := r.removeRemoteEntityOps(s.Tag()) ops = append(ops, tokenOps...) return ops, nil }
[ "func", "(", "s", "*", "RemoteApplication", ")", "removeOps", "(", "asserts", "bson", ".", "D", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "r", ":=", "s", ".", "st", ".", "RemoteEntities", "(", ")", "\n", "ops", ":=", "[", "]", "txn", ".", "Op", "{", "{", "C", ":", "remoteApplicationsC", ",", "Id", ":", "s", ".", "doc", ".", "DocID", ",", "Assert", ":", "asserts", ",", "Remove", ":", "true", ",", "}", ",", "removeStatusOp", "(", "s", ".", "st", ",", "s", ".", "globalKey", "(", ")", ")", ",", "}", "\n", "tokenOps", ":=", "r", ".", "removeRemoteEntityOps", "(", "s", ".", "Tag", "(", ")", ")", "\n", "ops", "=", "append", "(", "ops", ",", "tokenOps", "...", ")", "\n", "return", "ops", ",", "nil", "\n", "}" ]
// removeOps returns the operations required to remove the application. Supplied // asserts will be included in the operation on the application document.
[ "removeOps", "returns", "the", "operations", "required", "to", "remove", "the", "application", ".", "Supplied", "asserts", "will", "be", "included", "in", "the", "operation", "on", "the", "application", "document", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/remoteapplication.go#L462-L476
157,072
juju/juju
state/remoteapplication.go
Status
func (s *RemoteApplication) Status() (status.StatusInfo, error) { return getStatus(s.st.db(), s.globalKey(), "remote application") }
go
func (s *RemoteApplication) Status() (status.StatusInfo, error) { return getStatus(s.st.db(), s.globalKey(), "remote application") }
[ "func", "(", "s", "*", "RemoteApplication", ")", "Status", "(", ")", "(", "status", ".", "StatusInfo", ",", "error", ")", "{", "return", "getStatus", "(", "s", ".", "st", ".", "db", "(", ")", ",", "s", ".", "globalKey", "(", ")", ",", "\"", "\"", ")", "\n", "}" ]
// Status returns the status of the remote application.
[ "Status", "returns", "the", "status", "of", "the", "remote", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/remoteapplication.go#L479-L481
157,073
juju/juju
state/remoteapplication.go
Refresh
func (s *RemoteApplication) Refresh() error { applications, closer := s.st.db().GetCollection(remoteApplicationsC) defer closer() err := applications.FindId(s.doc.DocID).One(&s.doc) if err == mgo.ErrNotFound { return errors.NotFoundf("remote application %q", s) } if err != nil { return fmt.Errorf("cannot refresh application %q: %v", s, err) } return nil }
go
func (s *RemoteApplication) Refresh() error { applications, closer := s.st.db().GetCollection(remoteApplicationsC) defer closer() err := applications.FindId(s.doc.DocID).One(&s.doc) if err == mgo.ErrNotFound { return errors.NotFoundf("remote application %q", s) } if err != nil { return fmt.Errorf("cannot refresh application %q: %v", s, err) } return nil }
[ "func", "(", "s", "*", "RemoteApplication", ")", "Refresh", "(", ")", "error", "{", "applications", ",", "closer", ":=", "s", ".", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "remoteApplicationsC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "err", ":=", "applications", ".", "FindId", "(", "s", ".", "doc", ".", "DocID", ")", ".", "One", "(", "&", "s", ".", "doc", ")", "\n", "if", "err", "==", "mgo", ".", "ErrNotFound", "{", "return", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "s", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Refresh refreshes the contents of the RemoteApplication from the underlying // state. It returns an error that satisfies errors.IsNotFound if the // application has been removed.
[ "Refresh", "refreshes", "the", "contents", "of", "the", "RemoteApplication", "from", "the", "underlying", "state", ".", "It", "returns", "an", "error", "that", "satisfies", "errors", ".", "IsNotFound", "if", "the", "application", "has", "been", "removed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/remoteapplication.go#L643-L655
157,074
juju/juju
state/remoteapplication.go
Validate
func (p AddRemoteApplicationParams) Validate() error { if !names.IsValidApplication(p.Name) { return errors.NotValidf("name %q", p.Name) } if p.URL != "" { // URL may be empty, to represent remote applications corresponding // to consumers of an offered application. if _, err := crossmodel.ParseOfferURL(p.URL); err != nil { return errors.Annotate(err, "validating offer URL") } } if p.SourceModel == (names.ModelTag{}) { return errors.NotValidf("empty source model tag") } spaceNames := set.NewStrings() for _, space := range p.Spaces { spaceNames.Add(space.Name) } for endpoint, space := range p.Bindings { if !spaceNames.Contains(space) { return errors.NotValidf("endpoint %q bound to missing space %q", endpoint, space) } } return nil }
go
func (p AddRemoteApplicationParams) Validate() error { if !names.IsValidApplication(p.Name) { return errors.NotValidf("name %q", p.Name) } if p.URL != "" { // URL may be empty, to represent remote applications corresponding // to consumers of an offered application. if _, err := crossmodel.ParseOfferURL(p.URL); err != nil { return errors.Annotate(err, "validating offer URL") } } if p.SourceModel == (names.ModelTag{}) { return errors.NotValidf("empty source model tag") } spaceNames := set.NewStrings() for _, space := range p.Spaces { spaceNames.Add(space.Name) } for endpoint, space := range p.Bindings { if !spaceNames.Contains(space) { return errors.NotValidf("endpoint %q bound to missing space %q", endpoint, space) } } return nil }
[ "func", "(", "p", "AddRemoteApplicationParams", ")", "Validate", "(", ")", "error", "{", "if", "!", "names", ".", "IsValidApplication", "(", "p", ".", "Name", ")", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "p", ".", "Name", ")", "\n", "}", "\n", "if", "p", ".", "URL", "!=", "\"", "\"", "{", "// URL may be empty, to represent remote applications corresponding", "// to consumers of an offered application.", "if", "_", ",", "err", ":=", "crossmodel", ".", "ParseOfferURL", "(", "p", ".", "URL", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "if", "p", ".", "SourceModel", "==", "(", "names", ".", "ModelTag", "{", "}", ")", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "spaceNames", ":=", "set", ".", "NewStrings", "(", ")", "\n", "for", "_", ",", "space", ":=", "range", "p", ".", "Spaces", "{", "spaceNames", ".", "Add", "(", "space", ".", "Name", ")", "\n", "}", "\n", "for", "endpoint", ",", "space", ":=", "range", "p", ".", "Bindings", "{", "if", "!", "spaceNames", ".", "Contains", "(", "space", ")", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "endpoint", ",", "space", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate returns an error if there's a problem with the // parameters being used to create a remote application.
[ "Validate", "returns", "an", "error", "if", "there", "s", "a", "problem", "with", "the", "parameters", "being", "used", "to", "create", "a", "remote", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/remoteapplication.go#L703-L727
157,075
juju/juju
state/remoteapplication.go
RemoteApplication
func (st *State) RemoteApplication(name string) (_ *RemoteApplication, err error) { if !names.IsValidApplication(name) { return nil, errors.NotValidf("remote application name %q", name) } applications, closer := st.db().GetCollection(remoteApplicationsC) defer closer() appDoc := &remoteApplicationDoc{} err = applications.FindId(name).One(appDoc) if err == mgo.ErrNotFound { return nil, errors.NotFoundf("remote application %q", name) } if err != nil { return nil, errors.Annotatef(err, "cannot get remote application %q", name) } return newRemoteApplication(st, appDoc), nil }
go
func (st *State) RemoteApplication(name string) (_ *RemoteApplication, err error) { if !names.IsValidApplication(name) { return nil, errors.NotValidf("remote application name %q", name) } applications, closer := st.db().GetCollection(remoteApplicationsC) defer closer() appDoc := &remoteApplicationDoc{} err = applications.FindId(name).One(appDoc) if err == mgo.ErrNotFound { return nil, errors.NotFoundf("remote application %q", name) } if err != nil { return nil, errors.Annotatef(err, "cannot get remote application %q", name) } return newRemoteApplication(st, appDoc), nil }
[ "func", "(", "st", "*", "State", ")", "RemoteApplication", "(", "name", "string", ")", "(", "_", "*", "RemoteApplication", ",", "err", "error", ")", "{", "if", "!", "names", ".", "IsValidApplication", "(", "name", ")", "{", "return", "nil", ",", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n\n", "applications", ",", "closer", ":=", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "remoteApplicationsC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "appDoc", ":=", "&", "remoteApplicationDoc", "{", "}", "\n", "err", "=", "applications", ".", "FindId", "(", "name", ")", ".", "One", "(", "appDoc", ")", "\n", "if", "err", "==", "mgo", ".", "ErrNotFound", "{", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "return", "newRemoteApplication", "(", "st", ",", "appDoc", ")", ",", "nil", "\n", "}" ]
// RemoteApplication returns a remote application state by name.
[ "RemoteApplication", "returns", "a", "remote", "application", "state", "by", "name", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/remoteapplication.go#L856-L873
157,076
juju/juju
state/remoteapplication.go
RemoteApplicationByToken
func (st *State) RemoteApplicationByToken(token string) (_ *RemoteApplication, err error) { apps, closer := st.db().GetCollection(remoteApplicationsC) defer closer() appDoc := &remoteApplicationDoc{} err = apps.Find(bson.D{{"token", token}}).One(appDoc) if err == mgo.ErrNotFound { return nil, errors.NotFoundf("remote application with token %q", token) } if err != nil { return nil, errors.Annotatef(err, "cannot get remote application with token %q", token) } return newRemoteApplication(st, appDoc), nil }
go
func (st *State) RemoteApplicationByToken(token string) (_ *RemoteApplication, err error) { apps, closer := st.db().GetCollection(remoteApplicationsC) defer closer() appDoc := &remoteApplicationDoc{} err = apps.Find(bson.D{{"token", token}}).One(appDoc) if err == mgo.ErrNotFound { return nil, errors.NotFoundf("remote application with token %q", token) } if err != nil { return nil, errors.Annotatef(err, "cannot get remote application with token %q", token) } return newRemoteApplication(st, appDoc), nil }
[ "func", "(", "st", "*", "State", ")", "RemoteApplicationByToken", "(", "token", "string", ")", "(", "_", "*", "RemoteApplication", ",", "err", "error", ")", "{", "apps", ",", "closer", ":=", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "remoteApplicationsC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "appDoc", ":=", "&", "remoteApplicationDoc", "{", "}", "\n", "err", "=", "apps", ".", "Find", "(", "bson", ".", "D", "{", "{", "\"", "\"", ",", "token", "}", "}", ")", ".", "One", "(", "appDoc", ")", "\n", "if", "err", "==", "mgo", ".", "ErrNotFound", "{", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "token", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "token", ")", "\n", "}", "\n", "return", "newRemoteApplication", "(", "st", ",", "appDoc", ")", ",", "nil", "\n", "}" ]
// RemoteApplicationByToken returns a remote application state by token.
[ "RemoteApplicationByToken", "returns", "a", "remote", "application", "state", "by", "token", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/remoteapplication.go#L876-L889
157,077
juju/juju
state/remoteapplication.go
AllRemoteApplications
func (st *State) AllRemoteApplications() (applications []*RemoteApplication, err error) { applicationsCollection, closer := st.db().GetCollection(remoteApplicationsC) defer closer() appDocs := []remoteApplicationDoc{} err = applicationsCollection.Find(bson.D{}).All(&appDocs) if err != nil { return nil, errors.Errorf("cannot get all remote applications") } for _, v := range appDocs { applications = append(applications, newRemoteApplication(st, &v)) } return applications, nil }
go
func (st *State) AllRemoteApplications() (applications []*RemoteApplication, err error) { applicationsCollection, closer := st.db().GetCollection(remoteApplicationsC) defer closer() appDocs := []remoteApplicationDoc{} err = applicationsCollection.Find(bson.D{}).All(&appDocs) if err != nil { return nil, errors.Errorf("cannot get all remote applications") } for _, v := range appDocs { applications = append(applications, newRemoteApplication(st, &v)) } return applications, nil }
[ "func", "(", "st", "*", "State", ")", "AllRemoteApplications", "(", ")", "(", "applications", "[", "]", "*", "RemoteApplication", ",", "err", "error", ")", "{", "applicationsCollection", ",", "closer", ":=", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "remoteApplicationsC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "appDocs", ":=", "[", "]", "remoteApplicationDoc", "{", "}", "\n", "err", "=", "applicationsCollection", ".", "Find", "(", "bson", ".", "D", "{", "}", ")", ".", "All", "(", "&", "appDocs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "for", "_", ",", "v", ":=", "range", "appDocs", "{", "applications", "=", "append", "(", "applications", ",", "newRemoteApplication", "(", "st", ",", "&", "v", ")", ")", "\n", "}", "\n", "return", "applications", ",", "nil", "\n", "}" ]
// AllRemoteApplications returns all the remote applications used by the model.
[ "AllRemoteApplications", "returns", "all", "the", "remote", "applications", "used", "by", "the", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/remoteapplication.go#L892-L905
157,078
juju/juju
cmd/juju/commands/ssh.go
Run
func (c *sshCommand) Run(ctx *cmd.Context) error { err := c.initRun() if err != nil { return errors.Trace(err) } defer c.cleanupRun() target, err := c.resolveTarget(c.Target) if err != nil { return err } var pty bool if c.pty.b != nil { pty = *c.pty.b } else { // Flag was not specified: create a pty // on the remote side iff this process // has a terminal. isTerminal := isTerminal if c.isTerminal != nil { isTerminal = c.isTerminal } pty = isTerminal(ctx.Stdin) } options, err := c.getSSHOptions(pty, target) if err != nil { return err } cmd := ssh.Command(target.userHost(), c.Args, options) cmd.Stdin = ctx.Stdin cmd.Stdout = ctx.Stdout cmd.Stderr = ctx.Stderr return cmd.Run() }
go
func (c *sshCommand) Run(ctx *cmd.Context) error { err := c.initRun() if err != nil { return errors.Trace(err) } defer c.cleanupRun() target, err := c.resolveTarget(c.Target) if err != nil { return err } var pty bool if c.pty.b != nil { pty = *c.pty.b } else { // Flag was not specified: create a pty // on the remote side iff this process // has a terminal. isTerminal := isTerminal if c.isTerminal != nil { isTerminal = c.isTerminal } pty = isTerminal(ctx.Stdin) } options, err := c.getSSHOptions(pty, target) if err != nil { return err } cmd := ssh.Command(target.userHost(), c.Args, options) cmd.Stdin = ctx.Stdin cmd.Stdout = ctx.Stdout cmd.Stderr = ctx.Stderr return cmd.Run() }
[ "func", "(", "c", "*", "sshCommand", ")", "Run", "(", "ctx", "*", "cmd", ".", "Context", ")", "error", "{", "err", ":=", "c", ".", "initRun", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "defer", "c", ".", "cleanupRun", "(", ")", "\n\n", "target", ",", "err", ":=", "c", ".", "resolveTarget", "(", "c", ".", "Target", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "var", "pty", "bool", "\n", "if", "c", ".", "pty", ".", "b", "!=", "nil", "{", "pty", "=", "*", "c", ".", "pty", ".", "b", "\n", "}", "else", "{", "// Flag was not specified: create a pty", "// on the remote side iff this process", "// has a terminal.", "isTerminal", ":=", "isTerminal", "\n", "if", "c", ".", "isTerminal", "!=", "nil", "{", "isTerminal", "=", "c", ".", "isTerminal", "\n", "}", "\n", "pty", "=", "isTerminal", "(", "ctx", ".", "Stdin", ")", "\n", "}", "\n\n", "options", ",", "err", ":=", "c", ".", "getSSHOptions", "(", "pty", ",", "target", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "cmd", ":=", "ssh", ".", "Command", "(", "target", ".", "userHost", "(", ")", ",", "c", ".", "Args", ",", "options", ")", "\n", "cmd", ".", "Stdin", "=", "ctx", ".", "Stdin", "\n", "cmd", ".", "Stdout", "=", "ctx", ".", "Stdout", "\n", "cmd", ".", "Stderr", "=", "ctx", ".", "Stderr", "\n", "return", "cmd", ".", "Run", "(", ")", "\n", "}" ]
// Run resolves c.Target to a machine, to the address of a i // machine or unit forks ssh passing any arguments provided.
[ "Run", "resolves", "c", ".", "Target", "to", "a", "machine", "to", "the", "address", "of", "a", "i", "machine", "or", "unit", "forks", "ssh", "passing", "any", "arguments", "provided", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/commands/ssh.go#L115-L151
157,079
juju/juju
provider/gce/google/errors.go
NewInvalidConfigValueError
func NewInvalidConfigValueError(key, value string, reason error) error { err := &InvalidConfigValueError{ Err: *errors.Mask(reason).(*errors.Err), Key: key, Value: value, } err.Err.SetLocation(1) return err }
go
func NewInvalidConfigValueError(key, value string, reason error) error { err := &InvalidConfigValueError{ Err: *errors.Mask(reason).(*errors.Err), Key: key, Value: value, } err.Err.SetLocation(1) return err }
[ "func", "NewInvalidConfigValueError", "(", "key", ",", "value", "string", ",", "reason", "error", ")", "error", "{", "err", ":=", "&", "InvalidConfigValueError", "{", "Err", ":", "*", "errors", ".", "Mask", "(", "reason", ")", ".", "(", "*", "errors", ".", "Err", ")", ",", "Key", ":", "key", ",", "Value", ":", "value", ",", "}", "\n", "err", ".", "Err", ".", "SetLocation", "(", "1", ")", "\n", "return", "err", "\n", "}" ]
// NewInvalidConfigValueError returns a new InvalidConfigValueError for the given // info. If the provided reason is an error then Reason is set to that // error. Otherwise a non-nil value is treated as a string and Reason is // set to a non-nil value that wraps it.
[ "NewInvalidConfigValueError", "returns", "a", "new", "InvalidConfigValueError", "for", "the", "given", "info", ".", "If", "the", "provided", "reason", "is", "an", "error", "then", "Reason", "is", "set", "to", "that", "error", ".", "Otherwise", "a", "non", "-", "nil", "value", "is", "treated", "as", "a", "string", "and", "Reason", "is", "set", "to", "a", "non", "-", "nil", "value", "that", "wraps", "it", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/errors.go#L39-L47
157,080
juju/juju
provider/gce/google/errors.go
NewMissingConfigValue
func NewMissingConfigValue(key, field string) error { return NewInvalidConfigValueError(key, "", errors.New("missing "+field)) }
go
func NewMissingConfigValue(key, field string) error { return NewInvalidConfigValueError(key, "", errors.New("missing "+field)) }
[ "func", "NewMissingConfigValue", "(", "key", ",", "field", "string", ")", "error", "{", "return", "NewInvalidConfigValueError", "(", "key", ",", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", "+", "field", ")", ")", "\n", "}" ]
// NewMissingConfigValue returns a new error for a missing config field.
[ "NewMissingConfigValue", "returns", "a", "new", "error", "for", "a", "missing", "config", "field", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/errors.go#L55-L57
157,081
juju/juju
provider/gce/google/errors.go
HandleCredentialError
func HandleCredentialError(err error, ctx context.ProviderCallContext) error { maybeInvalidateCredential(err, ctx) return err }
go
func HandleCredentialError(err error, ctx context.ProviderCallContext) error { maybeInvalidateCredential(err, ctx) return err }
[ "func", "HandleCredentialError", "(", "err", "error", ",", "ctx", "context", ".", "ProviderCallContext", ")", "error", "{", "maybeInvalidateCredential", "(", "err", ",", "ctx", ")", "\n", "return", "err", "\n", "}" ]
// HandleCredentialError determines if a given error relates to an invalid credential. // If it is, the credential is invalidated. Original error is returned untouched.
[ "HandleCredentialError", "determines", "if", "a", "given", "error", "relates", "to", "an", "invalid", "credential", ".", "If", "it", "is", "the", "credential", "is", "invalidated", ".", "Original", "error", "is", "returned", "untouched", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/errors.go#L66-L69
157,082
juju/juju
provider/gce/google/errors.go
HasDenialStatusCode
func HasDenialStatusCode(err error) bool { if err == nil { return false } // http/url.Error is constructed with status code in mind and, at the time of writing for go-1.10, // contains response status code and description in error.Error. // We have to examine the error message to determine whether the error is related to authentication failure. if cause, ok := errors.Cause(err).(*url.Error); ok { for code, desc := range AuthorisationFailureStatusCodes { if strings.Contains(cause.Error(), fmt.Sprintf(": %v %v", code, desc)) { return true } } } return false }
go
func HasDenialStatusCode(err error) bool { if err == nil { return false } // http/url.Error is constructed with status code in mind and, at the time of writing for go-1.10, // contains response status code and description in error.Error. // We have to examine the error message to determine whether the error is related to authentication failure. if cause, ok := errors.Cause(err).(*url.Error); ok { for code, desc := range AuthorisationFailureStatusCodes { if strings.Contains(cause.Error(), fmt.Sprintf(": %v %v", code, desc)) { return true } } } return false }
[ "func", "HasDenialStatusCode", "(", "err", "error", ")", "bool", "{", "if", "err", "==", "nil", "{", "return", "false", "\n", "}", "\n\n", "// http/url.Error is constructed with status code in mind and, at the time of writing for go-1.10,", "// contains response status code and description in error.Error.", "// We have to examine the error message to determine whether the error is related to authentication failure.", "if", "cause", ",", "ok", ":=", "errors", ".", "Cause", "(", "err", ")", ".", "(", "*", "url", ".", "Error", ")", ";", "ok", "{", "for", "code", ",", "desc", ":=", "range", "AuthorisationFailureStatusCodes", "{", "if", "strings", ".", "Contains", "(", "cause", ".", "Error", "(", ")", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "code", ",", "desc", ")", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "false", "\n\n", "}" ]
// HasDenialStatusCode determines if the given error was caused by an invalid credential, i.e. whether it contains a // response status code that indicates an authentication failure.
[ "HasDenialStatusCode", "determines", "if", "the", "given", "error", "was", "caused", "by", "an", "invalid", "credential", "i", ".", "e", ".", "whether", "it", "contains", "a", "response", "status", "code", "that", "indicates", "an", "authentication", "failure", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/errors.go#L88-L105
157,083
juju/juju
apiserver/watcher.go
NewAllWatcher
func NewAllWatcher(context facade.Context) (facade.Facade, error) { id := context.ID() auth := context.Auth() resources := context.Resources() if !auth.AuthClient() { // Note that we don't need to check specific permissions // here, as the AllWatcher can only do anything if the // watcher resource has already been created, so we can // rely on the permission check there to ensure that // this facade can't do anything it shouldn't be allowed // to. // // This is useful because the AllWatcher is reused for // both the WatchAll (requires model access rights) and // the WatchAllModels (requring controller superuser // rights) API calls. return nil, common.ErrPerm } watcher, ok := resources.Get(id).(*state.Multiwatcher) if !ok { return nil, common.ErrUnknownWatcher } return &SrvAllWatcher{ watcherCommon: newWatcherCommon(context), watcher: watcher, }, nil }
go
func NewAllWatcher(context facade.Context) (facade.Facade, error) { id := context.ID() auth := context.Auth() resources := context.Resources() if !auth.AuthClient() { // Note that we don't need to check specific permissions // here, as the AllWatcher can only do anything if the // watcher resource has already been created, so we can // rely on the permission check there to ensure that // this facade can't do anything it shouldn't be allowed // to. // // This is useful because the AllWatcher is reused for // both the WatchAll (requires model access rights) and // the WatchAllModels (requring controller superuser // rights) API calls. return nil, common.ErrPerm } watcher, ok := resources.Get(id).(*state.Multiwatcher) if !ok { return nil, common.ErrUnknownWatcher } return &SrvAllWatcher{ watcherCommon: newWatcherCommon(context), watcher: watcher, }, nil }
[ "func", "NewAllWatcher", "(", "context", "facade", ".", "Context", ")", "(", "facade", ".", "Facade", ",", "error", ")", "{", "id", ":=", "context", ".", "ID", "(", ")", "\n", "auth", ":=", "context", ".", "Auth", "(", ")", "\n", "resources", ":=", "context", ".", "Resources", "(", ")", "\n\n", "if", "!", "auth", ".", "AuthClient", "(", ")", "{", "// Note that we don't need to check specific permissions", "// here, as the AllWatcher can only do anything if the", "// watcher resource has already been created, so we can", "// rely on the permission check there to ensure that", "// this facade can't do anything it shouldn't be allowed", "// to.", "//", "// This is useful because the AllWatcher is reused for", "// both the WatchAll (requires model access rights) and", "// the WatchAllModels (requring controller superuser", "// rights) API calls.", "return", "nil", ",", "common", ".", "ErrPerm", "\n", "}", "\n", "watcher", ",", "ok", ":=", "resources", ".", "Get", "(", "id", ")", ".", "(", "*", "state", ".", "Multiwatcher", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "common", ".", "ErrUnknownWatcher", "\n", "}", "\n", "return", "&", "SrvAllWatcher", "{", "watcherCommon", ":", "newWatcherCommon", "(", "context", ")", ",", "watcher", ":", "watcher", ",", "}", ",", "nil", "\n", "}" ]
// NewAllWatcher returns a new API server endpoint for interacting // with a watcher created by the WatchAll and WatchAllModels API calls.
[ "NewAllWatcher", "returns", "a", "new", "API", "server", "endpoint", "for", "interacting", "with", "a", "watcher", "created", "by", "the", "WatchAll", "and", "WatchAllModels", "API", "calls", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/watcher.go#L24-L51
157,084
juju/juju
apiserver/watcher.go
Next
func (w *srvNotifyWatcher) Next() error { if _, ok := <-w.watcher.Changes(); ok { return nil } var err error if e, ok := w.watcher.(hasErr); ok { err = e.Err() } if err == nil { err = common.ErrStoppedWatcher } return err }
go
func (w *srvNotifyWatcher) Next() error { if _, ok := <-w.watcher.Changes(); ok { return nil } var err error if e, ok := w.watcher.(hasErr); ok { err = e.Err() } if err == nil { err = common.ErrStoppedWatcher } return err }
[ "func", "(", "w", "*", "srvNotifyWatcher", ")", "Next", "(", ")", "error", "{", "if", "_", ",", "ok", ":=", "<-", "w", ".", "watcher", ".", "Changes", "(", ")", ";", "ok", "{", "return", "nil", "\n", "}", "\n\n", "var", "err", "error", "\n", "if", "e", ",", "ok", ":=", "w", ".", "watcher", ".", "(", "hasErr", ")", ";", "ok", "{", "err", "=", "e", ".", "Err", "(", ")", "\n", "}", "\n", "if", "err", "==", "nil", "{", "err", "=", "common", ".", "ErrStoppedWatcher", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Next returns when a change has occurred to the // entity being watched since the most recent call to Next // or the Watch call that created the NotifyWatcher.
[ "Next", "returns", "when", "a", "change", "has", "occurred", "to", "the", "entity", "being", "watched", "since", "the", "most", "recent", "call", "to", "Next", "or", "the", "Watch", "call", "that", "created", "the", "NotifyWatcher", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/watcher.go#L134-L147
157,085
juju/juju
apiserver/watcher.go
Next
func (w *srvStringsWatcher) Next() (params.StringsWatchResult, error) { if changes, ok := <-w.watcher.Changes(); ok { return params.StringsWatchResult{ Changes: changes, }, nil } var err error if e, ok := w.watcher.(hasErr); ok { err = e.Err() } if err == nil { err = common.ErrStoppedWatcher } return params.StringsWatchResult{}, err }
go
func (w *srvStringsWatcher) Next() (params.StringsWatchResult, error) { if changes, ok := <-w.watcher.Changes(); ok { return params.StringsWatchResult{ Changes: changes, }, nil } var err error if e, ok := w.watcher.(hasErr); ok { err = e.Err() } if err == nil { err = common.ErrStoppedWatcher } return params.StringsWatchResult{}, err }
[ "func", "(", "w", "*", "srvStringsWatcher", ")", "Next", "(", ")", "(", "params", ".", "StringsWatchResult", ",", "error", ")", "{", "if", "changes", ",", "ok", ":=", "<-", "w", ".", "watcher", ".", "Changes", "(", ")", ";", "ok", "{", "return", "params", ".", "StringsWatchResult", "{", "Changes", ":", "changes", ",", "}", ",", "nil", "\n", "}", "\n", "var", "err", "error", "\n", "if", "e", ",", "ok", ":=", "w", ".", "watcher", ".", "(", "hasErr", ")", ";", "ok", "{", "err", "=", "e", ".", "Err", "(", ")", "\n", "}", "\n", "if", "err", "==", "nil", "{", "err", "=", "common", ".", "ErrStoppedWatcher", "\n", "}", "\n", "return", "params", ".", "StringsWatchResult", "{", "}", ",", "err", "\n", "}" ]
// Next returns when a change has occurred to an entity of the // collection being watched since the most recent call to Next // or the Watch call that created the srvStringsWatcher.
[ "Next", "returns", "when", "a", "change", "has", "occurred", "to", "an", "entity", "of", "the", "collection", "being", "watched", "since", "the", "most", "recent", "call", "to", "Next", "or", "the", "Watch", "call", "that", "created", "the", "srvStringsWatcher", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/watcher.go#L181-L195
157,086
juju/juju
apiserver/watcher.go
Next
func (w *srvRelationUnitsWatcher) Next() (params.RelationUnitsWatchResult, error) { if changes, ok := <-w.watcher.Changes(); ok { return params.RelationUnitsWatchResult{ Changes: changes, }, nil } err := w.watcher.Err() if err == nil { err = common.ErrStoppedWatcher } return params.RelationUnitsWatchResult{}, err }
go
func (w *srvRelationUnitsWatcher) Next() (params.RelationUnitsWatchResult, error) { if changes, ok := <-w.watcher.Changes(); ok { return params.RelationUnitsWatchResult{ Changes: changes, }, nil } err := w.watcher.Err() if err == nil { err = common.ErrStoppedWatcher } return params.RelationUnitsWatchResult{}, err }
[ "func", "(", "w", "*", "srvRelationUnitsWatcher", ")", "Next", "(", ")", "(", "params", ".", "RelationUnitsWatchResult", ",", "error", ")", "{", "if", "changes", ",", "ok", ":=", "<-", "w", ".", "watcher", ".", "Changes", "(", ")", ";", "ok", "{", "return", "params", ".", "RelationUnitsWatchResult", "{", "Changes", ":", "changes", ",", "}", ",", "nil", "\n", "}", "\n", "err", ":=", "w", ".", "watcher", ".", "Err", "(", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "common", ".", "ErrStoppedWatcher", "\n", "}", "\n", "return", "params", ".", "RelationUnitsWatchResult", "{", "}", ",", "err", "\n", "}" ]
// Next returns when a change has occurred to an entity of the // collection being watched since the most recent call to Next // or the Watch call that created the srvRelationUnitsWatcher.
[ "Next", "returns", "when", "a", "change", "has", "occurred", "to", "an", "entity", "of", "the", "collection", "being", "watched", "since", "the", "most", "recent", "call", "to", "Next", "or", "the", "Watch", "call", "that", "created", "the", "srvRelationUnitsWatcher", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/watcher.go#L228-L239
157,087
juju/juju
apiserver/watcher.go
Next
func (w *srvRelationStatusWatcher) Next() (params.RelationLifeSuspendedStatusWatchResult, error) { if changes, ok := <-w.watcher.Changes(); ok { changesParams := make([]params.RelationLifeSuspendedStatusChange, len(changes)) for i, key := range changes { change, err := crossmodel.GetRelationLifeSuspendedStatusChange(crossmodel.GetBackend(w.st), key) if err != nil { return params.RelationLifeSuspendedStatusWatchResult{ Error: common.ServerError(err), }, nil } changesParams[i] = *change } return params.RelationLifeSuspendedStatusWatchResult{ Changes: changesParams, }, nil } err := w.watcher.Err() if err == nil { err = common.ErrStoppedWatcher } return params.RelationLifeSuspendedStatusWatchResult{}, err }
go
func (w *srvRelationStatusWatcher) Next() (params.RelationLifeSuspendedStatusWatchResult, error) { if changes, ok := <-w.watcher.Changes(); ok { changesParams := make([]params.RelationLifeSuspendedStatusChange, len(changes)) for i, key := range changes { change, err := crossmodel.GetRelationLifeSuspendedStatusChange(crossmodel.GetBackend(w.st), key) if err != nil { return params.RelationLifeSuspendedStatusWatchResult{ Error: common.ServerError(err), }, nil } changesParams[i] = *change } return params.RelationLifeSuspendedStatusWatchResult{ Changes: changesParams, }, nil } err := w.watcher.Err() if err == nil { err = common.ErrStoppedWatcher } return params.RelationLifeSuspendedStatusWatchResult{}, err }
[ "func", "(", "w", "*", "srvRelationStatusWatcher", ")", "Next", "(", ")", "(", "params", ".", "RelationLifeSuspendedStatusWatchResult", ",", "error", ")", "{", "if", "changes", ",", "ok", ":=", "<-", "w", ".", "watcher", ".", "Changes", "(", ")", ";", "ok", "{", "changesParams", ":=", "make", "(", "[", "]", "params", ".", "RelationLifeSuspendedStatusChange", ",", "len", "(", "changes", ")", ")", "\n", "for", "i", ",", "key", ":=", "range", "changes", "{", "change", ",", "err", ":=", "crossmodel", ".", "GetRelationLifeSuspendedStatusChange", "(", "crossmodel", ".", "GetBackend", "(", "w", ".", "st", ")", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "RelationLifeSuspendedStatusWatchResult", "{", "Error", ":", "common", ".", "ServerError", "(", "err", ")", ",", "}", ",", "nil", "\n", "}", "\n", "changesParams", "[", "i", "]", "=", "*", "change", "\n", "}", "\n", "return", "params", ".", "RelationLifeSuspendedStatusWatchResult", "{", "Changes", ":", "changesParams", ",", "}", ",", "nil", "\n", "}", "\n", "err", ":=", "w", ".", "watcher", ".", "Err", "(", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "common", ".", "ErrStoppedWatcher", "\n", "}", "\n", "return", "params", ".", "RelationLifeSuspendedStatusWatchResult", "{", "}", ",", "err", "\n", "}" ]
// Next returns when a change has occurred to an entity of the // collection being watched since the most recent call to Next // or the Watch call that created the srvRelationStatusWatcher.
[ "Next", "returns", "when", "a", "change", "has", "occurred", "to", "an", "entity", "of", "the", "collection", "being", "watched", "since", "the", "most", "recent", "call", "to", "Next", "or", "the", "Watch", "call", "that", "created", "the", "srvRelationStatusWatcher", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/watcher.go#L272-L293
157,088
juju/juju
apiserver/watcher.go
Next
func (w *srvOfferStatusWatcher) Next() (params.OfferStatusWatchResult, error) { if _, ok := <-w.watcher.Changes(); ok { change, err := crossmodel.GetOfferStatusChange(crossmodel.GetBackend(w.st), w.watcher.OfferUUID()) if err != nil { return params.OfferStatusWatchResult{ Error: common.ServerError(err), }, nil } return params.OfferStatusWatchResult{ Changes: []params.OfferStatusChange{*change}, }, nil } err := w.watcher.Err() if err == nil { err = common.ErrStoppedWatcher } return params.OfferStatusWatchResult{}, err }
go
func (w *srvOfferStatusWatcher) Next() (params.OfferStatusWatchResult, error) { if _, ok := <-w.watcher.Changes(); ok { change, err := crossmodel.GetOfferStatusChange(crossmodel.GetBackend(w.st), w.watcher.OfferUUID()) if err != nil { return params.OfferStatusWatchResult{ Error: common.ServerError(err), }, nil } return params.OfferStatusWatchResult{ Changes: []params.OfferStatusChange{*change}, }, nil } err := w.watcher.Err() if err == nil { err = common.ErrStoppedWatcher } return params.OfferStatusWatchResult{}, err }
[ "func", "(", "w", "*", "srvOfferStatusWatcher", ")", "Next", "(", ")", "(", "params", ".", "OfferStatusWatchResult", ",", "error", ")", "{", "if", "_", ",", "ok", ":=", "<-", "w", ".", "watcher", ".", "Changes", "(", ")", ";", "ok", "{", "change", ",", "err", ":=", "crossmodel", ".", "GetOfferStatusChange", "(", "crossmodel", ".", "GetBackend", "(", "w", ".", "st", ")", ",", "w", ".", "watcher", ".", "OfferUUID", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "OfferStatusWatchResult", "{", "Error", ":", "common", ".", "ServerError", "(", "err", ")", ",", "}", ",", "nil", "\n", "}", "\n", "return", "params", ".", "OfferStatusWatchResult", "{", "Changes", ":", "[", "]", "params", ".", "OfferStatusChange", "{", "*", "change", "}", ",", "}", ",", "nil", "\n", "}", "\n", "err", ":=", "w", ".", "watcher", ".", "Err", "(", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "common", ".", "ErrStoppedWatcher", "\n", "}", "\n", "return", "params", ".", "OfferStatusWatchResult", "{", "}", ",", "err", "\n", "}" ]
// Next returns when a change has occurred to an entity of the // collection being watched since the most recent call to Next // or the Watch call that created the srvOfferStatusWatcher.
[ "Next", "returns", "when", "a", "change", "has", "occurred", "to", "an", "entity", "of", "the", "collection", "being", "watched", "since", "the", "most", "recent", "call", "to", "Next", "or", "the", "Watch", "call", "that", "created", "the", "srvOfferStatusWatcher", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/watcher.go#L326-L343
157,089
juju/juju
apiserver/watcher.go
Next
func (w *srvMachineStorageIdsWatcher) Next() (params.MachineStorageIdsWatchResult, error) { if stringChanges, ok := <-w.watcher.Changes(); ok { changes, err := w.parser(stringChanges) if err != nil { return params.MachineStorageIdsWatchResult{}, err } return params.MachineStorageIdsWatchResult{ Changes: changes, }, nil } err := w.watcher.Err() if err == nil { err = common.ErrStoppedWatcher } return params.MachineStorageIdsWatchResult{}, err }
go
func (w *srvMachineStorageIdsWatcher) Next() (params.MachineStorageIdsWatchResult, error) { if stringChanges, ok := <-w.watcher.Changes(); ok { changes, err := w.parser(stringChanges) if err != nil { return params.MachineStorageIdsWatchResult{}, err } return params.MachineStorageIdsWatchResult{ Changes: changes, }, nil } err := w.watcher.Err() if err == nil { err = common.ErrStoppedWatcher } return params.MachineStorageIdsWatchResult{}, err }
[ "func", "(", "w", "*", "srvMachineStorageIdsWatcher", ")", "Next", "(", ")", "(", "params", ".", "MachineStorageIdsWatchResult", ",", "error", ")", "{", "if", "stringChanges", ",", "ok", ":=", "<-", "w", ".", "watcher", ".", "Changes", "(", ")", ";", "ok", "{", "changes", ",", "err", ":=", "w", ".", "parser", "(", "stringChanges", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "MachineStorageIdsWatchResult", "{", "}", ",", "err", "\n", "}", "\n", "return", "params", ".", "MachineStorageIdsWatchResult", "{", "Changes", ":", "changes", ",", "}", ",", "nil", "\n", "}", "\n", "err", ":=", "w", ".", "watcher", ".", "Err", "(", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "common", ".", "ErrStoppedWatcher", "\n", "}", "\n", "return", "params", ".", "MachineStorageIdsWatchResult", "{", "}", ",", "err", "\n", "}" ]
// Next returns when a change has occurred to an entity of the // collection being watched since the most recent call to Next // or the Watch call that created the srvMachineStorageIdsWatcher.
[ "Next", "returns", "when", "a", "change", "has", "occurred", "to", "an", "entity", "of", "the", "collection", "being", "watched", "since", "the", "most", "recent", "call", "to", "Next", "or", "the", "Watch", "call", "that", "created", "the", "srvMachineStorageIdsWatcher", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/watcher.go#L403-L418
157,090
juju/juju
apiserver/watcher.go
Next
func (w *srvEntitiesWatcher) Next() (params.EntitiesWatchResult, error) { if changes, ok := <-w.watcher.Changes(); ok { mapped, err := w.watcher.MapChanges(changes) if err != nil { return params.EntitiesWatchResult{}, errors.Annotate(err, "cannot map changes") } return params.EntitiesWatchResult{ Changes: mapped, }, nil } err := w.watcher.Err() if err == nil { err = common.ErrStoppedWatcher } return params.EntitiesWatchResult{}, err }
go
func (w *srvEntitiesWatcher) Next() (params.EntitiesWatchResult, error) { if changes, ok := <-w.watcher.Changes(); ok { mapped, err := w.watcher.MapChanges(changes) if err != nil { return params.EntitiesWatchResult{}, errors.Annotate(err, "cannot map changes") } return params.EntitiesWatchResult{ Changes: mapped, }, nil } err := w.watcher.Err() if err == nil { err = common.ErrStoppedWatcher } return params.EntitiesWatchResult{}, err }
[ "func", "(", "w", "*", "srvEntitiesWatcher", ")", "Next", "(", ")", "(", "params", ".", "EntitiesWatchResult", ",", "error", ")", "{", "if", "changes", ",", "ok", ":=", "<-", "w", ".", "watcher", ".", "Changes", "(", ")", ";", "ok", "{", "mapped", ",", "err", ":=", "w", ".", "watcher", ".", "MapChanges", "(", "changes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "EntitiesWatchResult", "{", "}", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "params", ".", "EntitiesWatchResult", "{", "Changes", ":", "mapped", ",", "}", ",", "nil", "\n", "}", "\n", "err", ":=", "w", ".", "watcher", ".", "Err", "(", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "common", ".", "ErrStoppedWatcher", "\n", "}", "\n", "return", "params", ".", "EntitiesWatchResult", "{", "}", ",", "err", "\n", "}" ]
// Next returns when a change has occurred to an entity of the // collection being watched since the most recent call to Next // or the Watch call that created the srvEntitiesWatcher.
[ "Next", "returns", "when", "a", "change", "has", "occurred", "to", "an", "entity", "of", "the", "collection", "being", "watched", "since", "the", "most", "recent", "call", "to", "Next", "or", "the", "Watch", "call", "that", "created", "the", "srvEntitiesWatcher", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/watcher.go#L463-L478
157,091
juju/juju
apiserver/watcher.go
Next
func (w *srvMigrationStatusWatcher) Next() (params.MigrationStatus, error) { empty := params.MigrationStatus{} if _, ok := <-w.watcher.Changes(); !ok { err := w.watcher.Err() if err == nil { err = common.ErrStoppedWatcher } return empty, err } mig, err := w.st.LatestMigration() if errors.IsNotFound(err) { return params.MigrationStatus{ Phase: migration.NONE.String(), }, nil } else if err != nil { return empty, errors.Annotate(err, "migration lookup") } phase, err := mig.Phase() if err != nil { return empty, errors.Annotate(err, "retrieving migration phase") } sourceAddrs, err := w.getLocalHostPorts() if err != nil { return empty, errors.Annotate(err, "retrieving source addresses") } sourceCACert, err := getControllerCACert(w.st) if err != nil { return empty, errors.Annotate(err, "retrieving source CA cert") } target, err := mig.TargetInfo() if err != nil { return empty, errors.Annotate(err, "retrieving target info") } return params.MigrationStatus{ MigrationId: mig.Id(), Attempt: mig.Attempt(), Phase: phase.String(), SourceAPIAddrs: sourceAddrs, SourceCACert: sourceCACert, TargetAPIAddrs: target.Addrs, TargetCACert: target.CACert, }, nil }
go
func (w *srvMigrationStatusWatcher) Next() (params.MigrationStatus, error) { empty := params.MigrationStatus{} if _, ok := <-w.watcher.Changes(); !ok { err := w.watcher.Err() if err == nil { err = common.ErrStoppedWatcher } return empty, err } mig, err := w.st.LatestMigration() if errors.IsNotFound(err) { return params.MigrationStatus{ Phase: migration.NONE.String(), }, nil } else if err != nil { return empty, errors.Annotate(err, "migration lookup") } phase, err := mig.Phase() if err != nil { return empty, errors.Annotate(err, "retrieving migration phase") } sourceAddrs, err := w.getLocalHostPorts() if err != nil { return empty, errors.Annotate(err, "retrieving source addresses") } sourceCACert, err := getControllerCACert(w.st) if err != nil { return empty, errors.Annotate(err, "retrieving source CA cert") } target, err := mig.TargetInfo() if err != nil { return empty, errors.Annotate(err, "retrieving target info") } return params.MigrationStatus{ MigrationId: mig.Id(), Attempt: mig.Attempt(), Phase: phase.String(), SourceAPIAddrs: sourceAddrs, SourceCACert: sourceCACert, TargetAPIAddrs: target.Addrs, TargetCACert: target.CACert, }, nil }
[ "func", "(", "w", "*", "srvMigrationStatusWatcher", ")", "Next", "(", ")", "(", "params", ".", "MigrationStatus", ",", "error", ")", "{", "empty", ":=", "params", ".", "MigrationStatus", "{", "}", "\n\n", "if", "_", ",", "ok", ":=", "<-", "w", ".", "watcher", ".", "Changes", "(", ")", ";", "!", "ok", "{", "err", ":=", "w", ".", "watcher", ".", "Err", "(", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "common", ".", "ErrStoppedWatcher", "\n", "}", "\n", "return", "empty", ",", "err", "\n", "}", "\n\n", "mig", ",", "err", ":=", "w", ".", "st", ".", "LatestMigration", "(", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "params", ".", "MigrationStatus", "{", "Phase", ":", "migration", ".", "NONE", ".", "String", "(", ")", ",", "}", ",", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "empty", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "phase", ",", "err", ":=", "mig", ".", "Phase", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "empty", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "sourceAddrs", ",", "err", ":=", "w", ".", "getLocalHostPorts", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "empty", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "sourceCACert", ",", "err", ":=", "getControllerCACert", "(", "w", ".", "st", ")", "\n", "if", "err", "!=", "nil", "{", "return", "empty", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "target", ",", "err", ":=", "mig", ".", "TargetInfo", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "empty", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "params", ".", "MigrationStatus", "{", "MigrationId", ":", "mig", ".", "Id", "(", ")", ",", "Attempt", ":", "mig", ".", "Attempt", "(", ")", ",", "Phase", ":", "phase", ".", "String", "(", ")", ",", "SourceAPIAddrs", ":", "sourceAddrs", ",", "SourceCACert", ":", "sourceCACert", ",", "TargetAPIAddrs", ":", "target", ".", "Addrs", ",", "TargetCACert", ":", "target", ".", "CACert", ",", "}", ",", "nil", "\n", "}" ]
// Next returns when the status for a model migration for the // associated model changes. The current details for the active // migration are returned.
[ "Next", "returns", "when", "the", "status", "for", "a", "model", "migration", "for", "the", "associated", "model", "changes", ".", "The", "current", "details", "for", "the", "active", "migration", "are", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/watcher.go#L521-L570
157,092
juju/juju
apiserver/facades/client/highavailability/highavailability.go
NewHighAvailabilityAPI
func NewHighAvailabilityAPI(st *state.State, resources facade.Resources, authorizer facade.Authorizer) (*HighAvailabilityAPI, error) { // Only clients can access the high availability facade. if !authorizer.AuthClient() { return nil, common.ErrPerm } model, err := st.Model() if err != nil { return nil, errors.Trace(err) } if model.Type() == state.ModelTypeCAAS { return nil, errors.NotSupportedf("high availability on kubernetes controllers") } return &HighAvailabilityAPI{ state: st, resources: resources, authorizer: authorizer, }, nil }
go
func NewHighAvailabilityAPI(st *state.State, resources facade.Resources, authorizer facade.Authorizer) (*HighAvailabilityAPI, error) { // Only clients can access the high availability facade. if !authorizer.AuthClient() { return nil, common.ErrPerm } model, err := st.Model() if err != nil { return nil, errors.Trace(err) } if model.Type() == state.ModelTypeCAAS { return nil, errors.NotSupportedf("high availability on kubernetes controllers") } return &HighAvailabilityAPI{ state: st, resources: resources, authorizer: authorizer, }, nil }
[ "func", "NewHighAvailabilityAPI", "(", "st", "*", "state", ".", "State", ",", "resources", "facade", ".", "Resources", ",", "authorizer", "facade", ".", "Authorizer", ")", "(", "*", "HighAvailabilityAPI", ",", "error", ")", "{", "// Only clients can access the high availability facade.", "if", "!", "authorizer", ".", "AuthClient", "(", ")", "{", "return", "nil", ",", "common", ".", "ErrPerm", "\n", "}", "\n\n", "model", ",", "err", ":=", "st", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "model", ".", "Type", "(", ")", "==", "state", ".", "ModelTypeCAAS", "{", "return", "nil", ",", "errors", ".", "NotSupportedf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "HighAvailabilityAPI", "{", "state", ":", "st", ",", "resources", ":", "resources", ",", "authorizer", ":", "authorizer", ",", "}", ",", "nil", "\n", "}" ]
// NewHighAvailabilityAPI creates a new server-side highavailability API end point.
[ "NewHighAvailabilityAPI", "creates", "a", "new", "server", "-", "side", "highavailability", "API", "end", "point", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/highavailability/highavailability.go#L46-L65
157,093
juju/juju
apiserver/facades/client/highavailability/highavailability.go
EnableHA
func (api *HighAvailabilityAPI) EnableHA(args params.ControllersSpecs) (params.ControllersChangeResults, error) { results := params.ControllersChangeResults{} admin, err := api.authorizer.HasPermission(permission.SuperuserAccess, api.state.ControllerTag()) if err != nil && !errors.IsNotFound(err) { return results, errors.Trace(err) } if !admin { return results, common.ServerError(common.ErrPerm) } if len(args.Specs) == 0 { return results, nil } if len(args.Specs) > 1 { return results, errors.New("only one controller spec is supported") } result, err := api.enableHASingle(api.state, args.Specs[0]) results.Results = make([]params.ControllersChangeResult, 1) results.Results[0].Result = result results.Results[0].Error = common.ServerError(err) return results, nil }
go
func (api *HighAvailabilityAPI) EnableHA(args params.ControllersSpecs) (params.ControllersChangeResults, error) { results := params.ControllersChangeResults{} admin, err := api.authorizer.HasPermission(permission.SuperuserAccess, api.state.ControllerTag()) if err != nil && !errors.IsNotFound(err) { return results, errors.Trace(err) } if !admin { return results, common.ServerError(common.ErrPerm) } if len(args.Specs) == 0 { return results, nil } if len(args.Specs) > 1 { return results, errors.New("only one controller spec is supported") } result, err := api.enableHASingle(api.state, args.Specs[0]) results.Results = make([]params.ControllersChangeResult, 1) results.Results[0].Result = result results.Results[0].Error = common.ServerError(err) return results, nil }
[ "func", "(", "api", "*", "HighAvailabilityAPI", ")", "EnableHA", "(", "args", "params", ".", "ControllersSpecs", ")", "(", "params", ".", "ControllersChangeResults", ",", "error", ")", "{", "results", ":=", "params", ".", "ControllersChangeResults", "{", "}", "\n\n", "admin", ",", "err", ":=", "api", ".", "authorizer", ".", "HasPermission", "(", "permission", ".", "SuperuserAccess", ",", "api", ".", "state", ".", "ControllerTag", "(", ")", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "results", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "!", "admin", "{", "return", "results", ",", "common", ".", "ServerError", "(", "common", ".", "ErrPerm", ")", "\n", "}", "\n\n", "if", "len", "(", "args", ".", "Specs", ")", "==", "0", "{", "return", "results", ",", "nil", "\n", "}", "\n", "if", "len", "(", "args", ".", "Specs", ")", ">", "1", "{", "return", "results", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "result", ",", "err", ":=", "api", ".", "enableHASingle", "(", "api", ".", "state", ",", "args", ".", "Specs", "[", "0", "]", ")", "\n", "results", ".", "Results", "=", "make", "(", "[", "]", "params", ".", "ControllersChangeResult", ",", "1", ")", "\n", "results", ".", "Results", "[", "0", "]", ".", "Result", "=", "result", "\n", "results", ".", "Results", "[", "0", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "return", "results", ",", "nil", "\n", "}" ]
// EnableHA adds controller machines as necessary to ensure the // controller has the number of machines specified.
[ "EnableHA", "adds", "controller", "machines", "as", "necessary", "to", "ensure", "the", "controller", "has", "the", "number", "of", "machines", "specified", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/highavailability/highavailability.go#L69-L92
157,094
juju/juju
apiserver/facades/client/highavailability/highavailability.go
getReferenceController
func getReferenceController(st *state.State, machineIds []string) (*state.Machine, error) { // Sort the controller IDs from low to high and take the first. // This will typically give the initial bootstrap machine. var controllerIds []int for _, id := range machineIds { idNum, err := strconv.Atoi(id) if err != nil { logger.Warningf("ignoring non numeric controller id %v", id) continue } controllerIds = append(controllerIds, idNum) } if len(controllerIds) == 0 { return nil, errors.Errorf("internal error; failed to find any controllers") } sort.Ints(controllerIds) controllerId := controllerIds[0] // Load the controller machine and get its constraints. controller, err := st.Machine(strconv.Itoa(controllerId)) if err != nil { return nil, errors.Annotatef(err, "reading controller id %v", controllerId) } return controller, nil }
go
func getReferenceController(st *state.State, machineIds []string) (*state.Machine, error) { // Sort the controller IDs from low to high and take the first. // This will typically give the initial bootstrap machine. var controllerIds []int for _, id := range machineIds { idNum, err := strconv.Atoi(id) if err != nil { logger.Warningf("ignoring non numeric controller id %v", id) continue } controllerIds = append(controllerIds, idNum) } if len(controllerIds) == 0 { return nil, errors.Errorf("internal error; failed to find any controllers") } sort.Ints(controllerIds) controllerId := controllerIds[0] // Load the controller machine and get its constraints. controller, err := st.Machine(strconv.Itoa(controllerId)) if err != nil { return nil, errors.Annotatef(err, "reading controller id %v", controllerId) } return controller, nil }
[ "func", "getReferenceController", "(", "st", "*", "state", ".", "State", ",", "machineIds", "[", "]", "string", ")", "(", "*", "state", ".", "Machine", ",", "error", ")", "{", "// Sort the controller IDs from low to high and take the first.", "// This will typically give the initial bootstrap machine.", "var", "controllerIds", "[", "]", "int", "\n", "for", "_", ",", "id", ":=", "range", "machineIds", "{", "idNum", ",", "err", ":=", "strconv", ".", "Atoi", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Warningf", "(", "\"", "\"", ",", "id", ")", "\n", "continue", "\n", "}", "\n", "controllerIds", "=", "append", "(", "controllerIds", ",", "idNum", ")", "\n", "}", "\n", "if", "len", "(", "controllerIds", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "sort", ".", "Ints", "(", "controllerIds", ")", "\n", "controllerId", ":=", "controllerIds", "[", "0", "]", "\n\n", "// Load the controller machine and get its constraints.", "controller", ",", "err", ":=", "st", ".", "Machine", "(", "strconv", ".", "Itoa", "(", "controllerId", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "controllerId", ")", "\n", "}", "\n", "return", "controller", ",", "nil", "\n", "}" ]
// getReferenceController looks up the ideal controller to use as a reference for Constraints and Series
[ "getReferenceController", "looks", "up", "the", "ideal", "controller", "to", "use", "as", "a", "reference", "for", "Constraints", "and", "Series" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/highavailability/highavailability.go#L154-L178
157,095
juju/juju
apiserver/facades/client/highavailability/highavailability.go
validateCurrentControllers
func validateCurrentControllers(st *state.State, cfg controller.Config, machineIds []string) error { if cfg.JujuHASpace() != "" { return nil } var badIds []string for _, id := range machineIds { controller, err := st.Machine(id) if err != nil { return errors.Annotatef(err, "reading controller id %v", id) } addresses := controller.Addresses() if len(addresses) == 0 { // machines without any address are essentially not started yet continue } internal := network.SelectInternalAddresses(addresses, false) if len(internal) != 1 { badIds = append(badIds, id) } } if len(badIds) > 0 { return errors.Errorf( "juju-ha-space is not set and a unique usable address was not found for machines: %s"+ "\nrun \"juju controller-config juju-ha-space=<name>\" to set a space for Mongo peer communication", strings.Join(badIds, ", "), ) } return nil }
go
func validateCurrentControllers(st *state.State, cfg controller.Config, machineIds []string) error { if cfg.JujuHASpace() != "" { return nil } var badIds []string for _, id := range machineIds { controller, err := st.Machine(id) if err != nil { return errors.Annotatef(err, "reading controller id %v", id) } addresses := controller.Addresses() if len(addresses) == 0 { // machines without any address are essentially not started yet continue } internal := network.SelectInternalAddresses(addresses, false) if len(internal) != 1 { badIds = append(badIds, id) } } if len(badIds) > 0 { return errors.Errorf( "juju-ha-space is not set and a unique usable address was not found for machines: %s"+ "\nrun \"juju controller-config juju-ha-space=<name>\" to set a space for Mongo peer communication", strings.Join(badIds, ", "), ) } return nil }
[ "func", "validateCurrentControllers", "(", "st", "*", "state", ".", "State", ",", "cfg", "controller", ".", "Config", ",", "machineIds", "[", "]", "string", ")", "error", "{", "if", "cfg", ".", "JujuHASpace", "(", ")", "!=", "\"", "\"", "{", "return", "nil", "\n", "}", "\n\n", "var", "badIds", "[", "]", "string", "\n", "for", "_", ",", "id", ":=", "range", "machineIds", "{", "controller", ",", "err", ":=", "st", ".", "Machine", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "id", ")", "\n", "}", "\n", "addresses", ":=", "controller", ".", "Addresses", "(", ")", "\n", "if", "len", "(", "addresses", ")", "==", "0", "{", "// machines without any address are essentially not started yet", "continue", "\n", "}", "\n", "internal", ":=", "network", ".", "SelectInternalAddresses", "(", "addresses", ",", "false", ")", "\n", "if", "len", "(", "internal", ")", "!=", "1", "{", "badIds", "=", "append", "(", "badIds", ",", "id", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "badIds", ")", ">", "0", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\\n", "\\\"", "\\\"", "\"", ",", "strings", ".", "Join", "(", "badIds", ",", "\"", "\"", ")", ",", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validateCurrentControllers checks for a scenario where there is no HA space // in controller configuration and more than one machine-local address on any // of the controller machines. An error is returned if it is detected. // When HA space is set, there are other code paths that ensure controllers // have at least one address in the space.
[ "validateCurrentControllers", "checks", "for", "a", "scenario", "where", "there", "is", "no", "HA", "space", "in", "controller", "configuration", "and", "more", "than", "one", "machine", "-", "local", "address", "on", "any", "of", "the", "controller", "machines", ".", "An", "error", "is", "returned", "if", "it", "is", "detected", ".", "When", "HA", "space", "is", "set", "there", "are", "other", "code", "paths", "that", "ensure", "controllers", "have", "at", "least", "one", "address", "in", "the", "space", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/highavailability/highavailability.go#L185-L214
157,096
juju/juju
apiserver/facades/client/highavailability/highavailability.go
validatePlacementForSpaces
func validatePlacementForSpaces(st *state.State, spaces *[]string, placement []string) error { if spaces == nil || len(*spaces) == 0 || len(placement) == 0 { return nil } for _, v := range placement { p, err := instance.ParsePlacement(v) if err != nil { if err == instance.ErrPlacementScopeMissing { // Where an unscoped placement is not parsed as a machine ID, // such as for a MaaS node name, just allow it through. // TODO (manadart 2018-03-27): Possible work at the provider // level to accommodate placement and space constraints during // instance pre-check may be entertained in the future. continue } return errors.Annotate(err, "parsing placement") } if p.Directive == "" { continue } m, err := st.Machine(p.Directive) if err != nil { if errors.IsNotFound(err) { // Don't throw out of here when the machine does not exist. // Validate others if required and leave it handled downstream. continue } return errors.Annotate(err, "retrieving machine") } for _, space := range *spaces { spaceName := network.SpaceName(space) inSpace := false for _, addr := range m.Addresses() { if addr.SpaceName == spaceName { inSpace = true break } } if !inSpace { return fmt.Errorf("machine %q has no addresses in space %q", p.Directive, space) } } } return nil }
go
func validatePlacementForSpaces(st *state.State, spaces *[]string, placement []string) error { if spaces == nil || len(*spaces) == 0 || len(placement) == 0 { return nil } for _, v := range placement { p, err := instance.ParsePlacement(v) if err != nil { if err == instance.ErrPlacementScopeMissing { // Where an unscoped placement is not parsed as a machine ID, // such as for a MaaS node name, just allow it through. // TODO (manadart 2018-03-27): Possible work at the provider // level to accommodate placement and space constraints during // instance pre-check may be entertained in the future. continue } return errors.Annotate(err, "parsing placement") } if p.Directive == "" { continue } m, err := st.Machine(p.Directive) if err != nil { if errors.IsNotFound(err) { // Don't throw out of here when the machine does not exist. // Validate others if required and leave it handled downstream. continue } return errors.Annotate(err, "retrieving machine") } for _, space := range *spaces { spaceName := network.SpaceName(space) inSpace := false for _, addr := range m.Addresses() { if addr.SpaceName == spaceName { inSpace = true break } } if !inSpace { return fmt.Errorf("machine %q has no addresses in space %q", p.Directive, space) } } } return nil }
[ "func", "validatePlacementForSpaces", "(", "st", "*", "state", ".", "State", ",", "spaces", "*", "[", "]", "string", ",", "placement", "[", "]", "string", ")", "error", "{", "if", "spaces", "==", "nil", "||", "len", "(", "*", "spaces", ")", "==", "0", "||", "len", "(", "placement", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "for", "_", ",", "v", ":=", "range", "placement", "{", "p", ",", "err", ":=", "instance", ".", "ParsePlacement", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "instance", ".", "ErrPlacementScopeMissing", "{", "// Where an unscoped placement is not parsed as a machine ID,", "// such as for a MaaS node name, just allow it through.", "// TODO (manadart 2018-03-27): Possible work at the provider", "// level to accommodate placement and space constraints during", "// instance pre-check may be entertained in the future.", "continue", "\n", "}", "\n", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "p", ".", "Directive", "==", "\"", "\"", "{", "continue", "\n", "}", "\n\n", "m", ",", "err", ":=", "st", ".", "Machine", "(", "p", ".", "Directive", ")", "\n", "if", "err", "!=", "nil", "{", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "// Don't throw out of here when the machine does not exist.", "// Validate others if required and leave it handled downstream.", "continue", "\n", "}", "\n", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "for", "_", ",", "space", ":=", "range", "*", "spaces", "{", "spaceName", ":=", "network", ".", "SpaceName", "(", "space", ")", "\n", "inSpace", ":=", "false", "\n", "for", "_", ",", "addr", ":=", "range", "m", ".", "Addresses", "(", ")", "{", "if", "addr", ".", "SpaceName", "==", "spaceName", "{", "inSpace", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "inSpace", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "p", ".", "Directive", ",", "space", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validatePlacementForSpaces checks whether there are both space constraints // and machine placement directives. // If there are, checks are made to ensure that the machines specified have at // least one address in all of the spaces.
[ "validatePlacementForSpaces", "checks", "whether", "there", "are", "both", "space", "constraints", "and", "machine", "placement", "directives", ".", "If", "there", "are", "checks", "are", "made", "to", "ensure", "that", "the", "machines", "specified", "have", "at", "least", "one", "address", "in", "all", "of", "the", "spaces", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/highavailability/highavailability.go#L220-L267
157,097
juju/juju
apiserver/facades/client/highavailability/highavailability.go
controllersChanges
func controllersChanges(change state.ControllersChanges) params.ControllersChanges { return params.ControllersChanges{ Added: machineIdsToTags(change.Added...), Maintained: machineIdsToTags(change.Maintained...), Removed: machineIdsToTags(change.Removed...), Promoted: machineIdsToTags(change.Promoted...), Demoted: machineIdsToTags(change.Demoted...), Converted: machineIdsToTags(change.Converted...), } }
go
func controllersChanges(change state.ControllersChanges) params.ControllersChanges { return params.ControllersChanges{ Added: machineIdsToTags(change.Added...), Maintained: machineIdsToTags(change.Maintained...), Removed: machineIdsToTags(change.Removed...), Promoted: machineIdsToTags(change.Promoted...), Demoted: machineIdsToTags(change.Demoted...), Converted: machineIdsToTags(change.Converted...), } }
[ "func", "controllersChanges", "(", "change", "state", ".", "ControllersChanges", ")", "params", ".", "ControllersChanges", "{", "return", "params", ".", "ControllersChanges", "{", "Added", ":", "machineIdsToTags", "(", "change", ".", "Added", "...", ")", ",", "Maintained", ":", "machineIdsToTags", "(", "change", ".", "Maintained", "...", ")", ",", "Removed", ":", "machineIdsToTags", "(", "change", ".", "Removed", "...", ")", ",", "Promoted", ":", "machineIdsToTags", "(", "change", ".", "Promoted", "...", ")", ",", "Demoted", ":", "machineIdsToTags", "(", "change", ".", "Demoted", "...", ")", ",", "Converted", ":", "machineIdsToTags", "(", "change", ".", "Converted", "...", ")", ",", "}", "\n", "}" ]
// controllersChanges generates a new params instance from the state instance.
[ "controllersChanges", "generates", "a", "new", "params", "instance", "from", "the", "state", "instance", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/highavailability/highavailability.go#L270-L279
157,098
juju/juju
apiserver/facades/client/highavailability/highavailability.go
machineIdsToTags
func machineIdsToTags(ids ...string) []string { var result []string for _, id := range ids { result = append(result, names.NewMachineTag(id).String()) } return result }
go
func machineIdsToTags(ids ...string) []string { var result []string for _, id := range ids { result = append(result, names.NewMachineTag(id).String()) } return result }
[ "func", "machineIdsToTags", "(", "ids", "...", "string", ")", "[", "]", "string", "{", "var", "result", "[", "]", "string", "\n", "for", "_", ",", "id", ":=", "range", "ids", "{", "result", "=", "append", "(", "result", ",", "names", ".", "NewMachineTag", "(", "id", ")", ".", "String", "(", ")", ")", "\n", "}", "\n", "return", "result", "\n", "}" ]
// machineIdsToTags returns a slice of machine tag strings created from the // input machine IDs.
[ "machineIdsToTags", "returns", "a", "slice", "of", "machine", "tag", "strings", "created", "from", "the", "input", "machine", "IDs", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/highavailability/highavailability.go#L283-L289
157,099
juju/juju
apiserver/facades/client/highavailability/highavailability.go
StopHAReplicationForUpgrade
func (api *HighAvailabilityAPI) StopHAReplicationForUpgrade(args params.UpgradeMongoParams) ( params.MongoUpgradeResults, error, ) { ha, err := api.state.SetUpgradeMongoMode(mongo.Version{ Major: args.Target.Major, Minor: args.Target.Minor, Patch: args.Target.Patch, StorageEngine: mongo.StorageEngine(args.Target.StorageEngine), }) if err != nil { return params.MongoUpgradeResults{}, errors.Annotate(err, "cannot stop HA for upgrade") } members := make([]params.HAMember, len(ha.Members)) for i, m := range ha.Members { members[i] = params.HAMember{ Tag: m.Tag, PublicAddress: m.PublicAddress, Series: m.Series, } } return params.MongoUpgradeResults{ Master: params.HAMember{ Tag: ha.Master.Tag, PublicAddress: ha.Master.PublicAddress, Series: ha.Master.Series, }, Members: members, RsMembers: ha.RsMembers, }, nil }
go
func (api *HighAvailabilityAPI) StopHAReplicationForUpgrade(args params.UpgradeMongoParams) ( params.MongoUpgradeResults, error, ) { ha, err := api.state.SetUpgradeMongoMode(mongo.Version{ Major: args.Target.Major, Minor: args.Target.Minor, Patch: args.Target.Patch, StorageEngine: mongo.StorageEngine(args.Target.StorageEngine), }) if err != nil { return params.MongoUpgradeResults{}, errors.Annotate(err, "cannot stop HA for upgrade") } members := make([]params.HAMember, len(ha.Members)) for i, m := range ha.Members { members[i] = params.HAMember{ Tag: m.Tag, PublicAddress: m.PublicAddress, Series: m.Series, } } return params.MongoUpgradeResults{ Master: params.HAMember{ Tag: ha.Master.Tag, PublicAddress: ha.Master.PublicAddress, Series: ha.Master.Series, }, Members: members, RsMembers: ha.RsMembers, }, nil }
[ "func", "(", "api", "*", "HighAvailabilityAPI", ")", "StopHAReplicationForUpgrade", "(", "args", "params", ".", "UpgradeMongoParams", ")", "(", "params", ".", "MongoUpgradeResults", ",", "error", ",", ")", "{", "ha", ",", "err", ":=", "api", ".", "state", ".", "SetUpgradeMongoMode", "(", "mongo", ".", "Version", "{", "Major", ":", "args", ".", "Target", ".", "Major", ",", "Minor", ":", "args", ".", "Target", ".", "Minor", ",", "Patch", ":", "args", ".", "Target", ".", "Patch", ",", "StorageEngine", ":", "mongo", ".", "StorageEngine", "(", "args", ".", "Target", ".", "StorageEngine", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "MongoUpgradeResults", "{", "}", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "members", ":=", "make", "(", "[", "]", "params", ".", "HAMember", ",", "len", "(", "ha", ".", "Members", ")", ")", "\n", "for", "i", ",", "m", ":=", "range", "ha", ".", "Members", "{", "members", "[", "i", "]", "=", "params", ".", "HAMember", "{", "Tag", ":", "m", ".", "Tag", ",", "PublicAddress", ":", "m", ".", "PublicAddress", ",", "Series", ":", "m", ".", "Series", ",", "}", "\n", "}", "\n", "return", "params", ".", "MongoUpgradeResults", "{", "Master", ":", "params", ".", "HAMember", "{", "Tag", ":", "ha", ".", "Master", ".", "Tag", ",", "PublicAddress", ":", "ha", ".", "Master", ".", "PublicAddress", ",", "Series", ":", "ha", ".", "Master", ".", "Series", ",", "}", ",", "Members", ":", "members", ",", "RsMembers", ":", "ha", ".", "RsMembers", ",", "}", ",", "nil", "\n", "}" ]
// StopHAReplicationForUpgrade will prompt the HA cluster to enter upgrade // mongo mode.
[ "StopHAReplicationForUpgrade", "will", "prompt", "the", "HA", "cluster", "to", "enter", "upgrade", "mongo", "mode", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/highavailability/highavailability.go#L293-L322