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
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
4,900
juju/juju
worker/metrics/spool/listener.go
NewSocketListener
func NewSocketListener(socketPath string, handler ConnectionHandler) (*socketListener, error) { listener, err := sockets.Listen(socketPath) if err != nil { return nil, errors.Trace(err) } sListener := &socketListener{listener: listener, handler: handler} sListener.t.Go(sListener.loop) return sListener, nil }
go
func NewSocketListener(socketPath string, handler ConnectionHandler) (*socketListener, error) { listener, err := sockets.Listen(socketPath) if err != nil { return nil, errors.Trace(err) } sListener := &socketListener{listener: listener, handler: handler} sListener.t.Go(sListener.loop) return sListener, nil }
[ "func", "NewSocketListener", "(", "socketPath", "string", ",", "handler", "ConnectionHandler", ")", "(", "*", "socketListener", ",", "error", ")", "{", "listener", ",", "err", ":=", "sockets", ".", "Listen", "(", "socketPath", ")", "\n", "if", "err", "!=", ...
// NewSocketListener returns a new socket listener struct.
[ "NewSocketListener", "returns", "a", "new", "socket", "listener", "struct", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/spool/listener.go#L36-L44
4,901
juju/juju
worker/metrics/spool/listener.go
Stop
func (l *socketListener) Stop() error { l.t.Kill(nil) err := l.listener.Close() if err != nil { logger.Errorf("failed to close the collect-metrics listener: %v", err) } return l.t.Wait() }
go
func (l *socketListener) Stop() error { l.t.Kill(nil) err := l.listener.Close() if err != nil { logger.Errorf("failed to close the collect-metrics listener: %v", err) } return l.t.Wait() }
[ "func", "(", "l", "*", "socketListener", ")", "Stop", "(", ")", "error", "{", "l", ".", "t", ".", "Kill", "(", "nil", ")", "\n", "err", ":=", "l", ".", "listener", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "E...
// Stop closes the listener and releases all resources // used by the socketListener.
[ "Stop", "closes", "the", "listener", "and", "releases", "all", "resources", "used", "by", "the", "socketListener", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/spool/listener.go#L48-L55
4,902
juju/juju
worker/metrics/spool/listener.go
NewPeriodicWorker
func NewPeriodicWorker(do jworker.PeriodicWorkerCall, period time.Duration, newTimer func(time.Duration) jworker.PeriodicTimer, stop func()) worker.Worker { return &periodicWorker{ Worker: jworker.NewPeriodicWorker(do, period, newTimer, jworker.Jitter(0.2)), stop: stop, } }
go
func NewPeriodicWorker(do jworker.PeriodicWorkerCall, period time.Duration, newTimer func(time.Duration) jworker.PeriodicTimer, stop func()) worker.Worker { return &periodicWorker{ Worker: jworker.NewPeriodicWorker(do, period, newTimer, jworker.Jitter(0.2)), stop: stop, } }
[ "func", "NewPeriodicWorker", "(", "do", "jworker", ".", "PeriodicWorkerCall", ",", "period", "time", ".", "Duration", ",", "newTimer", "func", "(", "time", ".", "Duration", ")", "jworker", ".", "PeriodicTimer", ",", "stop", "func", "(", ")", ")", "worker", ...
// NewPeriodicWorker returns a periodic worker, that will call a stop function // when it is killed.
[ "NewPeriodicWorker", "returns", "a", "periodic", "worker", "that", "will", "call", "a", "stop", "function", "when", "it", "is", "killed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metrics/spool/listener.go#L75-L80
4,903
juju/juju
worker/credentialvalidator/worker.go
NewWorker
func NewWorker(config Config) (worker.Worker, error) { if err := config.Validate(); err != nil { return nil, errors.Trace(err) } mc, err := modelCredential(config.Facade) if err != nil { return nil, errors.Trace(err) } // This worker needs to monitor both the changes to the credential content that // this model uses as well as what credential the model uses. // It needs to be restarted if there is a change in either. mcw, err := config.Facade.WatchModelCredential() if err != nil { return nil, errors.Trace(err) } v := &validator{ validatorFacade: config.Facade, credential: mc, modelCredentialWatcher: mcw, } // The watcher needs to be added to the worker's catacomb plan // here in order to be controlled by this worker's lifecycle events: // for example, to be destroyed when this worker is destroyed, etc. // We also add the watcher to the Plan.Init collection to ensure that // the worker's Plan.Work method is executed after the watcher // is initialised and watcher's changes collection obtains the changes. // Watchers that are added using catacomb.Add method // miss out on a first call of Worker's Plan.Work method and can, thus, // be missing out on an initial change. plan := catacomb.Plan{ Site: &v.catacomb, Work: v.loop, Init: []worker.Worker{v.modelCredentialWatcher}, } if mc.CloudCredential != "" { var err error v.credentialWatcher, err = config.Facade.WatchCredential(mc.CloudCredential) if err != nil { return nil, errors.Trace(err) } plan.Init = append(plan.Init, v.credentialWatcher) } if err := catacomb.Invoke(plan); err != nil { return nil, errors.Trace(err) } return v, nil }
go
func NewWorker(config Config) (worker.Worker, error) { if err := config.Validate(); err != nil { return nil, errors.Trace(err) } mc, err := modelCredential(config.Facade) if err != nil { return nil, errors.Trace(err) } // This worker needs to monitor both the changes to the credential content that // this model uses as well as what credential the model uses. // It needs to be restarted if there is a change in either. mcw, err := config.Facade.WatchModelCredential() if err != nil { return nil, errors.Trace(err) } v := &validator{ validatorFacade: config.Facade, credential: mc, modelCredentialWatcher: mcw, } // The watcher needs to be added to the worker's catacomb plan // here in order to be controlled by this worker's lifecycle events: // for example, to be destroyed when this worker is destroyed, etc. // We also add the watcher to the Plan.Init collection to ensure that // the worker's Plan.Work method is executed after the watcher // is initialised and watcher's changes collection obtains the changes. // Watchers that are added using catacomb.Add method // miss out on a first call of Worker's Plan.Work method and can, thus, // be missing out on an initial change. plan := catacomb.Plan{ Site: &v.catacomb, Work: v.loop, Init: []worker.Worker{v.modelCredentialWatcher}, } if mc.CloudCredential != "" { var err error v.credentialWatcher, err = config.Facade.WatchCredential(mc.CloudCredential) if err != nil { return nil, errors.Trace(err) } plan.Init = append(plan.Init, v.credentialWatcher) } if err := catacomb.Invoke(plan); err != nil { return nil, errors.Trace(err) } return v, nil }
[ "func", "NewWorker", "(", "config", "Config", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "if", "err", ":=", "config", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err",...
// NewWorker returns a Worker that tracks the validity of the Model's cloud // credential, as exposed by the Facade.
[ "NewWorker", "returns", "a", "Worker", "that", "tracks", "the", "validity", "of", "the", "Model", "s", "cloud", "credential", "as", "exposed", "by", "the", "Facade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/credentialvalidator/worker.go#L58-L110
4,904
juju/juju
apiserver/common/storagecommon/filesystems.go
FilesystemParams
func FilesystemParams( f state.Filesystem, storageInstance state.StorageInstance, modelUUID, controllerUUID string, environConfig *config.Config, poolManager poolmanager.PoolManager, registry storage.ProviderRegistry, ) (params.FilesystemParams, error) { var pool string var size uint64 if stateFilesystemParams, ok := f.Params(); ok { pool = stateFilesystemParams.Pool size = stateFilesystemParams.Size } else { filesystemInfo, err := f.Info() if err != nil { return params.FilesystemParams{}, errors.Trace(err) } pool = filesystemInfo.Pool size = filesystemInfo.Size } filesystemTags, err := StorageTags(storageInstance, modelUUID, controllerUUID, environConfig) if err != nil { return params.FilesystemParams{}, errors.Annotate(err, "computing storage tags") } providerType, cfg, err := StoragePoolConfig(pool, poolManager, registry) if err != nil { return params.FilesystemParams{}, errors.Trace(err) } result := params.FilesystemParams{ f.Tag().String(), "", // volume tag size, string(providerType), cfg.Attrs(), filesystemTags, nil, // attachment params set by the caller } volumeTag, err := f.Volume() if err == nil { result.VolumeTag = volumeTag.String() } else if err != state.ErrNoBackingVolume { return params.FilesystemParams{}, errors.Trace(err) } return result, nil }
go
func FilesystemParams( f state.Filesystem, storageInstance state.StorageInstance, modelUUID, controllerUUID string, environConfig *config.Config, poolManager poolmanager.PoolManager, registry storage.ProviderRegistry, ) (params.FilesystemParams, error) { var pool string var size uint64 if stateFilesystemParams, ok := f.Params(); ok { pool = stateFilesystemParams.Pool size = stateFilesystemParams.Size } else { filesystemInfo, err := f.Info() if err != nil { return params.FilesystemParams{}, errors.Trace(err) } pool = filesystemInfo.Pool size = filesystemInfo.Size } filesystemTags, err := StorageTags(storageInstance, modelUUID, controllerUUID, environConfig) if err != nil { return params.FilesystemParams{}, errors.Annotate(err, "computing storage tags") } providerType, cfg, err := StoragePoolConfig(pool, poolManager, registry) if err != nil { return params.FilesystemParams{}, errors.Trace(err) } result := params.FilesystemParams{ f.Tag().String(), "", // volume tag size, string(providerType), cfg.Attrs(), filesystemTags, nil, // attachment params set by the caller } volumeTag, err := f.Volume() if err == nil { result.VolumeTag = volumeTag.String() } else if err != state.ErrNoBackingVolume { return params.FilesystemParams{}, errors.Trace(err) } return result, nil }
[ "func", "FilesystemParams", "(", "f", "state", ".", "Filesystem", ",", "storageInstance", "state", ".", "StorageInstance", ",", "modelUUID", ",", "controllerUUID", "string", ",", "environConfig", "*", "config", ".", "Config", ",", "poolManager", "poolmanager", "."...
// FilesystemParams returns the parameters for creating or destroying the // given filesystem.
[ "FilesystemParams", "returns", "the", "parameters", "for", "creating", "or", "destroying", "the", "given", "filesystem", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/storagecommon/filesystems.go#L19-L69
4,905
juju/juju
apiserver/common/storagecommon/filesystems.go
FilesystemToState
func FilesystemToState(v params.Filesystem) (names.FilesystemTag, state.FilesystemInfo, error) { filesystemTag, err := names.ParseFilesystemTag(v.FilesystemTag) if err != nil { return names.FilesystemTag{}, state.FilesystemInfo{}, errors.Trace(err) } return filesystemTag, state.FilesystemInfo{ v.Info.Size, "", // pool is set by state v.Info.FilesystemId, }, nil }
go
func FilesystemToState(v params.Filesystem) (names.FilesystemTag, state.FilesystemInfo, error) { filesystemTag, err := names.ParseFilesystemTag(v.FilesystemTag) if err != nil { return names.FilesystemTag{}, state.FilesystemInfo{}, errors.Trace(err) } return filesystemTag, state.FilesystemInfo{ v.Info.Size, "", // pool is set by state v.Info.FilesystemId, }, nil }
[ "func", "FilesystemToState", "(", "v", "params", ".", "Filesystem", ")", "(", "names", ".", "FilesystemTag", ",", "state", ".", "FilesystemInfo", ",", "error", ")", "{", "filesystemTag", ",", "err", ":=", "names", ".", "ParseFilesystemTag", "(", "v", ".", ...
// FilesystemToState converts a params.Filesystem to state.FilesystemInfo // and names.FilesystemTag.
[ "FilesystemToState", "converts", "a", "params", ".", "Filesystem", "to", "state", ".", "FilesystemInfo", "and", "names", ".", "FilesystemTag", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/storagecommon/filesystems.go#L73-L83
4,906
juju/juju
apiserver/common/storagecommon/filesystems.go
FilesystemFromState
func FilesystemFromState(f state.Filesystem) (params.Filesystem, error) { info, err := f.Info() if err != nil { return params.Filesystem{}, errors.Trace(err) } result := params.Filesystem{ f.FilesystemTag().String(), "", FilesystemInfoFromState(info), } volumeTag, err := f.Volume() if err == nil { result.VolumeTag = volumeTag.String() } else if err != state.ErrNoBackingVolume { return params.Filesystem{}, errors.Trace(err) } return result, nil }
go
func FilesystemFromState(f state.Filesystem) (params.Filesystem, error) { info, err := f.Info() if err != nil { return params.Filesystem{}, errors.Trace(err) } result := params.Filesystem{ f.FilesystemTag().String(), "", FilesystemInfoFromState(info), } volumeTag, err := f.Volume() if err == nil { result.VolumeTag = volumeTag.String() } else if err != state.ErrNoBackingVolume { return params.Filesystem{}, errors.Trace(err) } return result, nil }
[ "func", "FilesystemFromState", "(", "f", "state", ".", "Filesystem", ")", "(", "params", ".", "Filesystem", ",", "error", ")", "{", "info", ",", "err", ":=", "f", ".", "Info", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", ...
// FilesystemFromState converts a state.Filesystem to params.Filesystem.
[ "FilesystemFromState", "converts", "a", "state", ".", "Filesystem", "to", "params", ".", "Filesystem", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/storagecommon/filesystems.go#L86-L103
4,907
juju/juju
apiserver/common/storagecommon/filesystems.go
FilesystemInfoFromState
func FilesystemInfoFromState(info state.FilesystemInfo) params.FilesystemInfo { return params.FilesystemInfo{ info.FilesystemId, info.Pool, info.Size, } }
go
func FilesystemInfoFromState(info state.FilesystemInfo) params.FilesystemInfo { return params.FilesystemInfo{ info.FilesystemId, info.Pool, info.Size, } }
[ "func", "FilesystemInfoFromState", "(", "info", "state", ".", "FilesystemInfo", ")", "params", ".", "FilesystemInfo", "{", "return", "params", ".", "FilesystemInfo", "{", "info", ".", "FilesystemId", ",", "info", ".", "Pool", ",", "info", ".", "Size", ",", "...
// FilesystemInfoFromState converts a state.FilesystemInfo to params.FilesystemInfo.
[ "FilesystemInfoFromState", "converts", "a", "state", ".", "FilesystemInfo", "to", "params", ".", "FilesystemInfo", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/storagecommon/filesystems.go#L106-L112
4,908
juju/juju
apiserver/common/storagecommon/filesystems.go
FilesystemAttachmentToState
func FilesystemAttachmentToState(in params.FilesystemAttachment) (names.MachineTag, names.FilesystemTag, state.FilesystemAttachmentInfo, error) { machineTag, err := names.ParseMachineTag(in.MachineTag) if err != nil { return names.MachineTag{}, names.FilesystemTag{}, state.FilesystemAttachmentInfo{}, err } filesystemTag, err := names.ParseFilesystemTag(in.FilesystemTag) if err != nil { return names.MachineTag{}, names.FilesystemTag{}, state.FilesystemAttachmentInfo{}, err } info := state.FilesystemAttachmentInfo{ in.Info.MountPoint, in.Info.ReadOnly, } return machineTag, filesystemTag, info, nil }
go
func FilesystemAttachmentToState(in params.FilesystemAttachment) (names.MachineTag, names.FilesystemTag, state.FilesystemAttachmentInfo, error) { machineTag, err := names.ParseMachineTag(in.MachineTag) if err != nil { return names.MachineTag{}, names.FilesystemTag{}, state.FilesystemAttachmentInfo{}, err } filesystemTag, err := names.ParseFilesystemTag(in.FilesystemTag) if err != nil { return names.MachineTag{}, names.FilesystemTag{}, state.FilesystemAttachmentInfo{}, err } info := state.FilesystemAttachmentInfo{ in.Info.MountPoint, in.Info.ReadOnly, } return machineTag, filesystemTag, info, nil }
[ "func", "FilesystemAttachmentToState", "(", "in", "params", ".", "FilesystemAttachment", ")", "(", "names", ".", "MachineTag", ",", "names", ".", "FilesystemTag", ",", "state", ".", "FilesystemAttachmentInfo", ",", "error", ")", "{", "machineTag", ",", "err", ":...
// FilesystemAttachmentToState converts a storage.FilesystemAttachment // to a state.FilesystemAttachmentInfo.
[ "FilesystemAttachmentToState", "converts", "a", "storage", ".", "FilesystemAttachment", "to", "a", "state", ".", "FilesystemAttachmentInfo", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/storagecommon/filesystems.go#L116-L130
4,909
juju/juju
apiserver/common/storagecommon/filesystems.go
FilesystemAttachmentFromState
func FilesystemAttachmentFromState(v state.FilesystemAttachment) (params.FilesystemAttachment, error) { info, err := v.Info() if err != nil { return params.FilesystemAttachment{}, errors.Trace(err) } return params.FilesystemAttachment{ v.Filesystem().String(), v.Host().String(), FilesystemAttachmentInfoFromState(info), }, nil }
go
func FilesystemAttachmentFromState(v state.FilesystemAttachment) (params.FilesystemAttachment, error) { info, err := v.Info() if err != nil { return params.FilesystemAttachment{}, errors.Trace(err) } return params.FilesystemAttachment{ v.Filesystem().String(), v.Host().String(), FilesystemAttachmentInfoFromState(info), }, nil }
[ "func", "FilesystemAttachmentFromState", "(", "v", "state", ".", "FilesystemAttachment", ")", "(", "params", ".", "FilesystemAttachment", ",", "error", ")", "{", "info", ",", "err", ":=", "v", ".", "Info", "(", ")", "\n", "if", "err", "!=", "nil", "{", "...
// FilesystemAttachmentFromState converts a state.FilesystemAttachment to params.FilesystemAttachment.
[ "FilesystemAttachmentFromState", "converts", "a", "state", ".", "FilesystemAttachment", "to", "params", ".", "FilesystemAttachment", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/storagecommon/filesystems.go#L133-L143
4,910
juju/juju
apiserver/common/storagecommon/filesystems.go
FilesystemAttachmentInfoFromState
func FilesystemAttachmentInfoFromState(info state.FilesystemAttachmentInfo) params.FilesystemAttachmentInfo { return params.FilesystemAttachmentInfo{ info.MountPoint, info.ReadOnly, } }
go
func FilesystemAttachmentInfoFromState(info state.FilesystemAttachmentInfo) params.FilesystemAttachmentInfo { return params.FilesystemAttachmentInfo{ info.MountPoint, info.ReadOnly, } }
[ "func", "FilesystemAttachmentInfoFromState", "(", "info", "state", ".", "FilesystemAttachmentInfo", ")", "params", ".", "FilesystemAttachmentInfo", "{", "return", "params", ".", "FilesystemAttachmentInfo", "{", "info", ".", "MountPoint", ",", "info", ".", "ReadOnly", ...
// FilesystemAttachmentInfoFromState converts a state.FilesystemAttachmentInfo // to params.FilesystemAttachmentInfo.
[ "FilesystemAttachmentInfoFromState", "converts", "a", "state", ".", "FilesystemAttachmentInfo", "to", "params", ".", "FilesystemAttachmentInfo", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/storagecommon/filesystems.go#L147-L152
4,911
juju/juju
apiserver/common/storagecommon/filesystems.go
ParseFilesystemAttachmentIds
func ParseFilesystemAttachmentIds(stringIds []string) ([]params.MachineStorageId, error) { ids := make([]params.MachineStorageId, len(stringIds)) for i, s := range stringIds { m, f, err := state.ParseFilesystemAttachmentId(s) if err != nil { return nil, err } ids[i] = params.MachineStorageId{ MachineTag: m.String(), AttachmentTag: f.String(), } } return ids, nil }
go
func ParseFilesystemAttachmentIds(stringIds []string) ([]params.MachineStorageId, error) { ids := make([]params.MachineStorageId, len(stringIds)) for i, s := range stringIds { m, f, err := state.ParseFilesystemAttachmentId(s) if err != nil { return nil, err } ids[i] = params.MachineStorageId{ MachineTag: m.String(), AttachmentTag: f.String(), } } return ids, nil }
[ "func", "ParseFilesystemAttachmentIds", "(", "stringIds", "[", "]", "string", ")", "(", "[", "]", "params", ".", "MachineStorageId", ",", "error", ")", "{", "ids", ":=", "make", "(", "[", "]", "params", ".", "MachineStorageId", ",", "len", "(", "stringIds"...
// ParseFilesystemAttachmentIds parses the strings, returning machine storage IDs.
[ "ParseFilesystemAttachmentIds", "parses", "the", "strings", "returning", "machine", "storage", "IDs", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/storagecommon/filesystems.go#L155-L168
4,912
juju/juju
payload/api/private/helpers.go
API2Result
func API2Result(r params.PayloadResult) (payload.Result, error) { result := payload.Result{ NotFound: r.NotFound, } id, err := api.API2ID(r.Tag) if err != nil { return result, errors.Trace(err) } result.ID = id if r.Payload != nil { pl, err := api.API2Payload(*r.Payload) if err != nil { return result, errors.Trace(err) } result.Payload = &pl } if r.Error != nil { result.Error = common.RestoreError(r.Error) } return result, nil }
go
func API2Result(r params.PayloadResult) (payload.Result, error) { result := payload.Result{ NotFound: r.NotFound, } id, err := api.API2ID(r.Tag) if err != nil { return result, errors.Trace(err) } result.ID = id if r.Payload != nil { pl, err := api.API2Payload(*r.Payload) if err != nil { return result, errors.Trace(err) } result.Payload = &pl } if r.Error != nil { result.Error = common.RestoreError(r.Error) } return result, nil }
[ "func", "API2Result", "(", "r", "params", ".", "PayloadResult", ")", "(", "payload", ".", "Result", ",", "error", ")", "{", "result", ":=", "payload", ".", "Result", "{", "NotFound", ":", "r", ".", "NotFound", ",", "}", "\n\n", "id", ",", "err", ":="...
// API2Result converts the API result to a payload.Result.
[ "API2Result", "converts", "the", "API", "result", "to", "a", "payload", ".", "Result", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/payload/api/private/helpers.go#L17-L41
4,913
juju/juju
payload/api/private/helpers.go
Payloads2TrackArgs
func Payloads2TrackArgs(payloads []payload.Payload) params.TrackPayloadArgs { var args params.TrackPayloadArgs for _, pl := range payloads { fullPayload := payload.FullPayloadInfo{Payload: pl} arg := api.Payload2api(fullPayload) args.Payloads = append(args.Payloads, arg) } return args }
go
func Payloads2TrackArgs(payloads []payload.Payload) params.TrackPayloadArgs { var args params.TrackPayloadArgs for _, pl := range payloads { fullPayload := payload.FullPayloadInfo{Payload: pl} arg := api.Payload2api(fullPayload) args.Payloads = append(args.Payloads, arg) } return args }
[ "func", "Payloads2TrackArgs", "(", "payloads", "[", "]", "payload", ".", "Payload", ")", "params", ".", "TrackPayloadArgs", "{", "var", "args", "params", ".", "TrackPayloadArgs", "\n", "for", "_", ",", "pl", ":=", "range", "payloads", "{", "fullPayload", ":=...
// Payloads2TrackArgs converts the provided payload info into arguments // for the Track API endpoint.
[ "Payloads2TrackArgs", "converts", "the", "provided", "payload", "info", "into", "arguments", "for", "the", "Track", "API", "endpoint", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/payload/api/private/helpers.go#L45-L53
4,914
juju/juju
payload/api/private/helpers.go
FullIDs2LookUpArgs
func FullIDs2LookUpArgs(fullIDs []string) params.LookUpPayloadArgs { var args params.LookUpPayloadArgs for _, fullID := range fullIDs { name, rawID := payload.ParseID(fullID) args.Args = append(args.Args, params.LookUpPayloadArg{ Name: name, ID: rawID, }) } return args }
go
func FullIDs2LookUpArgs(fullIDs []string) params.LookUpPayloadArgs { var args params.LookUpPayloadArgs for _, fullID := range fullIDs { name, rawID := payload.ParseID(fullID) args.Args = append(args.Args, params.LookUpPayloadArg{ Name: name, ID: rawID, }) } return args }
[ "func", "FullIDs2LookUpArgs", "(", "fullIDs", "[", "]", "string", ")", "params", ".", "LookUpPayloadArgs", "{", "var", "args", "params", ".", "LookUpPayloadArgs", "\n", "for", "_", ",", "fullID", ":=", "range", "fullIDs", "{", "name", ",", "rawID", ":=", "...
// FullIDs2LookUpArgs converts the provided payload "full" IDs into arguments // for the LookUp API endpoint.
[ "FullIDs2LookUpArgs", "converts", "the", "provided", "payload", "full", "IDs", "into", "arguments", "for", "the", "LookUp", "API", "endpoint", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/payload/api/private/helpers.go#L63-L73
4,915
juju/juju
payload/api/private/helpers.go
IDs2SetStatusArgs
func IDs2SetStatusArgs(ids []string, status string) params.SetPayloadStatusArgs { var args params.SetPayloadStatusArgs for _, id := range ids { arg := params.SetPayloadStatusArg{ Status: status, } arg.Tag = names.NewPayloadTag(id).String() args.Args = append(args.Args, arg) } return args }
go
func IDs2SetStatusArgs(ids []string, status string) params.SetPayloadStatusArgs { var args params.SetPayloadStatusArgs for _, id := range ids { arg := params.SetPayloadStatusArg{ Status: status, } arg.Tag = names.NewPayloadTag(id).String() args.Args = append(args.Args, arg) } return args }
[ "func", "IDs2SetStatusArgs", "(", "ids", "[", "]", "string", ",", "status", "string", ")", "params", ".", "SetPayloadStatusArgs", "{", "var", "args", "params", ".", "SetPayloadStatusArgs", "\n", "for", "_", ",", "id", ":=", "range", "ids", "{", "arg", ":="...
// IDs2SetStatusArgs converts the provided payload IDs into arguments // for the SetStatus API endpoint.
[ "IDs2SetStatusArgs", "converts", "the", "provided", "payload", "IDs", "into", "arguments", "for", "the", "SetStatus", "API", "endpoint", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/payload/api/private/helpers.go#L77-L87
4,916
juju/juju
upgrades/steps_221.go
stateStepsFor221
func stateStepsFor221() []Step { return []Step{ &upgradeStep{ description: "add update-status hook config settings", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().AddUpdateStatusHookSettings() }, }, &upgradeStep{ description: "correct relation unit counts for subordinates", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().CorrectRelationUnitCounts() }, }, } }
go
func stateStepsFor221() []Step { return []Step{ &upgradeStep{ description: "add update-status hook config settings", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().AddUpdateStatusHookSettings() }, }, &upgradeStep{ description: "correct relation unit counts for subordinates", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().CorrectRelationUnitCounts() }, }, } }
[ "func", "stateStepsFor221", "(", ")", "[", "]", "Step", "{", "return", "[", "]", "Step", "{", "&", "upgradeStep", "{", "description", ":", "\"", "\"", ",", "targets", ":", "[", "]", "Target", "{", "DatabaseMaster", "}", ",", "run", ":", "func", "(", ...
// stateStepsFor221 returns upgrade steps for Juju 2.2.1 that manipulate state directly.
[ "stateStepsFor221", "returns", "upgrade", "steps", "for", "Juju", "2", ".", "2", ".", "1", "that", "manipulate", "state", "directly", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/upgrades/steps_221.go#L7-L24
4,917
juju/juju
provider/gce/environ_network.go
Subnets
func (e *environ) Subnets(ctx context.ProviderCallContext, inst instance.Id, subnetIds []network.Id) ([]network.SubnetInfo, error) { // In GCE all the subnets are in all AZs. zones, err := e.zoneNames(ctx) if err != nil { return nil, errors.Trace(err) } ids := makeIncludeSet(subnetIds) var results []network.SubnetInfo if inst == instance.UnknownId { results, err = e.getMatchingSubnets(ctx, ids, zones) } else { results, err = e.getInstanceSubnets(ctx, inst, ids, zones) } if err != nil { return nil, errors.Trace(err) } if missing := ids.Missing(); len(missing) != 0 { return nil, errors.NotFoundf("subnets %v", formatMissing(missing)) } return results, nil }
go
func (e *environ) Subnets(ctx context.ProviderCallContext, inst instance.Id, subnetIds []network.Id) ([]network.SubnetInfo, error) { // In GCE all the subnets are in all AZs. zones, err := e.zoneNames(ctx) if err != nil { return nil, errors.Trace(err) } ids := makeIncludeSet(subnetIds) var results []network.SubnetInfo if inst == instance.UnknownId { results, err = e.getMatchingSubnets(ctx, ids, zones) } else { results, err = e.getInstanceSubnets(ctx, inst, ids, zones) } if err != nil { return nil, errors.Trace(err) } if missing := ids.Missing(); len(missing) != 0 { return nil, errors.NotFoundf("subnets %v", formatMissing(missing)) } return results, nil }
[ "func", "(", "e", "*", "environ", ")", "Subnets", "(", "ctx", "context", ".", "ProviderCallContext", ",", "inst", "instance", ".", "Id", ",", "subnetIds", "[", "]", "network", ".", "Id", ")", "(", "[", "]", "network", ".", "SubnetInfo", ",", "error", ...
// Subnets implements environs.NetworkingEnviron.
[ "Subnets", "implements", "environs", ".", "NetworkingEnviron", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/environ_network.go#L26-L48
4,918
juju/juju
provider/gce/environ_network.go
NetworkInterfaces
func (e *environ) NetworkInterfaces(ctx context.ProviderCallContext, instId instance.Id) ([]network.InterfaceInfo, error) { insts, err := e.Instances(ctx, []instance.Id{instId}) if err != nil { return nil, errors.Trace(err) } envInst, ok := insts[0].(*environInstance) if !ok { // This shouldn't happen. return nil, errors.Errorf("couldn't extract google instance for %q", instId) } // In GCE all the subnets are in all AZs. zones, err := e.zoneNames(ctx) if err != nil { return nil, errors.Trace(err) } networks, err := e.networksByURL(ctx) if err != nil { return nil, errors.Trace(err) } googleInst := envInst.base ifaces := googleInst.NetworkInterfaces() var subnetURLs []string for _, iface := range ifaces { if iface.Subnetwork != "" { subnetURLs = append(subnetURLs, iface.Subnetwork) } } subnets, err := e.subnetsByURL(ctx, subnetURLs, networks, zones) if err != nil { return nil, errors.Trace(err) } // We know there'll be a subnet for each url requested, otherwise // there would have been an error. var results []network.InterfaceInfo for i, iface := range ifaces { details, err := findNetworkDetails(iface, subnets, networks) if err != nil { return nil, errors.Annotatef(err, "instance %q", instId) } results = append(results, network.InterfaceInfo{ DeviceIndex: i, CIDR: details.cidr, // The network interface has no id in GCE so it's // identified by the machine's id + its name. ProviderId: network.Id(fmt.Sprintf("%s/%s", instId, iface.Name)), ProviderSubnetId: details.subnet, ProviderNetworkId: details.network, AvailabilityZones: copyStrings(zones), InterfaceName: iface.Name, Address: network.NewScopedAddress(iface.NetworkIP, network.ScopeCloudLocal), InterfaceType: network.EthernetInterface, Disabled: false, NoAutoStart: false, ConfigType: network.ConfigDHCP, }) } return results, nil }
go
func (e *environ) NetworkInterfaces(ctx context.ProviderCallContext, instId instance.Id) ([]network.InterfaceInfo, error) { insts, err := e.Instances(ctx, []instance.Id{instId}) if err != nil { return nil, errors.Trace(err) } envInst, ok := insts[0].(*environInstance) if !ok { // This shouldn't happen. return nil, errors.Errorf("couldn't extract google instance for %q", instId) } // In GCE all the subnets are in all AZs. zones, err := e.zoneNames(ctx) if err != nil { return nil, errors.Trace(err) } networks, err := e.networksByURL(ctx) if err != nil { return nil, errors.Trace(err) } googleInst := envInst.base ifaces := googleInst.NetworkInterfaces() var subnetURLs []string for _, iface := range ifaces { if iface.Subnetwork != "" { subnetURLs = append(subnetURLs, iface.Subnetwork) } } subnets, err := e.subnetsByURL(ctx, subnetURLs, networks, zones) if err != nil { return nil, errors.Trace(err) } // We know there'll be a subnet for each url requested, otherwise // there would have been an error. var results []network.InterfaceInfo for i, iface := range ifaces { details, err := findNetworkDetails(iface, subnets, networks) if err != nil { return nil, errors.Annotatef(err, "instance %q", instId) } results = append(results, network.InterfaceInfo{ DeviceIndex: i, CIDR: details.cidr, // The network interface has no id in GCE so it's // identified by the machine's id + its name. ProviderId: network.Id(fmt.Sprintf("%s/%s", instId, iface.Name)), ProviderSubnetId: details.subnet, ProviderNetworkId: details.network, AvailabilityZones: copyStrings(zones), InterfaceName: iface.Name, Address: network.NewScopedAddress(iface.NetworkIP, network.ScopeCloudLocal), InterfaceType: network.EthernetInterface, Disabled: false, NoAutoStart: false, ConfigType: network.ConfigDHCP, }) } return results, nil }
[ "func", "(", "e", "*", "environ", ")", "NetworkInterfaces", "(", "ctx", "context", ".", "ProviderCallContext", ",", "instId", "instance", ".", "Id", ")", "(", "[", "]", "network", ".", "InterfaceInfo", ",", "error", ")", "{", "insts", ",", "err", ":=", ...
// NetworkInterfaces implements environs.NetworkingEnviron.
[ "NetworkInterfaces", "implements", "environs", ".", "NetworkingEnviron", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/environ_network.go#L132-L191
4,919
juju/juju
provider/gce/environ_network.go
findNetworkDetails
func findNetworkDetails(iface compute.NetworkInterface, subnets subnetMap, networks networkMap) (networkDetails, error) { var result networkDetails if iface.Subnetwork == "" { // This interface is on a legacy network. netwk, ok := networks[iface.Network] if !ok { return result, errors.NotFoundf("network %q", iface.Network) } result.cidr = netwk.IPv4Range result.subnet = "" result.network = network.Id(netwk.Name) } else { subnet, ok := subnets[iface.Subnetwork] if !ok { return result, errors.NotFoundf("subnet %q", iface.Subnetwork) } result.cidr = subnet.CIDR result.subnet = subnet.ProviderId result.network = subnet.ProviderNetworkId } return result, nil }
go
func findNetworkDetails(iface compute.NetworkInterface, subnets subnetMap, networks networkMap) (networkDetails, error) { var result networkDetails if iface.Subnetwork == "" { // This interface is on a legacy network. netwk, ok := networks[iface.Network] if !ok { return result, errors.NotFoundf("network %q", iface.Network) } result.cidr = netwk.IPv4Range result.subnet = "" result.network = network.Id(netwk.Name) } else { subnet, ok := subnets[iface.Subnetwork] if !ok { return result, errors.NotFoundf("subnet %q", iface.Subnetwork) } result.cidr = subnet.CIDR result.subnet = subnet.ProviderId result.network = subnet.ProviderNetworkId } return result, nil }
[ "func", "findNetworkDetails", "(", "iface", "compute", ".", "NetworkInterface", ",", "subnets", "subnetMap", ",", "networks", "networkMap", ")", "(", "networkDetails", ",", "error", ")", "{", "var", "result", "networkDetails", "\n", "if", "iface", ".", "Subnetwo...
// findNetworkDetails looks up the network information we need to // populate an InterfaceInfo - if the interface is on a legacy network // we use information from the network because there'll be no subnet // linked.
[ "findNetworkDetails", "looks", "up", "the", "network", "information", "we", "need", "to", "populate", "an", "InterfaceInfo", "-", "if", "the", "interface", "is", "on", "a", "legacy", "network", "we", "use", "information", "from", "the", "network", "because", "...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/environ_network.go#L203-L224
4,920
juju/juju
provider/gce/environ_network.go
AllocateContainerAddresses
func (e *environ) AllocateContainerAddresses(context.ProviderCallContext, instance.Id, names.MachineTag, []network.InterfaceInfo) ([]network.InterfaceInfo, error) { return nil, errors.NotSupportedf("container addresses") }
go
func (e *environ) AllocateContainerAddresses(context.ProviderCallContext, instance.Id, names.MachineTag, []network.InterfaceInfo) ([]network.InterfaceInfo, error) { return nil, errors.NotSupportedf("container addresses") }
[ "func", "(", "e", "*", "environ", ")", "AllocateContainerAddresses", "(", "context", ".", "ProviderCallContext", ",", "instance", ".", "Id", ",", "names", ".", "MachineTag", ",", "[", "]", "network", ".", "InterfaceInfo", ")", "(", "[", "]", "network", "."...
// AllocateContainerAddresses implements environs.NetworkingEnviron.
[ "AllocateContainerAddresses", "implements", "environs", ".", "NetworkingEnviron", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/environ_network.go#L277-L279
4,921
juju/juju
provider/gce/environ_network.go
SSHAddresses
func (*environ) SSHAddresses(ctx context.ProviderCallContext, addresses []network.Address) ([]network.Address, error) { bestAddress, ok := network.SelectPublicAddress(addresses) if ok { return []network.Address{bestAddress}, nil } else { // fallback return addresses, nil } }
go
func (*environ) SSHAddresses(ctx context.ProviderCallContext, addresses []network.Address) ([]network.Address, error) { bestAddress, ok := network.SelectPublicAddress(addresses) if ok { return []network.Address{bestAddress}, nil } else { // fallback return addresses, nil } }
[ "func", "(", "*", "environ", ")", "SSHAddresses", "(", "ctx", "context", ".", "ProviderCallContext", ",", "addresses", "[", "]", "network", ".", "Address", ")", "(", "[", "]", "network", ".", "Address", ",", "error", ")", "{", "bestAddress", ",", "ok", ...
// SSHAddresses implements environs.SSHAddresses. // For GCE we want to make sure we're returning only one public address, so that probing won't // cause SSHGuard to lock us out
[ "SSHAddresses", "implements", "environs", ".", "SSHAddresses", ".", "For", "GCE", "we", "want", "to", "make", "sure", "we", "re", "returning", "only", "one", "public", "address", "so", "that", "probing", "won", "t", "cause", "SSHGuard", "to", "lock", "us", ...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/environ_network.go#L299-L307
4,922
juju/juju
provider/gce/environ_network.go
Include
func (s *includeSet) Include(item string) bool { if s.items.Contains(item) { s.items.Remove(item) return true } return false }
go
func (s *includeSet) Include(item string) bool { if s.items.Contains(item) { s.items.Remove(item) return true } return false }
[ "func", "(", "s", "*", "includeSet", ")", "Include", "(", "item", "string", ")", "bool", "{", "if", "s", ".", "items", ".", "Contains", "(", "item", ")", "{", "s", ".", "items", ".", "Remove", "(", "item", ")", "\n", "return", "true", "\n", "}", ...
// Include implements IncludeSet.
[ "Include", "implements", "IncludeSet", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/environ_network.go#L369-L375
4,923
juju/juju
apiserver/params/firewall.go
Validate
func (v KnownServiceValue) Validate() error { switch v { case SSHRule, JujuControllerRule, JujuApplicationOfferRule: return nil } return errors.NotValidf("known service %q", v) }
go
func (v KnownServiceValue) Validate() error { switch v { case SSHRule, JujuControllerRule, JujuApplicationOfferRule: return nil } return errors.NotValidf("known service %q", v) }
[ "func", "(", "v", "KnownServiceValue", ")", "Validate", "(", ")", "error", "{", "switch", "v", "{", "case", "SSHRule", ",", "JujuControllerRule", ",", "JujuApplicationOfferRule", ":", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "NotValidf", "(...
// Validate returns an error if the service value is not valid.
[ "Validate", "returns", "an", "error", "if", "the", "service", "value", "is", "not", "valid", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/params/firewall.go#L56-L62
4,924
juju/juju
charmstore/fakeclient.go
Get
func (d datastore) Get(path string, data interface{}) error { current := d[path] if current == nil { return errors.NotFoundf(path) } data = current return nil }
go
func (d datastore) Get(path string, data interface{}) error { current := d[path] if current == nil { return errors.NotFoundf(path) } data = current return nil }
[ "func", "(", "d", "datastore", ")", "Get", "(", "path", "string", ",", "data", "interface", "{", "}", ")", "error", "{", "current", ":=", "d", "[", "path", "]", "\n", "if", "current", "==", "nil", "{", "return", "errors", ".", "NotFoundf", "(", "pa...
// Get retrieves contents stored at path and saves it to data. If nothing exists at path, // an error satisfying errors.IsNotFound is returned.
[ "Get", "retrieves", "contents", "stored", "at", "path", "and", "saves", "it", "to", "data", ".", "If", "nothing", "exists", "at", "path", "an", "error", "satisfying", "errors", ".", "IsNotFound", "is", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/charmstore/fakeclient.go#L54-L61
4,925
juju/juju
charmstore/fakeclient.go
Put
func (d datastore) Put(path string, data interface{}) error { d[path] = data return nil }
go
func (d datastore) Put(path string, data interface{}) error { d[path] = data return nil }
[ "func", "(", "d", "datastore", ")", "Put", "(", "path", "string", ",", "data", "interface", "{", "}", ")", "error", "{", "d", "[", "path", "]", "=", "data", "\n", "return", "nil", "\n", "}" ]
// Put stores data at path. It will be accessible later via Get. // Data already at path will is overwritten and no // revision history is saved.
[ "Put", "stores", "data", "at", "path", ".", "It", "will", "be", "accessible", "later", "via", "Get", ".", "Data", "already", "at", "path", "will", "is", "overwritten", "and", "no", "revision", "history", "is", "saved", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/charmstore/fakeclient.go#L66-L69
4,926
juju/juju
charmstore/fakeclient.go
PutReader
func (d *datastore) PutReader(path string, data io.Reader) error { buffer := []byte{} _, err := data.Read(buffer) if err != nil { return errors.Trace(err) } return d.Put(path, buffer) }
go
func (d *datastore) PutReader(path string, data io.Reader) error { buffer := []byte{} _, err := data.Read(buffer) if err != nil { return errors.Trace(err) } return d.Put(path, buffer) }
[ "func", "(", "d", "*", "datastore", ")", "PutReader", "(", "path", "string", ",", "data", "io", ".", "Reader", ")", "error", "{", "buffer", ":=", "[", "]", "byte", "{", "}", "\n", "_", ",", "err", ":=", "data", ".", "Read", "(", "buffer", ")", ...
// PutReader data from a an io.Reader at path. It will be accessible later via Get. // Data already at path will is overwritten and no // revision history is saved.
[ "PutReader", "data", "from", "a", "an", "io", ".", "Reader", "at", "path", ".", "It", "will", "be", "accessible", "later", "via", "Get", ".", "Data", "already", "at", "path", "will", "is", "overwritten", "and", "no", "revision", "history", "is", "saved",...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/charmstore/fakeclient.go#L74-L81
4,927
juju/juju
charmstore/fakeclient.go
WithChannel
func (c FakeClient) WithChannel(channel params.Channel) *ChannelAwareFakeClient { return &ChannelAwareFakeClient{channel, c} }
go
func (c FakeClient) WithChannel(channel params.Channel) *ChannelAwareFakeClient { return &ChannelAwareFakeClient{channel, c} }
[ "func", "(", "c", "FakeClient", ")", "WithChannel", "(", "channel", "params", ".", "Channel", ")", "*", "ChannelAwareFakeClient", "{", "return", "&", "ChannelAwareFakeClient", "{", "channel", ",", "c", "}", "\n", "}" ]
// WithChannel returns a ChannelAwareFakeClient with its channel // set to channel and its other values originating from this client.
[ "WithChannel", "returns", "a", "ChannelAwareFakeClient", "with", "its", "channel", "set", "to", "channel", "and", "its", "other", "values", "originating", "from", "this", "client", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/charmstore/fakeclient.go#L117-L119
4,928
juju/juju
charmstore/fakeclient.go
Get
func (c ChannelAwareFakeClient) Get(path string, value interface{}) error { return c.charmstore.Get(path, value) }
go
func (c ChannelAwareFakeClient) Get(path string, value interface{}) error { return c.charmstore.Get(path, value) }
[ "func", "(", "c", "ChannelAwareFakeClient", ")", "Get", "(", "path", "string", ",", "value", "interface", "{", "}", ")", "error", "{", "return", "c", ".", "charmstore", ".", "Get", "(", "path", ",", "value", ")", "\n", "}" ]
// Get retrieves data from path. If nothing has been Put to // path, an error satisfying errors.IsNotFound is returned.
[ "Get", "retrieves", "data", "from", "path", ".", "If", "nothing", "has", "been", "Put", "to", "path", "an", "error", "satisfying", "errors", ".", "IsNotFound", "is", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/charmstore/fakeclient.go#L217-L219
4,929
juju/juju
charmstore/fakeclient.go
AddCharm
func (r Repository) AddCharm(id *charm.URL, channel params.Channel, force bool) error { withRevision := r.addRevision(id) alreadyAdded := r.added[string(channel)] for _, charm := range alreadyAdded { if *withRevision == charm { return nil // TODO(tsm) check expected behaviour // // if force { // return nil // } else { // return errors.NewAlreadyExists(errors.NewErr("%v already added in channel %v", id, channel)) // } } } r.added[string(channel)] = append(alreadyAdded, *withRevision) return nil }
go
func (r Repository) AddCharm(id *charm.URL, channel params.Channel, force bool) error { withRevision := r.addRevision(id) alreadyAdded := r.added[string(channel)] for _, charm := range alreadyAdded { if *withRevision == charm { return nil // TODO(tsm) check expected behaviour // // if force { // return nil // } else { // return errors.NewAlreadyExists(errors.NewErr("%v already added in channel %v", id, channel)) // } } } r.added[string(channel)] = append(alreadyAdded, *withRevision) return nil }
[ "func", "(", "r", "Repository", ")", "AddCharm", "(", "id", "*", "charm", ".", "URL", ",", "channel", "params", ".", "Channel", ",", "force", "bool", ")", "error", "{", "withRevision", ":=", "r", ".", "addRevision", "(", "id", ")", "\n", "alreadyAdded"...
// AddCharm registers a charm's availability on a particular channel, // but does not upload its contents. This is part of a two stage process // for storing charms in the repository. // // In this implementation, the force parameter is ignored.
[ "AddCharm", "registers", "a", "charm", "s", "availability", "on", "a", "particular", "channel", "but", "does", "not", "upload", "its", "contents", ".", "This", "is", "part", "of", "a", "two", "stage", "process", "for", "storing", "charms", "in", "the", "re...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/charmstore/fakeclient.go#L360-L378
4,930
juju/juju
charmstore/fakeclient.go
AddCharmWithAuthorization
func (r Repository) AddCharmWithAuthorization(id *charm.URL, channel params.Channel, macaroon *macaroon.Macaroon, force bool) error { return r.AddCharm(id, channel, force) }
go
func (r Repository) AddCharmWithAuthorization(id *charm.URL, channel params.Channel, macaroon *macaroon.Macaroon, force bool) error { return r.AddCharm(id, channel, force) }
[ "func", "(", "r", "Repository", ")", "AddCharmWithAuthorization", "(", "id", "*", "charm", ".", "URL", ",", "channel", "params", ".", "Channel", ",", "macaroon", "*", "macaroon", ".", "Macaroon", ",", "force", "bool", ")", "error", "{", "return", "r", "....
// AddCharmWithAuthorization is equivalent to AddCharm. // The macaroon parameter is ignored.
[ "AddCharmWithAuthorization", "is", "equivalent", "to", "AddCharm", ".", "The", "macaroon", "parameter", "is", "ignored", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/charmstore/fakeclient.go#L382-L384
4,931
juju/juju
charmstore/fakeclient.go
AddLocalCharm
func (r Repository) AddLocalCharm(id *charm.URL, details charm.Charm, force bool) (*charm.URL, error) { return id, r.AddCharm(id, params.NoChannel, force) }
go
func (r Repository) AddLocalCharm(id *charm.URL, details charm.Charm, force bool) (*charm.URL, error) { return id, r.AddCharm(id, params.NoChannel, force) }
[ "func", "(", "r", "Repository", ")", "AddLocalCharm", "(", "id", "*", "charm", ".", "URL", ",", "details", "charm", ".", "Charm", ",", "force", "bool", ")", "(", "*", "charm", ".", "URL", ",", "error", ")", "{", "return", "id", ",", "r", ".", "Ad...
// AddLocalCharm allows you to register a charm that is not associated with a particular release channel. // Its purpose is to facilitate registering charms that have been built locally.
[ "AddLocalCharm", "allows", "you", "to", "register", "a", "charm", "that", "is", "not", "associated", "with", "a", "particular", "release", "channel", ".", "Its", "purpose", "is", "to", "facilitate", "registering", "charms", "that", "have", "been", "built", "lo...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/charmstore/fakeclient.go#L388-L390
4,932
juju/juju
charmstore/fakeclient.go
CharmInfo
func (r Repository) CharmInfo(charmURL string) (*charms.CharmInfo, error) { charmId, err := charm.ParseURL(charmURL) if err != nil { return nil, errors.Trace(err) } charmDetails, err := r.Get(charmId) if err != nil { return nil, errors.Trace(err) } info := charms.CharmInfo{ Revision: charmDetails.Revision(), URL: charmId.String(), Config: charmDetails.Config(), Meta: charmDetails.Meta(), Actions: charmDetails.Actions(), Metrics: charmDetails.Metrics(), } return &info, nil }
go
func (r Repository) CharmInfo(charmURL string) (*charms.CharmInfo, error) { charmId, err := charm.ParseURL(charmURL) if err != nil { return nil, errors.Trace(err) } charmDetails, err := r.Get(charmId) if err != nil { return nil, errors.Trace(err) } info := charms.CharmInfo{ Revision: charmDetails.Revision(), URL: charmId.String(), Config: charmDetails.Config(), Meta: charmDetails.Meta(), Actions: charmDetails.Actions(), Metrics: charmDetails.Metrics(), } return &info, nil }
[ "func", "(", "r", "Repository", ")", "CharmInfo", "(", "charmURL", "string", ")", "(", "*", "charms", ".", "CharmInfo", ",", "error", ")", "{", "charmId", ",", "err", ":=", "charm", ".", "ParseURL", "(", "charmURL", ")", "\n", "if", "err", "!=", "nil...
// CharmInfo returns information about charms that are currently in the charm store.
[ "CharmInfo", "returns", "information", "about", "charms", "that", "are", "currently", "in", "the", "charm", "store", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/charmstore/fakeclient.go#L399-L418
4,933
juju/juju
charmstore/fakeclient.go
Resolve
func (r Repository) Resolve(ref *charm.URL) (canonRef *charm.URL, supportedSeries []string, err error) { return r.addRevision(ref), []string{"trusty", "wily", "quantal"}, nil }
go
func (r Repository) Resolve(ref *charm.URL) (canonRef *charm.URL, supportedSeries []string, err error) { return r.addRevision(ref), []string{"trusty", "wily", "quantal"}, nil }
[ "func", "(", "r", "Repository", ")", "Resolve", "(", "ref", "*", "charm", ".", "URL", ")", "(", "canonRef", "*", "charm", ".", "URL", ",", "supportedSeries", "[", "]", "string", ",", "err", "error", ")", "{", "return", "r", ".", "addRevision", "(", ...
// Resolve disambiguates a charm to a specific revision. // // Part of the charmrepo.Interface
[ "Resolve", "disambiguates", "a", "charm", "to", "a", "specific", "revision", ".", "Part", "of", "the", "charmrepo", ".", "Interface" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/charmstore/fakeclient.go#L423-L425
4,934
juju/juju
charmstore/fakeclient.go
Get
func (r Repository) Get(id *charm.URL) (charm.Charm, error) { withRevision := r.addRevision(id) charmData := r.charms[r.channel][*withRevision] if charmData == nil { return charmData, errors.NotFoundf("cannot retrieve \"%v\": charm", id.String()) } return charmData, nil }
go
func (r Repository) Get(id *charm.URL) (charm.Charm, error) { withRevision := r.addRevision(id) charmData := r.charms[r.channel][*withRevision] if charmData == nil { return charmData, errors.NotFoundf("cannot retrieve \"%v\": charm", id.String()) } return charmData, nil }
[ "func", "(", "r", "Repository", ")", "Get", "(", "id", "*", "charm", ".", "URL", ")", "(", "charm", ".", "Charm", ",", "error", ")", "{", "withRevision", ":=", "r", ".", "addRevision", "(", "id", ")", "\n", "charmData", ":=", "r", ".", "charms", ...
// Get retrieves a charm from the repository. // // Part of the charmrepo.Interface
[ "Get", "retrieves", "a", "charm", "from", "the", "repository", ".", "Part", "of", "the", "charmrepo", ".", "Interface" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/charmstore/fakeclient.go#L438-L445
4,935
juju/juju
charmstore/fakeclient.go
GetBundle
func (r Repository) GetBundle(id *charm.URL) (charm.Bundle, error) { bundleData := r.bundles[r.channel][*id] if bundleData == nil { return nil, errors.NotFoundf(id.String()) } return bundleData, nil }
go
func (r Repository) GetBundle(id *charm.URL) (charm.Bundle, error) { bundleData := r.bundles[r.channel][*id] if bundleData == nil { return nil, errors.NotFoundf(id.String()) } return bundleData, nil }
[ "func", "(", "r", "Repository", ")", "GetBundle", "(", "id", "*", "charm", ".", "URL", ")", "(", "charm", ".", "Bundle", ",", "error", ")", "{", "bundleData", ":=", "r", ".", "bundles", "[", "r", ".", "channel", "]", "[", "*", "id", "]", "\n", ...
// GetBundle retrieves a bundle from the repository. // // Part of the charmrepo.Interface
[ "GetBundle", "retrieves", "a", "bundle", "from", "the", "repository", ".", "Part", "of", "the", "charmrepo", ".", "Interface" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/charmstore/fakeclient.go#L450-L456
4,936
juju/juju
charmstore/fakeclient.go
Publish
func (r Repository) Publish(id *charm.URL, channels []params.Channel, resources map[string]int) error { for _, channel := range channels { published := r.published[channel] published.Add(id.String()) r.published[channel] = published } return nil }
go
func (r Repository) Publish(id *charm.URL, channels []params.Channel, resources map[string]int) error { for _, channel := range channels { published := r.published[channel] published.Add(id.String()) r.published[channel] = published } return nil }
[ "func", "(", "r", "Repository", ")", "Publish", "(", "id", "*", "charm", ".", "URL", ",", "channels", "[", "]", "params", ".", "Channel", ",", "resources", "map", "[", "string", "]", "int", ")", "error", "{", "for", "_", ",", "channel", ":=", "rang...
// Publish marks a charm or bundle as published within channels. // // In this implementation, the resources parameter is ignored.
[ "Publish", "marks", "a", "charm", "or", "bundle", "as", "published", "within", "channels", ".", "In", "this", "implementation", "the", "resources", "parameter", "is", "ignored", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/charmstore/fakeclient.go#L571-L578
4,937
juju/juju
charmstore/fakeclient.go
signature
func signature(r io.Reader) (hash []byte, err error) { h := sha512.New384() _, err = io.Copy(h, r) if err != nil { return nil, errors.Trace(err) } hash = []byte(fmt.Sprintf("%x", h.Sum(nil))) return hash, nil }
go
func signature(r io.Reader) (hash []byte, err error) { h := sha512.New384() _, err = io.Copy(h, r) if err != nil { return nil, errors.Trace(err) } hash = []byte(fmt.Sprintf("%x", h.Sum(nil))) return hash, nil }
[ "func", "signature", "(", "r", "io", ".", "Reader", ")", "(", "hash", "[", "]", "byte", ",", "err", "error", ")", "{", "h", ":=", "sha512", ".", "New384", "(", ")", "\n", "_", ",", "err", "=", "io", ".", "Copy", "(", "h", ",", "r", ")", "\n...
// signature creates a SHA384 digest from r
[ "signature", "creates", "a", "SHA384", "digest", "from", "r" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/charmstore/fakeclient.go#L581-L589
4,938
juju/juju
state/binarystorage/binarystorage.go
New
func New( modelUUID string, managedStorage blobstore.ManagedStorage, metadataCollection mongo.Collection, runner jujutxn.Runner, ) Storage { return &binaryStorage{ modelUUID: modelUUID, managedStorage: managedStorage, metadataCollection: metadataCollection, txnRunner: runner, } }
go
func New( modelUUID string, managedStorage blobstore.ManagedStorage, metadataCollection mongo.Collection, runner jujutxn.Runner, ) Storage { return &binaryStorage{ modelUUID: modelUUID, managedStorage: managedStorage, metadataCollection: metadataCollection, txnRunner: runner, } }
[ "func", "New", "(", "modelUUID", "string", ",", "managedStorage", "blobstore", ".", "ManagedStorage", ",", "metadataCollection", "mongo", ".", "Collection", ",", "runner", "jujutxn", ".", "Runner", ",", ")", "Storage", "{", "return", "&", "binaryStorage", "{", ...
// New constructs a new Storage that stores binary files in the provided // ManagedStorage, and metadata in the provided collection using the provided // transaction runner.
[ "New", "constructs", "a", "new", "Storage", "that", "stores", "binary", "files", "in", "the", "provided", "ManagedStorage", "and", "metadata", "in", "the", "provided", "collection", "using", "the", "provided", "transaction", "runner", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/binarystorage/binarystorage.go#L35-L47
4,939
juju/juju
state/binarystorage/binarystorage.go
Add
func (s *binaryStorage) Add(r io.Reader, metadata Metadata) (resultErr error) { // Add the binary file to storage. path := fmt.Sprintf("tools/%s-%s", metadata.Version, metadata.SHA256) if err := s.managedStorage.PutForBucket(s.modelUUID, path, r, metadata.Size); err != nil { return errors.Annotate(err, "cannot store binary file") } defer func() { if resultErr == nil { return } err := s.managedStorage.RemoveForBucket(s.modelUUID, path) if err != nil { logger.Errorf("failed to remove binary blob: %v", err) } }() newDoc := metadataDoc{ Id: metadata.Version, Version: metadata.Version, Size: metadata.Size, SHA256: metadata.SHA256, Path: path, } // Add or replace metadata. If replacing, record the existing path so we // can remove it later. var oldPath string buildTxn := func(attempt int) ([]txn.Op, error) { op := txn.Op{ C: s.metadataCollection.Name(), Id: newDoc.Id, } // On the first attempt we assume we're adding new binary files. // Subsequent attempts to add files will fetch the existing // doc, record the old path, and attempt to update the // size, path and hash fields. if attempt == 0 { op.Assert = txn.DocMissing op.Insert = &newDoc } else { oldDoc, err := s.findMetadata(metadata.Version) if err != nil { return nil, err } oldPath = oldDoc.Path op.Assert = bson.D{{"path", oldPath}} if oldPath != path { op.Update = bson.D{{ "$set", bson.D{ {"size", metadata.Size}, {"sha256", metadata.SHA256}, {"path", path}, }, }} } } return []txn.Op{op}, nil } err := s.txnRunner.Run(buildTxn) if err != nil { return errors.Annotate(err, "cannot store binary metadata") } if oldPath != "" && oldPath != path { // Attempt to remove the old path. Failure is non-fatal. err := s.managedStorage.RemoveForBucket(s.modelUUID, oldPath) if err != nil { logger.Errorf("failed to remove old binary blob: %v", err) } else { logger.Debugf("removed old binary blob") } } return nil }
go
func (s *binaryStorage) Add(r io.Reader, metadata Metadata) (resultErr error) { // Add the binary file to storage. path := fmt.Sprintf("tools/%s-%s", metadata.Version, metadata.SHA256) if err := s.managedStorage.PutForBucket(s.modelUUID, path, r, metadata.Size); err != nil { return errors.Annotate(err, "cannot store binary file") } defer func() { if resultErr == nil { return } err := s.managedStorage.RemoveForBucket(s.modelUUID, path) if err != nil { logger.Errorf("failed to remove binary blob: %v", err) } }() newDoc := metadataDoc{ Id: metadata.Version, Version: metadata.Version, Size: metadata.Size, SHA256: metadata.SHA256, Path: path, } // Add or replace metadata. If replacing, record the existing path so we // can remove it later. var oldPath string buildTxn := func(attempt int) ([]txn.Op, error) { op := txn.Op{ C: s.metadataCollection.Name(), Id: newDoc.Id, } // On the first attempt we assume we're adding new binary files. // Subsequent attempts to add files will fetch the existing // doc, record the old path, and attempt to update the // size, path and hash fields. if attempt == 0 { op.Assert = txn.DocMissing op.Insert = &newDoc } else { oldDoc, err := s.findMetadata(metadata.Version) if err != nil { return nil, err } oldPath = oldDoc.Path op.Assert = bson.D{{"path", oldPath}} if oldPath != path { op.Update = bson.D{{ "$set", bson.D{ {"size", metadata.Size}, {"sha256", metadata.SHA256}, {"path", path}, }, }} } } return []txn.Op{op}, nil } err := s.txnRunner.Run(buildTxn) if err != nil { return errors.Annotate(err, "cannot store binary metadata") } if oldPath != "" && oldPath != path { // Attempt to remove the old path. Failure is non-fatal. err := s.managedStorage.RemoveForBucket(s.modelUUID, oldPath) if err != nil { logger.Errorf("failed to remove old binary blob: %v", err) } else { logger.Debugf("removed old binary blob") } } return nil }
[ "func", "(", "s", "*", "binaryStorage", ")", "Add", "(", "r", "io", ".", "Reader", ",", "metadata", "Metadata", ")", "(", "resultErr", "error", ")", "{", "// Add the binary file to storage.", "path", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "me...
// Add implements Storage.Add.
[ "Add", "implements", "Storage", ".", "Add", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/binarystorage/binarystorage.go#L50-L124
4,940
juju/juju
provider/joyent/instance_firewall.go
createFirewallRuleVm
func createFirewallRuleVm(envName string, machineId string, portRange network.IngressRule) string { ports := []string{} for p := portRange.FromPort; p <= portRange.ToPort; p++ { ports = append(ports, fmt.Sprintf("PORT %d", p)) } var portList string if len(ports) > 1 { portList = fmt.Sprintf("( %s )", strings.Join(ports, " AND ")) } else if len(ports) == 1 { portList = ports[0] } return fmt.Sprintf(firewallRuleVm, envName, machineId, strings.ToLower(portRange.Protocol), portList) }
go
func createFirewallRuleVm(envName string, machineId string, portRange network.IngressRule) string { ports := []string{} for p := portRange.FromPort; p <= portRange.ToPort; p++ { ports = append(ports, fmt.Sprintf("PORT %d", p)) } var portList string if len(ports) > 1 { portList = fmt.Sprintf("( %s )", strings.Join(ports, " AND ")) } else if len(ports) == 1 { portList = ports[0] } return fmt.Sprintf(firewallRuleVm, envName, machineId, strings.ToLower(portRange.Protocol), portList) }
[ "func", "createFirewallRuleVm", "(", "envName", "string", ",", "machineId", "string", ",", "portRange", "network", ".", "IngressRule", ")", "string", "{", "ports", ":=", "[", "]", "string", "{", "}", "\n", "for", "p", ":=", "portRange", ".", "FromPort", ";...
// Helper method to create a firewall rule string for the given machine Id and port
[ "Helper", "method", "to", "create", "a", "firewall", "rule", "string", "for", "the", "given", "machine", "Id", "and", "port" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/joyent/instance_firewall.go#L22-L34
4,941
juju/juju
apiserver/bakeryutil/service.go
PublicKeyForLocation
func (b BakeryServicePublicKeyLocator) PublicKeyForLocation(string) (*bakery.PublicKey, error) { return b.Service.PublicKey(), nil }
go
func (b BakeryServicePublicKeyLocator) PublicKeyForLocation(string) (*bakery.PublicKey, error) { return b.Service.PublicKey(), nil }
[ "func", "(", "b", "BakeryServicePublicKeyLocator", ")", "PublicKeyForLocation", "(", "string", ")", "(", "*", "bakery", ".", "PublicKey", ",", "error", ")", "{", "return", "b", ".", "Service", ".", "PublicKey", "(", ")", ",", "nil", "\n", "}" ]
// PublicKeyForLocation implements bakery.PublicKeyLocator.
[ "PublicKeyForLocation", "implements", "bakery", ".", "PublicKeyLocator", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/bakeryutil/service.go#L25-L27
4,942
juju/juju
apiserver/bakeryutil/service.go
NewBakeryService
func NewBakeryService( st *state.State, store bakerystorage.ExpirableStorage, locator bakery.PublicKeyLocator, ) (*bakery.Service, *bakery.KeyPair, error) { key, err := bakery.GenerateKey() if err != nil { return nil, nil, errors.Annotate(err, "generating key for bakery service") } service, err := bakery.NewService(bakery.NewServiceParams{ Location: "juju model " + st.ModelUUID(), Store: store, Key: key, Locator: locator, }) if err != nil { return nil, nil, errors.Trace(err) } return service, key, nil }
go
func NewBakeryService( st *state.State, store bakerystorage.ExpirableStorage, locator bakery.PublicKeyLocator, ) (*bakery.Service, *bakery.KeyPair, error) { key, err := bakery.GenerateKey() if err != nil { return nil, nil, errors.Annotate(err, "generating key for bakery service") } service, err := bakery.NewService(bakery.NewServiceParams{ Location: "juju model " + st.ModelUUID(), Store: store, Key: key, Locator: locator, }) if err != nil { return nil, nil, errors.Trace(err) } return service, key, nil }
[ "func", "NewBakeryService", "(", "st", "*", "state", ".", "State", ",", "store", "bakerystorage", ".", "ExpirableStorage", ",", "locator", "bakery", ".", "PublicKeyLocator", ",", ")", "(", "*", "bakery", ".", "Service", ",", "*", "bakery", ".", "KeyPair", ...
// NewBakeryService returns a new bakery.Service and bakery.KeyPair. // The bakery service is identifeid by the model corresponding to the // State.
[ "NewBakeryService", "returns", "a", "new", "bakery", ".", "Service", "and", "bakery", ".", "KeyPair", ".", "The", "bakery", "service", "is", "identifeid", "by", "the", "model", "corresponding", "to", "the", "State", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/bakeryutil/service.go#L32-L51
4,943
juju/juju
apiserver/bakeryutil/service.go
ExpireStorageAfter
func (s *ExpirableStorageBakeryService) ExpireStorageAfter(t time.Duration) (authentication.ExpirableStorageBakeryService, error) { store := s.Store.ExpireAfter(t) service, err := bakery.NewService(bakery.NewServiceParams{ Location: s.Location(), Store: store, Key: s.Key, Locator: s.Locator, }) if err != nil { return nil, errors.Trace(err) } return &ExpirableStorageBakeryService{service, s.Key, store, s.Locator}, nil }
go
func (s *ExpirableStorageBakeryService) ExpireStorageAfter(t time.Duration) (authentication.ExpirableStorageBakeryService, error) { store := s.Store.ExpireAfter(t) service, err := bakery.NewService(bakery.NewServiceParams{ Location: s.Location(), Store: store, Key: s.Key, Locator: s.Locator, }) if err != nil { return nil, errors.Trace(err) } return &ExpirableStorageBakeryService{service, s.Key, store, s.Locator}, nil }
[ "func", "(", "s", "*", "ExpirableStorageBakeryService", ")", "ExpireStorageAfter", "(", "t", "time", ".", "Duration", ")", "(", "authentication", ".", "ExpirableStorageBakeryService", ",", "error", ")", "{", "store", ":=", "s", ".", "Store", ".", "ExpireAfter", ...
// ExpireStorageAfter implements authentication.ExpirableStorageBakeryService.
[ "ExpireStorageAfter", "implements", "authentication", ".", "ExpirableStorageBakeryService", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/bakeryutil/service.go#L63-L75
4,944
juju/juju
worker/provisioner/container_initialisation.go
NewContainerSetupHandler
func NewContainerSetupHandler(params ContainerSetupParams) watcher.StringsHandler { return &ContainerSetup{ runner: params.Runner, machine: params.Machine, supportedContainers: params.SupportedContainers, provisioner: params.Provisioner, config: params.Config, workerName: params.WorkerName, machineLock: params.MachineLock, credentialAPI: params.CredentialAPI, getNetConfig: common.GetObservedNetworkConfig, } }
go
func NewContainerSetupHandler(params ContainerSetupParams) watcher.StringsHandler { return &ContainerSetup{ runner: params.Runner, machine: params.Machine, supportedContainers: params.SupportedContainers, provisioner: params.Provisioner, config: params.Config, workerName: params.WorkerName, machineLock: params.MachineLock, credentialAPI: params.CredentialAPI, getNetConfig: common.GetObservedNetworkConfig, } }
[ "func", "NewContainerSetupHandler", "(", "params", "ContainerSetupParams", ")", "watcher", ".", "StringsHandler", "{", "return", "&", "ContainerSetup", "{", "runner", ":", "params", ".", "Runner", ",", "machine", ":", "params", ".", "Machine", ",", "supportedConta...
// NewContainerSetupHandler returns a StringsWatchHandler which is notified // when containers are created on the given machine.
[ "NewContainerSetupHandler", "returns", "a", "StringsWatchHandler", "which", "is", "notified", "when", "containers", "are", "created", "on", "the", "given", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/container_initialisation.go#L66-L78
4,945
juju/juju
worker/provisioner/container_initialisation.go
SetUp
func (cs *ContainerSetup) SetUp() (watcher watcher.StringsWatcher, err error) { // Set up the semaphores for each container type. cs.setupDone = make(map[instance.ContainerType]*int32, len(instance.ContainerTypes)) for _, containerType := range instance.ContainerTypes { zero := int32(0) cs.setupDone[containerType] = &zero } // Listen to all container lifecycle events on our machine. if watcher, err = cs.machine.WatchAllContainers(); err != nil { return nil, err } return watcher, nil }
go
func (cs *ContainerSetup) SetUp() (watcher watcher.StringsWatcher, err error) { // Set up the semaphores for each container type. cs.setupDone = make(map[instance.ContainerType]*int32, len(instance.ContainerTypes)) for _, containerType := range instance.ContainerTypes { zero := int32(0) cs.setupDone[containerType] = &zero } // Listen to all container lifecycle events on our machine. if watcher, err = cs.machine.WatchAllContainers(); err != nil { return nil, err } return watcher, nil }
[ "func", "(", "cs", "*", "ContainerSetup", ")", "SetUp", "(", ")", "(", "watcher", "watcher", ".", "StringsWatcher", ",", "err", "error", ")", "{", "// Set up the semaphores for each container type.", "cs", ".", "setupDone", "=", "make", "(", "map", "[", "insta...
// SetUp is defined on the StringsWatchHandler interface.
[ "SetUp", "is", "defined", "on", "the", "StringsWatchHandler", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/container_initialisation.go#L81-L93
4,946
juju/juju
worker/provisioner/container_initialisation.go
Handle
func (cs *ContainerSetup) Handle(abort <-chan struct{}, containerIds []string) (resultError error) { // Consume the initial watcher event. if len(containerIds) == 0 { return nil } logger.Infof("initial container setup with ids: %v", containerIds) for _, id := range containerIds { containerType := state.ContainerTypeFromId(id) // If this container type has been dealt with, do nothing. if atomic.LoadInt32(cs.setupDone[containerType]) != 0 { continue } if err := cs.initialiseAndStartProvisioner(abort, containerType); err != nil { logger.Errorf("starting container provisioner for %v: %v", containerType, err) // Just because dealing with one type of container fails, we won't // exit the entire function because we still want to try and start // other container types. So we take note of and return the first // such error. if resultError == nil { resultError = err } } } return errors.Trace(resultError) }
go
func (cs *ContainerSetup) Handle(abort <-chan struct{}, containerIds []string) (resultError error) { // Consume the initial watcher event. if len(containerIds) == 0 { return nil } logger.Infof("initial container setup with ids: %v", containerIds) for _, id := range containerIds { containerType := state.ContainerTypeFromId(id) // If this container type has been dealt with, do nothing. if atomic.LoadInt32(cs.setupDone[containerType]) != 0 { continue } if err := cs.initialiseAndStartProvisioner(abort, containerType); err != nil { logger.Errorf("starting container provisioner for %v: %v", containerType, err) // Just because dealing with one type of container fails, we won't // exit the entire function because we still want to try and start // other container types. So we take note of and return the first // such error. if resultError == nil { resultError = err } } } return errors.Trace(resultError) }
[ "func", "(", "cs", "*", "ContainerSetup", ")", "Handle", "(", "abort", "<-", "chan", "struct", "{", "}", ",", "containerIds", "[", "]", "string", ")", "(", "resultError", "error", ")", "{", "// Consume the initial watcher event.", "if", "len", "(", "containe...
// Handle is called whenever containers change on the machine being watched. // Machines start out with no containers so the first time Handle is called, // it will be because a container has been added.
[ "Handle", "is", "called", "whenever", "containers", "change", "on", "the", "machine", "being", "watched", ".", "Machines", "start", "out", "with", "no", "containers", "so", "the", "first", "time", "Handle", "is", "called", "it", "will", "be", "because", "a",...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/container_initialisation.go#L98-L123
4,947
juju/juju
worker/provisioner/container_initialisation.go
initContainerDependencies
func (cs *ContainerSetup) initContainerDependencies(abort <-chan struct{}, containerType instance.ContainerType) error { initialiser := getContainerInitialiser(containerType) releaser, err := cs.acquireLock(fmt.Sprintf("%s container initialisation", containerType), abort) if err != nil { return errors.Annotate(err, "failed to acquire initialization lock") } defer releaser() if err := initialiser.Initialise(); err != nil { return errors.Trace(err) } // At this point, Initialiser likely has changed host network information, // so re-probe to have an accurate view. observedConfig, err := cs.observeNetwork() if err != nil { return errors.Annotate(err, "cannot discover observed network config") } if len(observedConfig) > 0 { machineTag := cs.machine.MachineTag() logger.Tracef("updating observed network config for %q %s containers to %#v", machineTag, containerType, observedConfig) if err := cs.provisioner.SetHostMachineNetworkConfig(machineTag, observedConfig); err != nil { return errors.Trace(err) } } return nil }
go
func (cs *ContainerSetup) initContainerDependencies(abort <-chan struct{}, containerType instance.ContainerType) error { initialiser := getContainerInitialiser(containerType) releaser, err := cs.acquireLock(fmt.Sprintf("%s container initialisation", containerType), abort) if err != nil { return errors.Annotate(err, "failed to acquire initialization lock") } defer releaser() if err := initialiser.Initialise(); err != nil { return errors.Trace(err) } // At this point, Initialiser likely has changed host network information, // so re-probe to have an accurate view. observedConfig, err := cs.observeNetwork() if err != nil { return errors.Annotate(err, "cannot discover observed network config") } if len(observedConfig) > 0 { machineTag := cs.machine.MachineTag() logger.Tracef("updating observed network config for %q %s containers to %#v", machineTag, containerType, observedConfig) if err := cs.provisioner.SetHostMachineNetworkConfig(machineTag, observedConfig); err != nil { return errors.Trace(err) } } return nil }
[ "func", "(", "cs", "*", "ContainerSetup", ")", "initContainerDependencies", "(", "abort", "<-", "chan", "struct", "{", "}", ",", "containerType", "instance", ".", "ContainerType", ")", "error", "{", "initialiser", ":=", "getContainerInitialiser", "(", "containerTy...
// initContainerDependencies ensures that the host machine is set-up to manage // containers of the input type.
[ "initContainerDependencies", "ensures", "that", "the", "host", "machine", "is", "set", "-", "up", "to", "manage", "containers", "of", "the", "input", "type", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/container_initialisation.go#L197-L226
4,948
juju/juju
worker/provisioner/container_initialisation.go
startProvisionerWorker
func startProvisionerWorker( runner *worker.Runner, containerType instance.ContainerType, provisioner *apiprovisioner.State, config agent.Config, broker environs.InstanceBroker, toolsFinder ToolsFinder, distributionGroupFinder DistributionGroupFinder, credentialAPI workercommon.CredentialAPI, ) error { workerName := fmt.Sprintf("%s-provisioner", containerType) // The provisioner task is created after a container record has // already been added to the machine. It will see that the // container does not have an instance yet and create one. return runner.StartWorker(workerName, func() (worker.Worker, error) { w, err := NewContainerProvisioner(containerType, provisioner, config, broker, toolsFinder, distributionGroupFinder, credentialAPI, ) if err != nil { return nil, errors.Trace(err) } return w, nil }) }
go
func startProvisionerWorker( runner *worker.Runner, containerType instance.ContainerType, provisioner *apiprovisioner.State, config agent.Config, broker environs.InstanceBroker, toolsFinder ToolsFinder, distributionGroupFinder DistributionGroupFinder, credentialAPI workercommon.CredentialAPI, ) error { workerName := fmt.Sprintf("%s-provisioner", containerType) // The provisioner task is created after a container record has // already been added to the machine. It will see that the // container does not have an instance yet and create one. return runner.StartWorker(workerName, func() (worker.Worker, error) { w, err := NewContainerProvisioner(containerType, provisioner, config, broker, toolsFinder, distributionGroupFinder, credentialAPI, ) if err != nil { return nil, errors.Trace(err) } return w, nil }) }
[ "func", "startProvisionerWorker", "(", "runner", "*", "worker", ".", "Runner", ",", "containerType", "instance", ".", "ContainerType", ",", "provisioner", "*", "apiprovisioner", ".", "State", ",", "config", "agent", ".", "Config", ",", "broker", "environs", ".",...
// startProvisionerWorker kicks off a provisioner task responsible for creating // containers of the specified type on the machine.
[ "startProvisionerWorker", "kicks", "off", "a", "provisioner", "task", "responsible", "for", "creating", "containers", "of", "the", "specified", "type", "on", "the", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/provisioner/container_initialisation.go#L273-L302
4,949
juju/juju
worker/modelworkermanager/modelworkermanager.go
Validate
func (config Config) Validate() error { if config.ModelWatcher == nil { return errors.NotValidf("nil ModelWatcher") } if config.ModelGetter == nil { return errors.NotValidf("nil ModelGetter") } if config.NewModelWorker == nil { return errors.NotValidf("nil NewModelWorker") } if config.ErrorDelay <= 0 { return errors.NotValidf("non-positive ErrorDelay") } return nil }
go
func (config Config) Validate() error { if config.ModelWatcher == nil { return errors.NotValidf("nil ModelWatcher") } if config.ModelGetter == nil { return errors.NotValidf("nil ModelGetter") } if config.NewModelWorker == nil { return errors.NotValidf("nil NewModelWorker") } if config.ErrorDelay <= 0 { return errors.NotValidf("non-positive ErrorDelay") } return nil }
[ "func", "(", "config", "Config", ")", "Validate", "(", ")", "error", "{", "if", "config", ".", "ModelWatcher", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "config", ".", "ModelGetter", "==", "n...
// Validate returns an error if config cannot be expected to drive // a functional model worker manager.
[ "Validate", "returns", "an", "error", "if", "config", "cannot", "be", "expected", "to", "drive", "a", "functional", "model", "worker", "manager", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/modelworkermanager/modelworkermanager.go#L54-L68
4,950
juju/juju
api/common/logs.go
StreamDebugLog
func StreamDebugLog(source base.StreamConnector, args DebugLogParams) (<-chan LogMessage, error) { // TODO(babbageclunk): this isn't cancellable - if the caller stops // reading from the channel (because it has an error, for example), // the goroutine will be leaked. This is OK when used from the command // line, but is a problem if it happens in jujud. Change it to accept // a stop channel and use a read deadline so that the client can stop // it. https://pad.lv/1644084 // Prepare URL query attributes. attrs := args.URLQuery() connection, err := source.ConnectStream("/log", attrs) if err != nil { return nil, errors.Trace(err) } messages := make(chan LogMessage) go func() { defer close(messages) for { var msg params.LogMessage err := connection.ReadJSON(&msg) if err != nil { return } messages <- LogMessage{ Entity: msg.Entity, Timestamp: msg.Timestamp, Severity: msg.Severity, Module: msg.Module, Location: msg.Location, Message: msg.Message, } } }() return messages, nil }
go
func StreamDebugLog(source base.StreamConnector, args DebugLogParams) (<-chan LogMessage, error) { // TODO(babbageclunk): this isn't cancellable - if the caller stops // reading from the channel (because it has an error, for example), // the goroutine will be leaked. This is OK when used from the command // line, but is a problem if it happens in jujud. Change it to accept // a stop channel and use a read deadline so that the client can stop // it. https://pad.lv/1644084 // Prepare URL query attributes. attrs := args.URLQuery() connection, err := source.ConnectStream("/log", attrs) if err != nil { return nil, errors.Trace(err) } messages := make(chan LogMessage) go func() { defer close(messages) for { var msg params.LogMessage err := connection.ReadJSON(&msg) if err != nil { return } messages <- LogMessage{ Entity: msg.Entity, Timestamp: msg.Timestamp, Severity: msg.Severity, Module: msg.Module, Location: msg.Location, Message: msg.Message, } } }() return messages, nil }
[ "func", "StreamDebugLog", "(", "source", "base", ".", "StreamConnector", ",", "args", "DebugLogParams", ")", "(", "<-", "chan", "LogMessage", ",", "error", ")", "{", "// TODO(babbageclunk): this isn't cancellable - if the caller stops", "// reading from the channel (because i...
// StreamDebugLog requests the specified debug log records from the // server and returns a channel of the messages that come back.
[ "StreamDebugLog", "requests", "the", "specified", "debug", "log", "records", "from", "the", "server", "and", "returns", "a", "channel", "of", "the", "messages", "that", "come", "back", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/common/logs.go#L98-L136
4,951
juju/juju
worker/uniter/operation/deploy.go
Prepare
func (d *deploy) Prepare(state State) (*State, error) { if err := d.checkAlreadyDone(state); err != nil { return nil, errors.Trace(err) } info, err := d.callbacks.GetArchiveInfo(d.charmURL) if err != nil { return nil, errors.Trace(err) } if err := d.deployer.Stage(info, d.abort); err != nil { return nil, errors.Trace(err) } // note: yes, this *should* be in Prepare, not Execute. Before we can safely // write out local state referencing the charm url (by returning the new // State to the Executor, below), we have to register our interest in that // charm on the controller. If we neglected to do so, the operation could // race with a new application-charm-url change on the controller, and lead to // failures on resume in which we try to obtain archive info for a charm that // has already been removed from the controller. if err := d.callbacks.SetCurrentCharm(d.charmURL); err != nil { return nil, errors.Trace(err) } return d.getState(state, Pending), nil }
go
func (d *deploy) Prepare(state State) (*State, error) { if err := d.checkAlreadyDone(state); err != nil { return nil, errors.Trace(err) } info, err := d.callbacks.GetArchiveInfo(d.charmURL) if err != nil { return nil, errors.Trace(err) } if err := d.deployer.Stage(info, d.abort); err != nil { return nil, errors.Trace(err) } // note: yes, this *should* be in Prepare, not Execute. Before we can safely // write out local state referencing the charm url (by returning the new // State to the Executor, below), we have to register our interest in that // charm on the controller. If we neglected to do so, the operation could // race with a new application-charm-url change on the controller, and lead to // failures on resume in which we try to obtain archive info for a charm that // has already been removed from the controller. if err := d.callbacks.SetCurrentCharm(d.charmURL); err != nil { return nil, errors.Trace(err) } return d.getState(state, Pending), nil }
[ "func", "(", "d", "*", "deploy", ")", "Prepare", "(", "state", "State", ")", "(", "*", "State", ",", "error", ")", "{", "if", "err", ":=", "d", ".", "checkAlreadyDone", "(", "state", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "error...
// Prepare downloads and verifies the charm, and informs the controller // that the unit will be using it. If the supplied state indicates that a // hook was pending, that hook is recorded in the returned state. // Prepare is part of the Operation interface.
[ "Prepare", "downloads", "and", "verifies", "the", "charm", "and", "informs", "the", "controller", "that", "the", "unit", "will", "be", "using", "it", ".", "If", "the", "supplied", "state", "indicates", "that", "a", "hook", "was", "pending", "that", "hook", ...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/operation/deploy.go#L50-L72
4,952
juju/juju
worker/uniter/operation/deploy.go
Execute
func (d *deploy) Execute(state State) (*State, error) { if err := d.deployer.Deploy(); err == charm.ErrConflict { return nil, NewDeployConflictError(d.charmURL) } else if err != nil { return nil, errors.Trace(err) } return d.getState(state, Done), nil }
go
func (d *deploy) Execute(state State) (*State, error) { if err := d.deployer.Deploy(); err == charm.ErrConflict { return nil, NewDeployConflictError(d.charmURL) } else if err != nil { return nil, errors.Trace(err) } return d.getState(state, Done), nil }
[ "func", "(", "d", "*", "deploy", ")", "Execute", "(", "state", "State", ")", "(", "*", "State", ",", "error", ")", "{", "if", "err", ":=", "d", ".", "deployer", ".", "Deploy", "(", ")", ";", "err", "==", "charm", ".", "ErrConflict", "{", "return"...
// Execute installs or upgrades the prepared charm, and preserves any hook // recorded in the supplied state. // Execute is part of the Operation interface.
[ "Execute", "installs", "or", "upgrades", "the", "prepared", "charm", "and", "preserves", "any", "hook", "recorded", "in", "the", "supplied", "state", ".", "Execute", "is", "part", "of", "the", "Operation", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/operation/deploy.go#L77-L84
4,953
juju/juju
worker/uniter/operation/deploy.go
Commit
func (d *deploy) Commit(state State) (*State, error) { change := &stateChange{ Kind: RunHook, } if hookInfo := d.interruptedHook(state); hookInfo != nil { change.Hook = hookInfo change.Step = Pending } else { change.Hook = &hook.Info{Kind: deployHookKinds[d.kind]} change.Step = Queued } return change.apply(state), nil }
go
func (d *deploy) Commit(state State) (*State, error) { change := &stateChange{ Kind: RunHook, } if hookInfo := d.interruptedHook(state); hookInfo != nil { change.Hook = hookInfo change.Step = Pending } else { change.Hook = &hook.Info{Kind: deployHookKinds[d.kind]} change.Step = Queued } return change.apply(state), nil }
[ "func", "(", "d", "*", "deploy", ")", "Commit", "(", "state", "State", ")", "(", "*", "State", ",", "error", ")", "{", "change", ":=", "&", "stateChange", "{", "Kind", ":", "RunHook", ",", "}", "\n", "if", "hookInfo", ":=", "d", ".", "interruptedHo...
// Commit restores state for any interrupted hook, or queues an install or // upgrade-charm hook if no hook was interrupted.
[ "Commit", "restores", "state", "for", "any", "interrupted", "hook", "or", "queues", "an", "install", "or", "upgrade", "-", "charm", "hook", "if", "no", "hook", "was", "interrupted", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/operation/deploy.go#L88-L100
4,954
juju/juju
resource/application.go
Updates
func (sr ApplicationResources) Updates() ([]resource.Resource, error) { storeResources, err := sr.alignStoreResources() if err != nil { return nil, errors.Trace(err) } var updates []resource.Resource for i, res := range sr.Resources { if res.Origin != resource.OriginStore { continue } csRes := storeResources[i] // If the revision is the same then all the other info must be. if res.Revision == csRes.Revision { continue } updates = append(updates, csRes) } return updates, nil }
go
func (sr ApplicationResources) Updates() ([]resource.Resource, error) { storeResources, err := sr.alignStoreResources() if err != nil { return nil, errors.Trace(err) } var updates []resource.Resource for i, res := range sr.Resources { if res.Origin != resource.OriginStore { continue } csRes := storeResources[i] // If the revision is the same then all the other info must be. if res.Revision == csRes.Revision { continue } updates = append(updates, csRes) } return updates, nil }
[ "func", "(", "sr", "ApplicationResources", ")", "Updates", "(", ")", "(", "[", "]", "resource", ".", "Resource", ",", "error", ")", "{", "storeResources", ",", "err", ":=", "sr", ".", "alignStoreResources", "(", ")", "\n", "if", "err", "!=", "nil", "{"...
// Updates returns the list of charm store resources corresponding to // the application's resources that are out of date. Note that there must be // a charm store resource for each of the application resources and // vice-versa. If they are out of sync then an error is returned.
[ "Updates", "returns", "the", "list", "of", "charm", "store", "resources", "corresponding", "to", "the", "application", "s", "resources", "that", "are", "out", "of", "date", ".", "Note", "that", "there", "must", "be", "a", "charm", "store", "resource", "for",...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/application.go#L35-L54
4,955
juju/juju
caas/kubernetes/provider/mocks/apiextensions_mock.go
NewMockApiextensionsV1beta1Interface
func NewMockApiextensionsV1beta1Interface(ctrl *gomock.Controller) *MockApiextensionsV1beta1Interface { mock := &MockApiextensionsV1beta1Interface{ctrl: ctrl} mock.recorder = &MockApiextensionsV1beta1InterfaceMockRecorder{mock} return mock }
go
func NewMockApiextensionsV1beta1Interface(ctrl *gomock.Controller) *MockApiextensionsV1beta1Interface { mock := &MockApiextensionsV1beta1Interface{ctrl: ctrl} mock.recorder = &MockApiextensionsV1beta1InterfaceMockRecorder{mock} return mock }
[ "func", "NewMockApiextensionsV1beta1Interface", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockApiextensionsV1beta1Interface", "{", "mock", ":=", "&", "MockApiextensionsV1beta1Interface", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "...
// NewMockApiextensionsV1beta1Interface creates a new mock instance
[ "NewMockApiextensionsV1beta1Interface", "creates", "a", "new", "mock", "instance" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/mocks/apiextensions_mock.go#L31-L35
4,956
juju/juju
caas/kubernetes/provider/mocks/apiextensions_mock.go
CustomResourceDefinitions
func (m *MockApiextensionsV1beta1Interface) CustomResourceDefinitions() v1beta10.CustomResourceDefinitionInterface { ret := m.ctrl.Call(m, "CustomResourceDefinitions") ret0, _ := ret[0].(v1beta10.CustomResourceDefinitionInterface) return ret0 }
go
func (m *MockApiextensionsV1beta1Interface) CustomResourceDefinitions() v1beta10.CustomResourceDefinitionInterface { ret := m.ctrl.Call(m, "CustomResourceDefinitions") ret0, _ := ret[0].(v1beta10.CustomResourceDefinitionInterface) return ret0 }
[ "func", "(", "m", "*", "MockApiextensionsV1beta1Interface", ")", "CustomResourceDefinitions", "(", ")", "v1beta10", ".", "CustomResourceDefinitionInterface", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ")", "\n", "ret0", ",", ...
// CustomResourceDefinitions mocks base method
[ "CustomResourceDefinitions", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/mocks/apiextensions_mock.go#L43-L47
4,957
juju/juju
caas/kubernetes/provider/mocks/apiextensions_mock.go
CustomResourceDefinitions
func (mr *MockApiextensionsV1beta1InterfaceMockRecorder) CustomResourceDefinitions() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CustomResourceDefinitions", reflect.TypeOf((*MockApiextensionsV1beta1Interface)(nil).CustomResourceDefinitions)) }
go
func (mr *MockApiextensionsV1beta1InterfaceMockRecorder) CustomResourceDefinitions() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CustomResourceDefinitions", reflect.TypeOf((*MockApiextensionsV1beta1Interface)(nil).CustomResourceDefinitions)) }
[ "func", "(", "mr", "*", "MockApiextensionsV1beta1InterfaceMockRecorder", ")", "CustomResourceDefinitions", "(", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", ...
// CustomResourceDefinitions indicates an expected call of CustomResourceDefinitions
[ "CustomResourceDefinitions", "indicates", "an", "expected", "call", "of", "CustomResourceDefinitions" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/mocks/apiextensions_mock.go#L50-L52
4,958
juju/juju
caas/kubernetes/provider/mocks/apiextensions_mock.go
RESTClient
func (m *MockApiextensionsV1beta1Interface) RESTClient() rest.Interface { ret := m.ctrl.Call(m, "RESTClient") ret0, _ := ret[0].(rest.Interface) return ret0 }
go
func (m *MockApiextensionsV1beta1Interface) RESTClient() rest.Interface { ret := m.ctrl.Call(m, "RESTClient") ret0, _ := ret[0].(rest.Interface) return ret0 }
[ "func", "(", "m", "*", "MockApiextensionsV1beta1Interface", ")", "RESTClient", "(", ")", "rest", ".", "Interface", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ...
// RESTClient mocks base method
[ "RESTClient", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/mocks/apiextensions_mock.go#L55-L59
4,959
juju/juju
caas/kubernetes/provider/mocks/apiextensions_mock.go
NewMockCustomResourceDefinitionInterface
func NewMockCustomResourceDefinitionInterface(ctrl *gomock.Controller) *MockCustomResourceDefinitionInterface { mock := &MockCustomResourceDefinitionInterface{ctrl: ctrl} mock.recorder = &MockCustomResourceDefinitionInterfaceMockRecorder{mock} return mock }
go
func NewMockCustomResourceDefinitionInterface(ctrl *gomock.Controller) *MockCustomResourceDefinitionInterface { mock := &MockCustomResourceDefinitionInterface{ctrl: ctrl} mock.recorder = &MockCustomResourceDefinitionInterfaceMockRecorder{mock} return mock }
[ "func", "NewMockCustomResourceDefinitionInterface", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockCustomResourceDefinitionInterface", "{", "mock", ":=", "&", "MockCustomResourceDefinitionInterface", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "re...
// NewMockCustomResourceDefinitionInterface creates a new mock instance
[ "NewMockCustomResourceDefinitionInterface", "creates", "a", "new", "mock", "instance" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/mocks/apiextensions_mock.go#L78-L82
4,960
juju/juju
permission/access.go
Validate
func (a Access) Validate() error { switch a { case NoAccess, AdminAccess, ReadAccess, WriteAccess, LoginAccess, AddModelAccess, SuperuserAccess: return nil } return errors.NotValidf("access level %s", a) }
go
func (a Access) Validate() error { switch a { case NoAccess, AdminAccess, ReadAccess, WriteAccess, LoginAccess, AddModelAccess, SuperuserAccess: return nil } return errors.NotValidf("access level %s", a) }
[ "func", "(", "a", "Access", ")", "Validate", "(", ")", "error", "{", "switch", "a", "{", "case", "NoAccess", ",", "AdminAccess", ",", "ReadAccess", ",", "WriteAccess", ",", "LoginAccess", ",", "AddModelAccess", ",", "SuperuserAccess", ":", "return", "nil", ...
// Validate returns error if the current is not a valid access level.
[ "Validate", "returns", "error", "if", "the", "current", "is", "not", "a", "valid", "access", "level", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/permission/access.go#L43-L50
4,961
juju/juju
permission/access.go
ValidateModelAccess
func ValidateModelAccess(access Access) error { switch access { case ReadAccess, WriteAccess, AdminAccess: return nil } return errors.NotValidf("%q model access", access) }
go
func ValidateModelAccess(access Access) error { switch access { case ReadAccess, WriteAccess, AdminAccess: return nil } return errors.NotValidf("%q model access", access) }
[ "func", "ValidateModelAccess", "(", "access", "Access", ")", "error", "{", "switch", "access", "{", "case", "ReadAccess", ",", "WriteAccess", ",", "AdminAccess", ":", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ...
// ValidateModelAccess returns error if the passed access is not a valid // model access level.
[ "ValidateModelAccess", "returns", "error", "if", "the", "passed", "access", "is", "not", "a", "valid", "model", "access", "level", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/permission/access.go#L54-L60
4,962
juju/juju
permission/access.go
ValidateOfferAccess
func ValidateOfferAccess(access Access) error { switch access { case ReadAccess, ConsumeAccess, AdminAccess: return nil } return errors.NotValidf("%q offer access", access) }
go
func ValidateOfferAccess(access Access) error { switch access { case ReadAccess, ConsumeAccess, AdminAccess: return nil } return errors.NotValidf("%q offer access", access) }
[ "func", "ValidateOfferAccess", "(", "access", "Access", ")", "error", "{", "switch", "access", "{", "case", "ReadAccess", ",", "ConsumeAccess", ",", "AdminAccess", ":", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ...
// ValidateOfferAccess returns error if the passed access is not a valid // offer access level.
[ "ValidateOfferAccess", "returns", "error", "if", "the", "passed", "access", "is", "not", "a", "valid", "offer", "access", "level", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/permission/access.go#L64-L70
4,963
juju/juju
permission/access.go
ValidateCloudAccess
func ValidateCloudAccess(access Access) error { switch access { case AddModelAccess, AdminAccess: return nil } return errors.NotValidf("%q cloud access", access) }
go
func ValidateCloudAccess(access Access) error { switch access { case AddModelAccess, AdminAccess: return nil } return errors.NotValidf("%q cloud access", access) }
[ "func", "ValidateCloudAccess", "(", "access", "Access", ")", "error", "{", "switch", "access", "{", "case", "AddModelAccess", ",", "AdminAccess", ":", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "access", "...
// ValidateCloudAccess returns error if the passed access is not a valid // cloud access level.
[ "ValidateCloudAccess", "returns", "error", "if", "the", "passed", "access", "is", "not", "a", "valid", "cloud", "access", "level", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/permission/access.go#L74-L80
4,964
juju/juju
permission/access.go
ValidateControllerAccess
func ValidateControllerAccess(access Access) error { switch access { case LoginAccess, SuperuserAccess: return nil } return errors.NotValidf("%q controller access", access) }
go
func ValidateControllerAccess(access Access) error { switch access { case LoginAccess, SuperuserAccess: return nil } return errors.NotValidf("%q controller access", access) }
[ "func", "ValidateControllerAccess", "(", "access", "Access", ")", "error", "{", "switch", "access", "{", "case", "LoginAccess", ",", "SuperuserAccess", ":", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "access...
//ValidateControllerAccess returns error if the passed access is not a valid // controller access level.
[ "ValidateControllerAccess", "returns", "error", "if", "the", "passed", "access", "is", "not", "a", "valid", "controller", "access", "level", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/permission/access.go#L84-L90
4,965
juju/juju
permission/access.go
EqualOrGreaterModelAccessThan
func (a Access) EqualOrGreaterModelAccessThan(access Access) bool { v1, v2 := a.modelValue(), access.modelValue() if v1 < 0 || v2 < 0 { return false } return v1 >= v2 }
go
func (a Access) EqualOrGreaterModelAccessThan(access Access) bool { v1, v2 := a.modelValue(), access.modelValue() if v1 < 0 || v2 < 0 { return false } return v1 >= v2 }
[ "func", "(", "a", "Access", ")", "EqualOrGreaterModelAccessThan", "(", "access", "Access", ")", "bool", "{", "v1", ",", "v2", ":=", "a", ".", "modelValue", "(", ")", ",", "access", ".", "modelValue", "(", ")", "\n", "if", "v1", "<", "0", "||", "v2", ...
// EqualOrGreaterModelAccessThan returns true if the current access is equal // or greater than the passed in access level.
[ "EqualOrGreaterModelAccessThan", "returns", "true", "if", "the", "current", "access", "is", "equal", "or", "greater", "than", "the", "passed", "in", "access", "level", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/permission/access.go#L133-L139
4,966
juju/juju
permission/access.go
EqualOrGreaterControllerAccessThan
func (a Access) EqualOrGreaterControllerAccessThan(access Access) bool { v1, v2 := a.controllerValue(), access.controllerValue() if v1 < 0 || v2 < 0 { return false } return v1 >= v2 }
go
func (a Access) EqualOrGreaterControllerAccessThan(access Access) bool { v1, v2 := a.controllerValue(), access.controllerValue() if v1 < 0 || v2 < 0 { return false } return v1 >= v2 }
[ "func", "(", "a", "Access", ")", "EqualOrGreaterControllerAccessThan", "(", "access", "Access", ")", "bool", "{", "v1", ",", "v2", ":=", "a", ".", "controllerValue", "(", ")", ",", "access", ".", "controllerValue", "(", ")", "\n", "if", "v1", "<", "0", ...
// EqualOrGreaterControllerAccessThan returns true if the current access is // equal or greater than the passed in access level.
[ "EqualOrGreaterControllerAccessThan", "returns", "true", "if", "the", "current", "access", "is", "equal", "or", "greater", "than", "the", "passed", "in", "access", "level", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/permission/access.go#L153-L159
4,967
juju/juju
permission/access.go
EqualOrGreaterCloudAccessThan
func (a Access) EqualOrGreaterCloudAccessThan(access Access) bool { v1, v2 := a.cloudValue(), access.cloudValue() if v1 < 0 || v2 < 0 { return false } return v1 >= v2 }
go
func (a Access) EqualOrGreaterCloudAccessThan(access Access) bool { v1, v2 := a.cloudValue(), access.cloudValue() if v1 < 0 || v2 < 0 { return false } return v1 >= v2 }
[ "func", "(", "a", "Access", ")", "EqualOrGreaterCloudAccessThan", "(", "access", "Access", ")", "bool", "{", "v1", ",", "v2", ":=", "a", ".", "cloudValue", "(", ")", ",", "access", ".", "cloudValue", "(", ")", "\n", "if", "v1", "<", "0", "||", "v2", ...
// EqualOrGreaterCloudAccessThan returns true if the current access is // equal or greater than the passed in access level.
[ "EqualOrGreaterCloudAccessThan", "returns", "true", "if", "the", "current", "access", "is", "equal", "or", "greater", "than", "the", "passed", "in", "access", "level", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/permission/access.go#L173-L179
4,968
juju/juju
permission/access.go
EqualOrGreaterOfferAccessThan
func (a Access) EqualOrGreaterOfferAccessThan(access Access) bool { v1, v2 := a.offerValue(), access.offerValue() if v1 < 0 || v2 < 0 { return false } return v1 >= v2 }
go
func (a Access) EqualOrGreaterOfferAccessThan(access Access) bool { v1, v2 := a.offerValue(), access.offerValue() if v1 < 0 || v2 < 0 { return false } return v1 >= v2 }
[ "func", "(", "a", "Access", ")", "EqualOrGreaterOfferAccessThan", "(", "access", "Access", ")", "bool", "{", "v1", ",", "v2", ":=", "a", ".", "offerValue", "(", ")", ",", "access", ".", "offerValue", "(", ")", "\n", "if", "v1", "<", "0", "||", "v2", ...
// EqualOrGreaterOfferAccessThan returns true if the current access is // equal or greater than the passed in access level.
[ "EqualOrGreaterOfferAccessThan", "returns", "true", "if", "the", "current", "access", "is", "equal", "or", "greater", "than", "the", "passed", "in", "access", "level", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/permission/access.go#L198-L204
4,969
juju/juju
cmd/juju/storage/show.go
NewShowCommand
func NewShowCommand() cmd.Command { cmd := &showCommand{} cmd.newAPIFunc = func() (StorageShowAPI, error) { return cmd.NewStorageAPI() } return modelcmd.Wrap(cmd) }
go
func NewShowCommand() cmd.Command { cmd := &showCommand{} cmd.newAPIFunc = func() (StorageShowAPI, error) { return cmd.NewStorageAPI() } return modelcmd.Wrap(cmd) }
[ "func", "NewShowCommand", "(", ")", "cmd", ".", "Command", "{", "cmd", ":=", "&", "showCommand", "{", "}", "\n", "cmd", ".", "newAPIFunc", "=", "func", "(", ")", "(", "StorageShowAPI", ",", "error", ")", "{", "return", "cmd", ".", "NewStorageAPI", "(",...
// NewShowCommand returns a command that shows storage details // on the specified machine
[ "NewShowCommand", "returns", "a", "command", "that", "shows", "storage", "details", "on", "the", "specified", "machine" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/storage/show.go#L20-L26
4,970
juju/juju
api/spaces/spaces.go
ListSpaces
func (api *API) ListSpaces() ([]params.Space, error) { var response params.ListSpacesResults err := api.facade.FacadeCall("ListSpaces", nil, &response) if params.IsCodeNotSupported(err) { return response.Results, errors.NewNotSupported(nil, err.Error()) } return response.Results, err }
go
func (api *API) ListSpaces() ([]params.Space, error) { var response params.ListSpacesResults err := api.facade.FacadeCall("ListSpaces", nil, &response) if params.IsCodeNotSupported(err) { return response.Results, errors.NewNotSupported(nil, err.Error()) } return response.Results, err }
[ "func", "(", "api", "*", "API", ")", "ListSpaces", "(", ")", "(", "[", "]", "params", ".", "Space", ",", "error", ")", "{", "var", "response", "params", ".", "ListSpacesResults", "\n", "err", ":=", "api", ".", "facade", ".", "FacadeCall", "(", "\"", ...
// ListSpaces lists all available spaces and their associated subnets.
[ "ListSpaces", "lists", "all", "available", "spaces", "and", "their", "associated", "subnets", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/spaces/spaces.go#L67-L74
4,971
juju/juju
api/spaces/spaces.go
ReloadSpaces
func (api *API) ReloadSpaces() error { if api.facade.BestAPIVersion() < 3 { return errors.NewNotSupported(nil, "Controller does not support reloading spaces") } err := api.facade.FacadeCall("ReloadSpaces", nil, nil) if params.IsCodeNotSupported(err) { return errors.NewNotSupported(nil, err.Error()) } return err }
go
func (api *API) ReloadSpaces() error { if api.facade.BestAPIVersion() < 3 { return errors.NewNotSupported(nil, "Controller does not support reloading spaces") } err := api.facade.FacadeCall("ReloadSpaces", nil, nil) if params.IsCodeNotSupported(err) { return errors.NewNotSupported(nil, err.Error()) } return err }
[ "func", "(", "api", "*", "API", ")", "ReloadSpaces", "(", ")", "error", "{", "if", "api", ".", "facade", ".", "BestAPIVersion", "(", ")", "<", "3", "{", "return", "errors", ".", "NewNotSupported", "(", "nil", ",", "\"", "\"", ")", "\n", "}", "\n", ...
// ReloadSpaces reloads spaces from substrate
[ "ReloadSpaces", "reloads", "spaces", "from", "substrate" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/spaces/spaces.go#L77-L86
4,972
juju/juju
cmd/modelcmd/apicontext.go
newAPIContext
func newAPIContext(ctxt *cmd.Context, opts *AuthOpts, store jujuclient.CookieStore, controllerName string) (*apiContext, error) { jar0, err := store.CookieJar(controllerName) if err != nil { return nil, errors.Trace(err) } // The JUJU_USER_DOMAIN environment variable specifies // the preferred user domain when discharging third party caveats. // We set up a cookie jar that will send it to all sites because // we don't know where the third party might be. jar := &domainCookieJar{ CookieJar: jar0, domain: os.Getenv("JUJU_USER_DOMAIN"), } var visitors []httpbakery.Visitor if ctxt != nil && opts != nil && opts.NoBrowser { filler := &form.IOFiller{ In: ctxt.Stdin, Out: ctxt.Stdout, } newVisitor := ussologin.NewVisitor("juju", filler, jujuclient.NewTokenStore()) visitors = append(visitors, newVisitor) } else { visitors = append(visitors, httpbakery.WebBrowserVisitor) } return &apiContext{ jar: jar, webPageVisitor: httpbakery.NewMultiVisitor(visitors...), }, nil }
go
func newAPIContext(ctxt *cmd.Context, opts *AuthOpts, store jujuclient.CookieStore, controllerName string) (*apiContext, error) { jar0, err := store.CookieJar(controllerName) if err != nil { return nil, errors.Trace(err) } // The JUJU_USER_DOMAIN environment variable specifies // the preferred user domain when discharging third party caveats. // We set up a cookie jar that will send it to all sites because // we don't know where the third party might be. jar := &domainCookieJar{ CookieJar: jar0, domain: os.Getenv("JUJU_USER_DOMAIN"), } var visitors []httpbakery.Visitor if ctxt != nil && opts != nil && opts.NoBrowser { filler := &form.IOFiller{ In: ctxt.Stdin, Out: ctxt.Stdout, } newVisitor := ussologin.NewVisitor("juju", filler, jujuclient.NewTokenStore()) visitors = append(visitors, newVisitor) } else { visitors = append(visitors, httpbakery.WebBrowserVisitor) } return &apiContext{ jar: jar, webPageVisitor: httpbakery.NewMultiVisitor(visitors...), }, nil }
[ "func", "newAPIContext", "(", "ctxt", "*", "cmd", ".", "Context", ",", "opts", "*", "AuthOpts", ",", "store", "jujuclient", ".", "CookieStore", ",", "controllerName", "string", ")", "(", "*", "apiContext", ",", "error", ")", "{", "jar0", ",", "err", ":="...
// newAPIContext returns an API context that will use the given // context for user interactions when authorizing. // The returned API context must be closed after use. // // If ctxt is nil, no command-line authorization // will be supported. // // This function is provided for use by commands that cannot use // CommandBase. Most clients should use that instead.
[ "newAPIContext", "returns", "an", "API", "context", "that", "will", "use", "the", "given", "context", "for", "user", "interactions", "when", "authorizing", ".", "The", "returned", "API", "context", "must", "be", "closed", "after", "use", ".", "If", "ctxt", "...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/modelcmd/apicontext.go#L51-L79
4,973
juju/juju
cmd/modelcmd/apicontext.go
NewBakeryClient
func (ctx *apiContext) NewBakeryClient() *httpbakery.Client { client := httpbakery.NewClient() client.Jar = ctx.jar client.WebPageVisitor = ctx.webPageVisitor return client }
go
func (ctx *apiContext) NewBakeryClient() *httpbakery.Client { client := httpbakery.NewClient() client.Jar = ctx.jar client.WebPageVisitor = ctx.webPageVisitor return client }
[ "func", "(", "ctx", "*", "apiContext", ")", "NewBakeryClient", "(", ")", "*", "httpbakery", ".", "Client", "{", "client", ":=", "httpbakery", ".", "NewClient", "(", ")", "\n", "client", ".", "Jar", "=", "ctx", ".", "jar", "\n", "client", ".", "WebPageV...
// NewBakeryClient returns a new httpbakery.Client, using the API context's // persistent cookie jar and web page visitor.
[ "NewBakeryClient", "returns", "a", "new", "httpbakery", ".", "Client", "using", "the", "API", "context", "s", "persistent", "cookie", "jar", "and", "web", "page", "visitor", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/modelcmd/apicontext.go#L89-L94
4,974
juju/juju
cmd/modelcmd/apicontext.go
Close
func (ctxt *apiContext) Close() error { if err := ctxt.jar.Save(); err != nil { return errors.Annotatef(err, "cannot save cookie jar") } return nil }
go
func (ctxt *apiContext) Close() error { if err := ctxt.jar.Save(); err != nil { return errors.Annotatef(err, "cannot save cookie jar") } return nil }
[ "func", "(", "ctxt", "*", "apiContext", ")", "Close", "(", ")", "error", "{", "if", "err", ":=", "ctxt", ".", "jar", ".", "Save", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ")", "\...
// Close closes the API context, saving any cookies to the // persistent cookie jar.
[ "Close", "closes", "the", "API", "context", "saving", "any", "cookies", "to", "the", "persistent", "cookie", "jar", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/modelcmd/apicontext.go#L98-L103
4,975
juju/juju
cmd/modelcmd/apicontext.go
Cookies
func (j *domainCookieJar) Cookies(u *url.URL) []*http.Cookie { cookies := j.CookieJar.Cookies(u) if j.domain == "" { return cookies } // Allow the site to override if it wants to. for _, c := range cookies { if c.Name == domainCookieName { return cookies } } return append(cookies, &http.Cookie{ Name: domainCookieName, Value: j.domain, }) }
go
func (j *domainCookieJar) Cookies(u *url.URL) []*http.Cookie { cookies := j.CookieJar.Cookies(u) if j.domain == "" { return cookies } // Allow the site to override if it wants to. for _, c := range cookies { if c.Name == domainCookieName { return cookies } } return append(cookies, &http.Cookie{ Name: domainCookieName, Value: j.domain, }) }
[ "func", "(", "j", "*", "domainCookieJar", ")", "Cookies", "(", "u", "*", "url", ".", "URL", ")", "[", "]", "*", "http", ".", "Cookie", "{", "cookies", ":=", "j", ".", "CookieJar", ".", "Cookies", "(", "u", ")", "\n", "if", "j", ".", "domain", "...
// Cookies implements http.CookieJar.Cookies by // adding the domain cookie when the domain is non-empty.
[ "Cookies", "implements", "http", ".", "CookieJar", ".", "Cookies", "by", "adding", "the", "domain", "cookie", "when", "the", "domain", "is", "non", "-", "empty", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/modelcmd/apicontext.go#L117-L132
4,976
juju/juju
apiserver/charms.go
manifestSender
func (h *charmsHandler) manifestSender(w http.ResponseWriter, r *http.Request, bundle *charm.CharmArchive) error { manifest, err := bundle.Manifest() if err != nil { return errors.Annotatef(err, "unable to read manifest in %q", bundle.Path) } return errors.Trace(sendStatusAndJSON(w, http.StatusOK, &params.CharmsResponse{ Files: manifest.SortedValues(), })) }
go
func (h *charmsHandler) manifestSender(w http.ResponseWriter, r *http.Request, bundle *charm.CharmArchive) error { manifest, err := bundle.Manifest() if err != nil { return errors.Annotatef(err, "unable to read manifest in %q", bundle.Path) } return errors.Trace(sendStatusAndJSON(w, http.StatusOK, &params.CharmsResponse{ Files: manifest.SortedValues(), })) }
[ "func", "(", "h", "*", "charmsHandler", ")", "manifestSender", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "bundle", "*", "charm", ".", "CharmArchive", ")", "error", "{", "manifest", ",", "err", ":=", "bundle", ...
// manifestSender sends a JSON-encoded response to the client including the // list of files contained in the charm bundle.
[ "manifestSender", "sends", "a", "JSON", "-", "encoded", "response", "to", "the", "client", "including", "the", "list", "of", "files", "contained", "in", "the", "charm", "bundle", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/charms.go#L156-L164
4,977
juju/juju
apiserver/charms.go
archiveEntrySender
func (h *charmsHandler) archiveEntrySender(filePath string, serveIcon bool) bundleContentSenderFunc { return func(w http.ResponseWriter, r *http.Request, bundle *charm.CharmArchive) error { contents, err := common.CharmArchiveEntry(bundle.Path, filePath, serveIcon) if err != nil { return errors.Trace(err) } ctype := mime.TypeByExtension(filepath.Ext(filePath)) if ctype != "" { // Older mime.types may map .js to x-javascript. // Map it to javascript for consistency. if ctype == params.ContentTypeXJS { ctype = params.ContentTypeJS } w.Header().Set("Content-Type", ctype) } w.Header().Set("Content-Length", strconv.Itoa(len(contents))) w.WriteHeader(http.StatusOK) io.Copy(w, bytes.NewReader(contents)) return nil } }
go
func (h *charmsHandler) archiveEntrySender(filePath string, serveIcon bool) bundleContentSenderFunc { return func(w http.ResponseWriter, r *http.Request, bundle *charm.CharmArchive) error { contents, err := common.CharmArchiveEntry(bundle.Path, filePath, serveIcon) if err != nil { return errors.Trace(err) } ctype := mime.TypeByExtension(filepath.Ext(filePath)) if ctype != "" { // Older mime.types may map .js to x-javascript. // Map it to javascript for consistency. if ctype == params.ContentTypeXJS { ctype = params.ContentTypeJS } w.Header().Set("Content-Type", ctype) } w.Header().Set("Content-Length", strconv.Itoa(len(contents))) w.WriteHeader(http.StatusOK) io.Copy(w, bytes.NewReader(contents)) return nil } }
[ "func", "(", "h", "*", "charmsHandler", ")", "archiveEntrySender", "(", "filePath", "string", ",", "serveIcon", "bool", ")", "bundleContentSenderFunc", "{", "return", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ","...
// archiveEntrySender returns a bundleContentSenderFunc which is responsible // for sending the contents of filePath included in the given charm bundle. If // filePath does not identify a file or a symlink, a 403 forbidden error is // returned. If serveIcon is true, then the charm icon.svg file is sent, or a // default icon if that file is not included in the charm.
[ "archiveEntrySender", "returns", "a", "bundleContentSenderFunc", "which", "is", "responsible", "for", "sending", "the", "contents", "of", "filePath", "included", "in", "the", "given", "charm", "bundle", ".", "If", "filePath", "does", "not", "identify", "a", "file"...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/charms.go#L171-L191
4,978
juju/juju
apiserver/charms.go
archiveSender
func (h *charmsHandler) archiveSender(w http.ResponseWriter, r *http.Request, bundle *charm.CharmArchive) error { // Note that http.ServeFile's error responses are not our standard JSON // responses (they are the usual textual error messages as produced // by http.Error), but there's not a great deal we can do about that, // except accept non-JSON error responses in the client, because // http.ServeFile does not provide a way of customizing its // error responses. http.ServeFile(w, r, bundle.Path) return nil }
go
func (h *charmsHandler) archiveSender(w http.ResponseWriter, r *http.Request, bundle *charm.CharmArchive) error { // Note that http.ServeFile's error responses are not our standard JSON // responses (they are the usual textual error messages as produced // by http.Error), but there's not a great deal we can do about that, // except accept non-JSON error responses in the client, because // http.ServeFile does not provide a way of customizing its // error responses. http.ServeFile(w, r, bundle.Path) return nil }
[ "func", "(", "h", "*", "charmsHandler", ")", "archiveSender", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "bundle", "*", "charm", ".", "CharmArchive", ")", "error", "{", "// Note that http.ServeFile's error responses are ...
// archiveSender is a bundleContentSenderFunc which is responsible for sending // the contents of the given charm bundle.
[ "archiveSender", "is", "a", "bundleContentSenderFunc", "which", "is", "responsible", "for", "sending", "the", "contents", "of", "the", "given", "charm", "bundle", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/charms.go#L195-L204
4,979
juju/juju
apiserver/charms.go
processUploadedArchive
func (h *charmsHandler) processUploadedArchive(path string) error { // Open the archive as a zip. f, err := os.OpenFile(path, os.O_RDWR, 0644) if err != nil { return err } defer f.Close() fi, err := f.Stat() if err != nil { return err } zipr, err := zip.NewReader(f, fi.Size()) if err != nil { return errors.Annotate(err, "cannot open charm archive") } // Find out the root dir prefix from the archive. rootDir, err := h.findArchiveRootDir(zipr) if err != nil { return errors.Annotate(err, "cannot read charm archive") } if rootDir == "." { // Normal charm, just use charm.ReadCharmArchive). return nil } // There is one or more subdirs, so we need extract it to a temp // dir and then read it as a charm dir. tempDir, err := ioutil.TempDir("", "charm-extract") if err != nil { return errors.Annotate(err, "cannot create temp directory") } defer os.RemoveAll(tempDir) if err := ziputil.Extract(zipr, tempDir, rootDir); err != nil { return errors.Annotate(err, "cannot extract charm archive") } dir, err := charm.ReadCharmDir(tempDir) if err != nil { return errors.Annotate(err, "cannot read extracted archive") } // Now repackage the dir as a bundle at the original path. if err := f.Truncate(0); err != nil { return err } if err := dir.ArchiveTo(f); err != nil { return err } return nil }
go
func (h *charmsHandler) processUploadedArchive(path string) error { // Open the archive as a zip. f, err := os.OpenFile(path, os.O_RDWR, 0644) if err != nil { return err } defer f.Close() fi, err := f.Stat() if err != nil { return err } zipr, err := zip.NewReader(f, fi.Size()) if err != nil { return errors.Annotate(err, "cannot open charm archive") } // Find out the root dir prefix from the archive. rootDir, err := h.findArchiveRootDir(zipr) if err != nil { return errors.Annotate(err, "cannot read charm archive") } if rootDir == "." { // Normal charm, just use charm.ReadCharmArchive). return nil } // There is one or more subdirs, so we need extract it to a temp // dir and then read it as a charm dir. tempDir, err := ioutil.TempDir("", "charm-extract") if err != nil { return errors.Annotate(err, "cannot create temp directory") } defer os.RemoveAll(tempDir) if err := ziputil.Extract(zipr, tempDir, rootDir); err != nil { return errors.Annotate(err, "cannot extract charm archive") } dir, err := charm.ReadCharmDir(tempDir) if err != nil { return errors.Annotate(err, "cannot read extracted archive") } // Now repackage the dir as a bundle at the original path. if err := f.Truncate(0); err != nil { return err } if err := dir.ArchiveTo(f); err != nil { return err } return nil }
[ "func", "(", "h", "*", "charmsHandler", ")", "processUploadedArchive", "(", "path", "string", ")", "error", "{", "// Open the archive as a zip.", "f", ",", "err", ":=", "os", ".", "OpenFile", "(", "path", ",", "os", ".", "O_RDWR", ",", "0644", ")", "\n", ...
// processUploadedArchive opens the given charm archive from path, // inspects it to see if it has all files at the root of the archive // or it has subdirs. It repackages the archive so it has all the // files at the root dir, if necessary, replacing the original archive // at path.
[ "processUploadedArchive", "opens", "the", "given", "charm", "archive", "from", "path", "inspects", "it", "to", "see", "if", "it", "has", "all", "files", "at", "the", "root", "of", "the", "archive", "or", "it", "has", "subdirs", ".", "It", "repackages", "th...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/charms.go#L307-L356
4,980
juju/juju
apiserver/charms.go
findArchiveRootDir
func (h *charmsHandler) findArchiveRootDir(zipr *zip.Reader) (string, error) { paths, err := ziputil.Find(zipr, "metadata.yaml") if err != nil { return "", err } switch len(paths) { case 0: return "", errors.Errorf("invalid charm archive: missing metadata.yaml") case 1: default: sort.Sort(byDepth(paths)) if depth(paths[0]) == depth(paths[1]) { return "", errors.Errorf("invalid charm archive: ambiguous root directory") } } return filepath.Dir(paths[0]), nil }
go
func (h *charmsHandler) findArchiveRootDir(zipr *zip.Reader) (string, error) { paths, err := ziputil.Find(zipr, "metadata.yaml") if err != nil { return "", err } switch len(paths) { case 0: return "", errors.Errorf("invalid charm archive: missing metadata.yaml") case 1: default: sort.Sort(byDepth(paths)) if depth(paths[0]) == depth(paths[1]) { return "", errors.Errorf("invalid charm archive: ambiguous root directory") } } return filepath.Dir(paths[0]), nil }
[ "func", "(", "h", "*", "charmsHandler", ")", "findArchiveRootDir", "(", "zipr", "*", "zip", ".", "Reader", ")", "(", "string", ",", "error", ")", "{", "paths", ",", "err", ":=", "ziputil", ".", "Find", "(", "zipr", ",", "\"", "\"", ")", "\n", "if",...
// findArchiveRootDir scans a zip archive and returns the rootDir of // the archive, the one containing metadata.yaml, config.yaml and // revision files, or an error if the archive appears invalid.
[ "findArchiveRootDir", "scans", "a", "zip", "archive", "and", "returns", "the", "rootDir", "of", "the", "archive", "the", "one", "containing", "metadata", ".", "yaml", "config", ".", "yaml", "and", "revision", "files", "or", "an", "error", "if", "the", "archi...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/charms.go#L361-L377
4,981
juju/juju
apiserver/charms.go
repackageAndUploadCharm
func (h *charmsHandler) repackageAndUploadCharm(st *state.State, archive *charm.CharmArchive, curl *charm.URL) error { // Create a temp dir to contain the extracted charm dir. tempDir, err := ioutil.TempDir("", "charm-download") if err != nil { return errors.Annotate(err, "cannot create temp directory") } defer os.RemoveAll(tempDir) extractPath := filepath.Join(tempDir, "extracted") // Expand and repack it with the revision specified by curl. archive.SetRevision(curl.Revision) if err := archive.ExpandTo(extractPath); err != nil { return errors.Annotate(err, "cannot extract uploaded charm") } charmDir, err := charm.ReadCharmDir(extractPath) if err != nil { return errors.Annotate(err, "cannot read extracted charm") } // Try to get the version details here. // read just the first line of the file. var version string versionPath := filepath.Join(extractPath, "version") if file, err := os.Open(versionPath); err == nil { scanner := bufio.NewScanner(file) scanner.Scan() file.Close() if err := scanner.Err(); err != nil { return errors.Annotate(err, "cannot read version file") } revLine := scanner.Text() // bzr revision info starts with "revision-id: " so strip that. revLine = strings.TrimPrefix(revLine, "revision-id: ") version = fmt.Sprintf("%.100s", revLine) } else if !os.IsNotExist(err) { return errors.Annotate(err, "cannot open version file") } // Bundle the charm and calculate its sha256 hash at the same time. var repackagedArchive bytes.Buffer hash := sha256.New() err = charmDir.ArchiveTo(io.MultiWriter(hash, &repackagedArchive)) if err != nil { return errors.Annotate(err, "cannot repackage uploaded charm") } bundleSHA256 := hex.EncodeToString(hash.Sum(nil)) info := application.CharmArchive{ ID: curl, Charm: archive, Data: &repackagedArchive, Size: int64(repackagedArchive.Len()), SHA256: bundleSHA256, CharmVersion: version, } // Store the charm archive in environment storage. shim := application.NewStateShim(st) return application.StoreCharmArchive(shim, info) }
go
func (h *charmsHandler) repackageAndUploadCharm(st *state.State, archive *charm.CharmArchive, curl *charm.URL) error { // Create a temp dir to contain the extracted charm dir. tempDir, err := ioutil.TempDir("", "charm-download") if err != nil { return errors.Annotate(err, "cannot create temp directory") } defer os.RemoveAll(tempDir) extractPath := filepath.Join(tempDir, "extracted") // Expand and repack it with the revision specified by curl. archive.SetRevision(curl.Revision) if err := archive.ExpandTo(extractPath); err != nil { return errors.Annotate(err, "cannot extract uploaded charm") } charmDir, err := charm.ReadCharmDir(extractPath) if err != nil { return errors.Annotate(err, "cannot read extracted charm") } // Try to get the version details here. // read just the first line of the file. var version string versionPath := filepath.Join(extractPath, "version") if file, err := os.Open(versionPath); err == nil { scanner := bufio.NewScanner(file) scanner.Scan() file.Close() if err := scanner.Err(); err != nil { return errors.Annotate(err, "cannot read version file") } revLine := scanner.Text() // bzr revision info starts with "revision-id: " so strip that. revLine = strings.TrimPrefix(revLine, "revision-id: ") version = fmt.Sprintf("%.100s", revLine) } else if !os.IsNotExist(err) { return errors.Annotate(err, "cannot open version file") } // Bundle the charm and calculate its sha256 hash at the same time. var repackagedArchive bytes.Buffer hash := sha256.New() err = charmDir.ArchiveTo(io.MultiWriter(hash, &repackagedArchive)) if err != nil { return errors.Annotate(err, "cannot repackage uploaded charm") } bundleSHA256 := hex.EncodeToString(hash.Sum(nil)) info := application.CharmArchive{ ID: curl, Charm: archive, Data: &repackagedArchive, Size: int64(repackagedArchive.Len()), SHA256: bundleSHA256, CharmVersion: version, } // Store the charm archive in environment storage. shim := application.NewStateShim(st) return application.StoreCharmArchive(shim, info) }
[ "func", "(", "h", "*", "charmsHandler", ")", "repackageAndUploadCharm", "(", "st", "*", "state", ".", "State", ",", "archive", "*", "charm", ".", "CharmArchive", ",", "curl", "*", "charm", ".", "URL", ")", "error", "{", "// Create a temp dir to contain the ext...
// repackageAndUploadCharm expands the given charm archive to a // temporary directory, repackages it with the given curl's revision, // then uploads it to storage, and finally updates the state.
[ "repackageAndUploadCharm", "expands", "the", "given", "charm", "archive", "to", "a", "temporary", "directory", "repackages", "it", "with", "the", "given", "curl", "s", "revision", "then", "uploads", "it", "to", "storage", "and", "finally", "updates", "the", "sta...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/charms.go#L392-L451
4,982
juju/juju
apiserver/charms.go
sendJSONError
func sendJSONError(w http.ResponseWriter, req *http.Request, err error) error { logger.Errorf("returning error from %s %s: %s", req.Method, req.URL, errors.Details(err)) perr, status := common.ServerErrorAndStatus(err) return errors.Trace(sendStatusAndJSON(w, status, &params.CharmsResponse{ Error: perr.Message, ErrorCode: perr.Code, ErrorInfo: perr.Info, })) }
go
func sendJSONError(w http.ResponseWriter, req *http.Request, err error) error { logger.Errorf("returning error from %s %s: %s", req.Method, req.URL, errors.Details(err)) perr, status := common.ServerErrorAndStatus(err) return errors.Trace(sendStatusAndJSON(w, status, &params.CharmsResponse{ Error: perr.Message, ErrorCode: perr.Code, ErrorInfo: perr.Info, })) }
[ "func", "sendJSONError", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ",", "err", "error", ")", "error", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "req", ".", "Method", ",", "req", ".", "URL", ",", "er...
// sendJSONError sends a JSON-encoded error response. Note the // difference from the error response sent by the sendError function - // the error is encoded in the Error field as a string, not an Error // object.
[ "sendJSONError", "sends", "a", "JSON", "-", "encoded", "error", "response", ".", "Note", "the", "difference", "from", "the", "error", "response", "sent", "by", "the", "sendError", "function", "-", "the", "error", "is", "encoded", "in", "the", "Error", "field...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/charms.go#L502-L510
4,983
juju/juju
apiserver/charms.go
sendBundleContent
func sendBundleContent( w http.ResponseWriter, r *http.Request, archivePath string, sender bundleContentSenderFunc, ) error { bundle, err := charm.ReadCharmArchive(archivePath) if err != nil { return errors.Annotatef(err, "unable to read archive in %q", archivePath) } // The bundleContentSenderFunc will set up and send an appropriate response. if err := sender(w, r, bundle); err != nil { return errors.Trace(err) } return nil }
go
func sendBundleContent( w http.ResponseWriter, r *http.Request, archivePath string, sender bundleContentSenderFunc, ) error { bundle, err := charm.ReadCharmArchive(archivePath) if err != nil { return errors.Annotatef(err, "unable to read archive in %q", archivePath) } // The bundleContentSenderFunc will set up and send an appropriate response. if err := sender(w, r, bundle); err != nil { return errors.Trace(err) } return nil }
[ "func", "sendBundleContent", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "archivePath", "string", ",", "sender", "bundleContentSenderFunc", ",", ")", "error", "{", "bundle", ",", "err", ":=", "charm", ".", "ReadCharmA...
// sendBundleContent uses the given bundleContentSenderFunc to send a // response related to the charm archive located in the given // archivePath.
[ "sendBundleContent", "uses", "the", "given", "bundleContentSenderFunc", "to", "send", "a", "response", "related", "to", "the", "charm", "archive", "located", "in", "the", "given", "archivePath", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/charms.go#L515-L530
4,984
juju/juju
cmd/juju/storage/storage.go
NewStorageAPI
func (c *StorageCommandBase) NewStorageAPI() (*storage.Client, error) { root, err := c.NewAPIRoot() if err != nil { return nil, err } return storage.NewClient(root), nil }
go
func (c *StorageCommandBase) NewStorageAPI() (*storage.Client, error) { root, err := c.NewAPIRoot() if err != nil { return nil, err } return storage.NewClient(root), nil }
[ "func", "(", "c", "*", "StorageCommandBase", ")", "NewStorageAPI", "(", ")", "(", "*", "storage", ".", "Client", ",", "error", ")", "{", "root", ",", "err", ":=", "c", ".", "NewAPIRoot", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil...
// NewStorageAPI returns a storage api for the root api endpoint // that the environment command returns.
[ "NewStorageAPI", "returns", "a", "storage", "api", "for", "the", "root", "api", "endpoint", "that", "the", "environment", "command", "returns", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/storage/storage.go#L27-L33
4,985
juju/juju
cmd/juju/storage/storage.go
formatStorageDetails
func formatStorageDetails(storages []params.StorageDetails) (map[string]StorageInfo, error) { if len(storages) == 0 { return nil, nil } output := make(map[string]StorageInfo) for _, details := range storages { storageTag, storageInfo, err := createStorageInfo(details) if err != nil { return nil, errors.Trace(err) } output[storageTag.Id()] = storageInfo } return output, nil }
go
func formatStorageDetails(storages []params.StorageDetails) (map[string]StorageInfo, error) { if len(storages) == 0 { return nil, nil } output := make(map[string]StorageInfo) for _, details := range storages { storageTag, storageInfo, err := createStorageInfo(details) if err != nil { return nil, errors.Trace(err) } output[storageTag.Id()] = storageInfo } return output, nil }
[ "func", "formatStorageDetails", "(", "storages", "[", "]", "params", ".", "StorageDetails", ")", "(", "map", "[", "string", "]", "StorageInfo", ",", "error", ")", "{", "if", "len", "(", "storages", ")", "==", "0", "{", "return", "nil", ",", "nil", "\n"...
// formatStorageDetails takes a set of StorageDetail and // creates a mapping from storage ID to storage details.
[ "formatStorageDetails", "takes", "a", "set", "of", "StorageDetail", "and", "creates", "a", "mapping", "from", "storage", "ID", "to", "storage", "details", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/storage/storage.go#L70-L83
4,986
juju/juju
state/mocks/watcher_mock.go
NewMockBaseWatcher
func NewMockBaseWatcher(ctrl *gomock.Controller) *MockBaseWatcher { mock := &MockBaseWatcher{ctrl: ctrl} mock.recorder = &MockBaseWatcherMockRecorder{mock} return mock }
go
func NewMockBaseWatcher(ctrl *gomock.Controller) *MockBaseWatcher { mock := &MockBaseWatcher{ctrl: ctrl} mock.recorder = &MockBaseWatcherMockRecorder{mock} return mock }
[ "func", "NewMockBaseWatcher", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockBaseWatcher", "{", "mock", ":=", "&", "MockBaseWatcher", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockBaseWatcherMockRecorder", "{", "...
// NewMockBaseWatcher creates a new mock instance
[ "NewMockBaseWatcher", "creates", "a", "new", "mock", "instance" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/mocks/watcher_mock.go#L25-L29
4,987
juju/juju
state/mocks/watcher_mock.go
Dead
func (m *MockBaseWatcher) Dead() <-chan struct{} { ret := m.ctrl.Call(m, "Dead") ret0, _ := ret[0].(<-chan struct{}) return ret0 }
go
func (m *MockBaseWatcher) Dead() <-chan struct{} { ret := m.ctrl.Call(m, "Dead") ret0, _ := ret[0].(<-chan struct{}) return ret0 }
[ "func", "(", "m", "*", "MockBaseWatcher", ")", "Dead", "(", ")", "<-", "chan", "struct", "{", "}", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ")", "\n", "ret0", ",", "_", ":=", "ret", "[", "0", "]", ".", "("...
// Dead mocks base method
[ "Dead", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/mocks/watcher_mock.go#L37-L41
4,988
juju/juju
state/mocks/watcher_mock.go
Dead
func (mr *MockBaseWatcherMockRecorder) Dead() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Dead", reflect.TypeOf((*MockBaseWatcher)(nil).Dead)) }
go
func (mr *MockBaseWatcherMockRecorder) Dead() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Dead", reflect.TypeOf((*MockBaseWatcher)(nil).Dead)) }
[ "func", "(", "mr", "*", "MockBaseWatcherMockRecorder", ")", "Dead", "(", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodType", "(", "mr", ".", "mock", ",", "\"", "\"", ",", "reflect", ".", "Typ...
// Dead indicates an expected call of Dead
[ "Dead", "indicates", "an", "expected", "call", "of", "Dead" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/mocks/watcher_mock.go#L44-L46
4,989
juju/juju
state/mocks/watcher_mock.go
WatchCollection
func (m *MockBaseWatcher) WatchCollection(arg0 string, arg1 chan<- watcher.Change) { m.ctrl.Call(m, "WatchCollection", arg0, arg1) }
go
func (m *MockBaseWatcher) WatchCollection(arg0 string, arg1 chan<- watcher.Change) { m.ctrl.Call(m, "WatchCollection", arg0, arg1) }
[ "func", "(", "m", "*", "MockBaseWatcher", ")", "WatchCollection", "(", "arg0", "string", ",", "arg1", "chan", "<-", "watcher", ".", "Change", ")", "{", "m", ".", "ctrl", ".", "Call", "(", "m", ",", "\"", "\"", ",", "arg0", ",", "arg1", ")", "\n", ...
// WatchCollection mocks base method
[ "WatchCollection", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/mocks/watcher_mock.go#L113-L115
4,990
juju/juju
state/mocks/watcher_mock.go
WatchCollectionWithFilter
func (m *MockBaseWatcher) WatchCollectionWithFilter(arg0 string, arg1 chan<- watcher.Change, arg2 func(interface{}) bool) { m.ctrl.Call(m, "WatchCollectionWithFilter", arg0, arg1, arg2) }
go
func (m *MockBaseWatcher) WatchCollectionWithFilter(arg0 string, arg1 chan<- watcher.Change, arg2 func(interface{}) bool) { m.ctrl.Call(m, "WatchCollectionWithFilter", arg0, arg1, arg2) }
[ "func", "(", "m", "*", "MockBaseWatcher", ")", "WatchCollectionWithFilter", "(", "arg0", "string", ",", "arg1", "chan", "<-", "watcher", ".", "Change", ",", "arg2", "func", "(", "interface", "{", "}", ")", "bool", ")", "{", "m", ".", "ctrl", ".", "Call...
// WatchCollectionWithFilter mocks base method
[ "WatchCollectionWithFilter", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/mocks/watcher_mock.go#L123-L125
4,991
juju/juju
state/mocks/watcher_mock.go
WatchCollectionWithFilter
func (mr *MockBaseWatcherMockRecorder) WatchCollectionWithFilter(arg0, arg1, arg2 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WatchCollectionWithFilter", reflect.TypeOf((*MockBaseWatcher)(nil).WatchCollectionWithFilter), arg0, arg1, arg2) }
go
func (mr *MockBaseWatcherMockRecorder) WatchCollectionWithFilter(arg0, arg1, arg2 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WatchCollectionWithFilter", reflect.TypeOf((*MockBaseWatcher)(nil).WatchCollectionWithFilter), arg0, arg1, arg2) }
[ "func", "(", "mr", "*", "MockBaseWatcherMockRecorder", ")", "WatchCollectionWithFilter", "(", "arg0", ",", "arg1", ",", "arg2", "interface", "{", "}", ")", "*", "gomock", ".", "Call", "{", "return", "mr", ".", "mock", ".", "ctrl", ".", "RecordCallWithMethodT...
// WatchCollectionWithFilter indicates an expected call of WatchCollectionWithFilter
[ "WatchCollectionWithFilter", "indicates", "an", "expected", "call", "of", "WatchCollectionWithFilter" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/mocks/watcher_mock.go#L128-L130
4,992
juju/juju
state/mocks/watcher_mock.go
WatchMulti
func (m *MockBaseWatcher) WatchMulti(arg0 string, arg1 []interface{}, arg2 chan<- watcher.Change) error { ret := m.ctrl.Call(m, "WatchMulti", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 }
go
func (m *MockBaseWatcher) WatchMulti(arg0 string, arg1 []interface{}, arg2 chan<- watcher.Change) error { ret := m.ctrl.Call(m, "WatchMulti", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 }
[ "func", "(", "m", "*", "MockBaseWatcher", ")", "WatchMulti", "(", "arg0", "string", ",", "arg1", "[", "]", "interface", "{", "}", ",", "arg2", "chan", "<-", "watcher", ".", "Change", ")", "error", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(...
// WatchMulti mocks base method
[ "WatchMulti", "mocks", "base", "method" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/mocks/watcher_mock.go#L133-L137
4,993
juju/juju
state/bakerystorage/interface.go
New
func New(config Config) (ExpirableStorage, error) { if err := config.Validate(); err != nil { return nil, errors.Annotate(err, "validating config") } return &storage{ config: config, rootKeys: mgostorage.NewRootKeys(5), }, nil }
go
func New(config Config) (ExpirableStorage, error) { if err := config.Validate(); err != nil { return nil, errors.Annotate(err, "validating config") } return &storage{ config: config, rootKeys: mgostorage.NewRootKeys(5), }, nil }
[ "func", "New", "(", "config", "Config", ")", "(", "ExpirableStorage", ",", "error", ")", "{", "if", "err", ":=", "config", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\...
// New returns an implementation of bakery.Storage // that stores all items in MongoDB with an expiry // time.
[ "New", "returns", "an", "implementation", "of", "bakery", ".", "Storage", "that", "stores", "all", "items", "in", "MongoDB", "with", "an", "expiry", "time", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/bakerystorage/interface.go#L56-L64
4,994
juju/juju
worker/peergrouper/desired.go
getLogMessage
func (info *peerGroupInfo) getLogMessage() string { lines := []string{ fmt.Sprintf("calculating desired peer group\ndesired voting members: (maxId: %d)", info.maxMemberId), } template := "\n %#v: rs_id=%d, rs_addr=%s" ids := make([]string, 0, len(info.recognised)) for id := range info.recognised { ids = append(ids, id) } sortAsInts(ids) for _, id := range ids { rm := info.recognised[id] lines = append(lines, fmt.Sprintf(template, info.machines[id], rm.Id, rm.Address)) } if len(info.extra) > 0 { lines = append(lines, "\nother members:") template := "\n rs_id=%d, rs_addr=%s, tags=%v, vote=%t" for _, em := range info.extra { vote := em.Votes != nil && *em.Votes > 0 lines = append(lines, fmt.Sprintf(template, em.Id, em.Address, em.Tags, vote)) } } return strings.Join(lines, "") }
go
func (info *peerGroupInfo) getLogMessage() string { lines := []string{ fmt.Sprintf("calculating desired peer group\ndesired voting members: (maxId: %d)", info.maxMemberId), } template := "\n %#v: rs_id=%d, rs_addr=%s" ids := make([]string, 0, len(info.recognised)) for id := range info.recognised { ids = append(ids, id) } sortAsInts(ids) for _, id := range ids { rm := info.recognised[id] lines = append(lines, fmt.Sprintf(template, info.machines[id], rm.Id, rm.Address)) } if len(info.extra) > 0 { lines = append(lines, "\nother members:") template := "\n rs_id=%d, rs_addr=%s, tags=%v, vote=%t" for _, em := range info.extra { vote := em.Votes != nil && *em.Votes > 0 lines = append(lines, fmt.Sprintf(template, em.Id, em.Address, em.Tags, vote)) } } return strings.Join(lines, "") }
[ "func", "(", "info", "*", "peerGroupInfo", ")", "getLogMessage", "(", ")", "string", "{", "lines", ":=", "[", "]", "string", "{", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "info", ".", "maxMemberId", ")", ",", "}", "\n\n", "template", ":=",...
// getLogMessage generates a nicely formatted log message from the known peer // group information.
[ "getLogMessage", "generates", "a", "nicely", "formatted", "log", "message", "from", "the", "known", "peer", "group", "information", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/peergrouper/desired.go#L132-L159
4,995
juju/juju
worker/peergrouper/desired.go
initNewReplicaSet
func (p *peerGroupChanges) initNewReplicaSet() map[string]*replicaset.Member { rs := make(map[string]*replicaset.Member, len(p.info.recognised)) for id := range p.info.recognised { // Local-scoped variable required here, // or the same pointer to the loop variable is used each time. m := p.info.recognised[id] rs[id] = &m } return rs }
go
func (p *peerGroupChanges) initNewReplicaSet() map[string]*replicaset.Member { rs := make(map[string]*replicaset.Member, len(p.info.recognised)) for id := range p.info.recognised { // Local-scoped variable required here, // or the same pointer to the loop variable is used each time. m := p.info.recognised[id] rs[id] = &m } return rs }
[ "func", "(", "p", "*", "peerGroupChanges", ")", "initNewReplicaSet", "(", ")", "map", "[", "string", "]", "*", "replicaset", ".", "Member", "{", "rs", ":=", "make", "(", "map", "[", "string", "]", "*", "replicaset", ".", "Member", ",", "len", "(", "p...
// initNewReplicaSet creates a new machine ID indexed map of known replica-set // members to use as the basis for a newly calculated replica-set.
[ "initNewReplicaSet", "creates", "a", "new", "machine", "ID", "indexed", "map", "of", "known", "replica", "-", "set", "members", "to", "use", "as", "the", "basis", "for", "a", "newly", "calculated", "replica", "-", "set", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/peergrouper/desired.go#L163-L172
4,996
juju/juju
worker/peergrouper/desired.go
checkExtraMembers
func (p *peerGroupChanges) checkExtraMembers() error { // Note: (jam 2018-04-18) With the new "juju remove-machine --force" it is much easier to get into this situation // because an active controller that is in the replicaset would get removed while it still had voting rights. // Given that Juju is in control of the replicaset we don't really just 'accept' that some other machine has a vote. // *maybe* we could allow non-voting members that would be used by 3rd parties to provide a warm database backup. // But I think the right answer is probably to downgrade unknown members from voting. for _, member := range p.info.extra { if isVotingMember(&member) { return fmt.Errorf("voting non-machine member %v found in peer group", member) } } if len(p.info.extra) > 0 { p.desired.isChanged = true } return nil }
go
func (p *peerGroupChanges) checkExtraMembers() error { // Note: (jam 2018-04-18) With the new "juju remove-machine --force" it is much easier to get into this situation // because an active controller that is in the replicaset would get removed while it still had voting rights. // Given that Juju is in control of the replicaset we don't really just 'accept' that some other machine has a vote. // *maybe* we could allow non-voting members that would be used by 3rd parties to provide a warm database backup. // But I think the right answer is probably to downgrade unknown members from voting. for _, member := range p.info.extra { if isVotingMember(&member) { return fmt.Errorf("voting non-machine member %v found in peer group", member) } } if len(p.info.extra) > 0 { p.desired.isChanged = true } return nil }
[ "func", "(", "p", "*", "peerGroupChanges", ")", "checkExtraMembers", "(", ")", "error", "{", "// Note: (jam 2018-04-18) With the new \"juju remove-machine --force\" it is much easier to get into this situation", "// because an active controller that is in the replicaset would get removed whi...
// checkExtraMembers checks to see if any of the input members, identified as // not being associated with machines, is set as a voter in the peer group. // If any have, an error is returned. // The boolean indicates whether any extra members were present at all.
[ "checkExtraMembers", "checks", "to", "see", "if", "any", "of", "the", "input", "members", "identified", "as", "not", "being", "associated", "with", "machines", "is", "set", "as", "a", "voter", "in", "the", "peer", "group", ".", "If", "any", "have", "an", ...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/peergrouper/desired.go#L240-L255
4,997
juju/juju
worker/peergrouper/desired.go
reviewPeerGroupChanges
func (p *peerGroupChanges) reviewPeerGroupChanges() { currVoters := 0 for _, m := range p.desired.members { if isVotingMember(m) { currVoters += 1 } } keptVoters := currVoters - len(p.toRemoveVote) if keptVoters == 0 { // to keep no voters means to step down the primary without a replacement, which is not possible. // So restore the current primary. Once there is another member to work with after reconfiguring, we will then // be able to ask the current primary to step down, and then we can finally remove it. var tempToRemove []string for _, id := range p.toRemoveVote { isPrimary := isPrimaryMember(p.info, id) if !isPrimary { tempToRemove = append(tempToRemove, id) } else { logger.Debugf("asked to remove all voters, preserving primary voter %q", id) p.desired.stepDownPrimary = false } } p.toRemoveVote = tempToRemove } newCount := keptVoters + len(p.toAddVote) if (newCount)%2 == 1 { logger.Debugf("number of voters is odd") // if this is true we will create an odd number of voters return } if len(p.toAddVote) > 0 { last := p.toAddVote[len(p.toAddVote)-1] logger.Debugf("number of voters would be even, not adding %q to maintain odd", last) p.toAddVote = p.toAddVote[:len(p.toAddVote)-1] return } // we must remove an extra peer // make sure we don't pick the primary to be removed. for i, id := range p.toKeepVoting { if !isPrimaryMember(p.info, id) { p.toRemoveVote = append(p.toRemoveVote, id) logger.Debugf("removing vote from %q to maintain odd number of voters", id) if i == len(p.toKeepVoting)-1 { p.toKeepVoting = p.toKeepVoting[:i] } else { p.toKeepVoting = append(p.toKeepVoting[:i], p.toKeepVoting[i+1:]...) } break } } }
go
func (p *peerGroupChanges) reviewPeerGroupChanges() { currVoters := 0 for _, m := range p.desired.members { if isVotingMember(m) { currVoters += 1 } } keptVoters := currVoters - len(p.toRemoveVote) if keptVoters == 0 { // to keep no voters means to step down the primary without a replacement, which is not possible. // So restore the current primary. Once there is another member to work with after reconfiguring, we will then // be able to ask the current primary to step down, and then we can finally remove it. var tempToRemove []string for _, id := range p.toRemoveVote { isPrimary := isPrimaryMember(p.info, id) if !isPrimary { tempToRemove = append(tempToRemove, id) } else { logger.Debugf("asked to remove all voters, preserving primary voter %q", id) p.desired.stepDownPrimary = false } } p.toRemoveVote = tempToRemove } newCount := keptVoters + len(p.toAddVote) if (newCount)%2 == 1 { logger.Debugf("number of voters is odd") // if this is true we will create an odd number of voters return } if len(p.toAddVote) > 0 { last := p.toAddVote[len(p.toAddVote)-1] logger.Debugf("number of voters would be even, not adding %q to maintain odd", last) p.toAddVote = p.toAddVote[:len(p.toAddVote)-1] return } // we must remove an extra peer // make sure we don't pick the primary to be removed. for i, id := range p.toKeepVoting { if !isPrimaryMember(p.info, id) { p.toRemoveVote = append(p.toRemoveVote, id) logger.Debugf("removing vote from %q to maintain odd number of voters", id) if i == len(p.toKeepVoting)-1 { p.toKeepVoting = p.toKeepVoting[:i] } else { p.toKeepVoting = append(p.toKeepVoting[:i], p.toKeepVoting[i+1:]...) } break } } }
[ "func", "(", "p", "*", "peerGroupChanges", ")", "reviewPeerGroupChanges", "(", ")", "{", "currVoters", ":=", "0", "\n", "for", "_", ",", "m", ":=", "range", "p", ".", "desired", ".", "members", "{", "if", "isVotingMember", "(", "m", ")", "{", "currVote...
// reviewPeerGroupChanges adds some extra logic after creating // possiblePeerGroupChanges to safely add or remove machines, keeping the // correct odd number of voters peer structure, and preventing the primary from // demotion.
[ "reviewPeerGroupChanges", "adds", "some", "extra", "logic", "after", "creating", "possiblePeerGroupChanges", "to", "safely", "add", "or", "remove", "machines", "keeping", "the", "correct", "odd", "number", "of", "voters", "peer", "structure", "and", "preventing", "t...
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/peergrouper/desired.go#L346-L396
4,998
juju/juju
worker/peergrouper/desired.go
adjustVotes
func (p *peerGroupChanges) adjustVotes() { setVoting := func(memberIds []string, voting bool) { for _, id := range memberIds { setMemberVoting(p.desired.members[id], voting) p.desired.machineVoting[id] = voting } } if len(p.toAddVote) > 0 || len(p.toRemoveVote) > 0 || len(p.toKeepCreateNonVotingMember) > 0 { p.desired.isChanged = true } setVoting(p.toAddVote, true) setVoting(p.toRemoveVote, false) setVoting(p.toKeepCreateNonVotingMember, false) }
go
func (p *peerGroupChanges) adjustVotes() { setVoting := func(memberIds []string, voting bool) { for _, id := range memberIds { setMemberVoting(p.desired.members[id], voting) p.desired.machineVoting[id] = voting } } if len(p.toAddVote) > 0 || len(p.toRemoveVote) > 0 || len(p.toKeepCreateNonVotingMember) > 0 { p.desired.isChanged = true } setVoting(p.toAddVote, true) setVoting(p.toRemoveVote, false) setVoting(p.toKeepCreateNonVotingMember, false) }
[ "func", "(", "p", "*", "peerGroupChanges", ")", "adjustVotes", "(", ")", "{", "setVoting", ":=", "func", "(", "memberIds", "[", "]", "string", ",", "voting", "bool", ")", "{", "for", "_", ",", "id", ":=", "range", "memberIds", "{", "setMemberVoting", "...
// adjustVotes removes and adds votes to the members via setVoting.
[ "adjustVotes", "removes", "and", "adds", "votes", "to", "the", "members", "via", "setVoting", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/peergrouper/desired.go#L420-L436
4,999
juju/juju
worker/peergrouper/desired.go
createNonVotingMember
func (p *peerGroupChanges) createNonVotingMember() { for _, id := range p.toKeepCreateNonVotingMember { logger.Debugf("create member with id %q", id) p.info.maxMemberId++ member := &replicaset.Member{ Tags: map[string]string{ jujuMachineKey: id, }, Id: p.info.maxMemberId, } setMemberVoting(member, false) p.desired.members[id] = member } for _, id := range p.toKeepNonVoting { if p.desired.members[id] != nil { continue } logger.Debugf("create member with id %q", id) p.info.maxMemberId++ member := &replicaset.Member{ Tags: map[string]string{ jujuMachineKey: id, }, Id: p.info.maxMemberId, } setMemberVoting(member, false) p.desired.members[id] = member } }
go
func (p *peerGroupChanges) createNonVotingMember() { for _, id := range p.toKeepCreateNonVotingMember { logger.Debugf("create member with id %q", id) p.info.maxMemberId++ member := &replicaset.Member{ Tags: map[string]string{ jujuMachineKey: id, }, Id: p.info.maxMemberId, } setMemberVoting(member, false) p.desired.members[id] = member } for _, id := range p.toKeepNonVoting { if p.desired.members[id] != nil { continue } logger.Debugf("create member with id %q", id) p.info.maxMemberId++ member := &replicaset.Member{ Tags: map[string]string{ jujuMachineKey: id, }, Id: p.info.maxMemberId, } setMemberVoting(member, false) p.desired.members[id] = member } }
[ "func", "(", "p", "*", "peerGroupChanges", ")", "createNonVotingMember", "(", ")", "{", "for", "_", ",", "id", ":=", "range", "p", ".", "toKeepCreateNonVotingMember", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "id", ")", "\n", "p", ".", "info"...
// createMembers from a list of member IDs, instantiate a new replica-set // member and add it to members map with the given ID.
[ "createMembers", "from", "a", "list", "of", "member", "IDs", "instantiate", "a", "new", "replica", "-", "set", "member", "and", "add", "it", "to", "members", "map", "with", "the", "given", "ID", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/peergrouper/desired.go#L440-L468