id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
3,700
juju/juju
apiserver/facades/controller/caasunitprovisioner/provisioner.go
ApplicationsScale
func (f *Facade) ApplicationsScale(args params.Entities) (params.IntResults, error) { results := params.IntResults{ Results: make([]params.IntResult, len(args.Entities)), } for i, arg := range args.Entities { scale, err := f.applicationScale(arg.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } results.Results[i].Result = scale } logger.Debugf("provisioning info result: %#v", results) return results, nil }
go
func (f *Facade) ApplicationsScale(args params.Entities) (params.IntResults, error) { results := params.IntResults{ Results: make([]params.IntResult, len(args.Entities)), } for i, arg := range args.Entities { scale, err := f.applicationScale(arg.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } results.Results[i].Result = scale } logger.Debugf("provisioning info result: %#v", results) return results, nil }
[ "func", "(", "f", "*", "Facade", ")", "ApplicationsScale", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "IntResults", ",", "error", ")", "{", "results", ":=", "params", ".", "IntResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "IntResult", ",", "len", "(", "args", ".", "Entities", ")", ")", ",", "}", "\n", "for", "i", ",", "arg", ":=", "range", "args", ".", "Entities", "{", "scale", ",", "err", ":=", "f", ".", "applicationScale", "(", "arg", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "results", ".", "Results", "[", "i", "]", ".", "Result", "=", "scale", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "results", ")", "\n", "return", "results", ",", "nil", "\n", "}" ]
// ApplicationsScale returns the scaling info for specified applications in this model.
[ "ApplicationsScale", "returns", "the", "scaling", "info", "for", "specified", "applications", "in", "this", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/caasunitprovisioner/provisioner.go#L194-L208
3,701
juju/juju
apiserver/facades/controller/caasunitprovisioner/provisioner.go
ProvisioningInfo
func (f *Facade) ProvisioningInfo(args params.Entities) (params.KubernetesProvisioningInfoResults, error) { model, err := f.state.Model() if err != nil { return params.KubernetesProvisioningInfoResults{}, errors.Trace(err) } results := params.KubernetesProvisioningInfoResults{ Results: make([]params.KubernetesProvisioningInfoResult, len(args.Entities)), } for i, arg := range args.Entities { info, err := f.provisioningInfo(model, arg.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } results.Results[i].Result = info } return results, nil }
go
func (f *Facade) ProvisioningInfo(args params.Entities) (params.KubernetesProvisioningInfoResults, error) { model, err := f.state.Model() if err != nil { return params.KubernetesProvisioningInfoResults{}, errors.Trace(err) } results := params.KubernetesProvisioningInfoResults{ Results: make([]params.KubernetesProvisioningInfoResult, len(args.Entities)), } for i, arg := range args.Entities { info, err := f.provisioningInfo(model, arg.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } results.Results[i].Result = info } return results, nil }
[ "func", "(", "f", "*", "Facade", ")", "ProvisioningInfo", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "KubernetesProvisioningInfoResults", ",", "error", ")", "{", "model", ",", "err", ":=", "f", ".", "state", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "KubernetesProvisioningInfoResults", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "results", ":=", "params", ".", "KubernetesProvisioningInfoResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "KubernetesProvisioningInfoResult", ",", "len", "(", "args", ".", "Entities", ")", ")", ",", "}", "\n", "for", "i", ",", "arg", ":=", "range", "args", ".", "Entities", "{", "info", ",", "err", ":=", "f", ".", "provisioningInfo", "(", "model", ",", "arg", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "results", ".", "Results", "[", "i", "]", ".", "Result", "=", "info", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// ProvisioningInfo returns the provisioning info for specified applications in this model.
[ "ProvisioningInfo", "returns", "the", "provisioning", "info", "for", "specified", "applications", "in", "this", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/caasunitprovisioner/provisioner.go#L223-L240
3,702
juju/juju
apiserver/facades/controller/caasunitprovisioner/provisioner.go
applicationFilesystemParams
func (f *Facade) applicationFilesystemParams( app Application, controllerConfig controller.Config, modelConfig *config.Config, ) ([]params.KubernetesFilesystemParams, error) { storage, err := app.StorageConstraints() if err != nil { return nil, errors.Trace(err) } ch, _, err := app.Charm() if err != nil { return nil, errors.Trace(err) } var allFilesystemParams []params.KubernetesFilesystemParams for name, cons := range storage { fsParams, err := filesystemParams( app, cons, name, controllerConfig.ControllerUUID(), modelConfig, f.storagePoolManager, f.registry, ) if err != nil { return nil, errors.Annotatef(err, "getting filesystem %q parameters", name) } for i := 0; i < int(cons.Count); i++ { charmStorage := ch.Meta().Storage[name] id := fmt.Sprintf("%s/%v", name, i) tag := names.NewStorageTag(id) location, err := state.FilesystemMountPoint(charmStorage, tag, "kubernetes") if err != nil { return nil, errors.Trace(err) } filesystemAttachmentParams := params.KubernetesFilesystemAttachmentParams{ Provider: fsParams.Provider, MountPoint: location, ReadOnly: charmStorage.ReadOnly, } fsParams.Attachment = &filesystemAttachmentParams allFilesystemParams = append(allFilesystemParams, fsParams) } } return allFilesystemParams, nil }
go
func (f *Facade) applicationFilesystemParams( app Application, controllerConfig controller.Config, modelConfig *config.Config, ) ([]params.KubernetesFilesystemParams, error) { storage, err := app.StorageConstraints() if err != nil { return nil, errors.Trace(err) } ch, _, err := app.Charm() if err != nil { return nil, errors.Trace(err) } var allFilesystemParams []params.KubernetesFilesystemParams for name, cons := range storage { fsParams, err := filesystemParams( app, cons, name, controllerConfig.ControllerUUID(), modelConfig, f.storagePoolManager, f.registry, ) if err != nil { return nil, errors.Annotatef(err, "getting filesystem %q parameters", name) } for i := 0; i < int(cons.Count); i++ { charmStorage := ch.Meta().Storage[name] id := fmt.Sprintf("%s/%v", name, i) tag := names.NewStorageTag(id) location, err := state.FilesystemMountPoint(charmStorage, tag, "kubernetes") if err != nil { return nil, errors.Trace(err) } filesystemAttachmentParams := params.KubernetesFilesystemAttachmentParams{ Provider: fsParams.Provider, MountPoint: location, ReadOnly: charmStorage.ReadOnly, } fsParams.Attachment = &filesystemAttachmentParams allFilesystemParams = append(allFilesystemParams, fsParams) } } return allFilesystemParams, nil }
[ "func", "(", "f", "*", "Facade", ")", "applicationFilesystemParams", "(", "app", "Application", ",", "controllerConfig", "controller", ".", "Config", ",", "modelConfig", "*", "config", ".", "Config", ",", ")", "(", "[", "]", "params", ".", "KubernetesFilesystemParams", ",", "error", ")", "{", "storage", ",", "err", ":=", "app", ".", "StorageConstraints", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "ch", ",", "_", ",", "err", ":=", "app", ".", "Charm", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "var", "allFilesystemParams", "[", "]", "params", ".", "KubernetesFilesystemParams", "\n", "for", "name", ",", "cons", ":=", "range", "storage", "{", "fsParams", ",", "err", ":=", "filesystemParams", "(", "app", ",", "cons", ",", "name", ",", "controllerConfig", ".", "ControllerUUID", "(", ")", ",", "modelConfig", ",", "f", ".", "storagePoolManager", ",", "f", ".", "registry", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "int", "(", "cons", ".", "Count", ")", ";", "i", "++", "{", "charmStorage", ":=", "ch", ".", "Meta", "(", ")", ".", "Storage", "[", "name", "]", "\n", "id", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ",", "i", ")", "\n", "tag", ":=", "names", ".", "NewStorageTag", "(", "id", ")", "\n", "location", ",", "err", ":=", "state", ".", "FilesystemMountPoint", "(", "charmStorage", ",", "tag", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "filesystemAttachmentParams", ":=", "params", ".", "KubernetesFilesystemAttachmentParams", "{", "Provider", ":", "fsParams", ".", "Provider", ",", "MountPoint", ":", "location", ",", "ReadOnly", ":", "charmStorage", ".", "ReadOnly", ",", "}", "\n", "fsParams", ".", "Attachment", "=", "&", "filesystemAttachmentParams", "\n", "allFilesystemParams", "=", "append", "(", "allFilesystemParams", ",", "fsParams", ")", "\n", "}", "\n", "}", "\n", "return", "allFilesystemParams", ",", "nil", "\n", "}" ]
// applicationFilesystemParams retrieves FilesystemParams for the filesystems // that should be provisioned with, and attached to, pods of the application.
[ "applicationFilesystemParams", "retrieves", "FilesystemParams", "for", "the", "filesystems", "that", "should", "be", "provisioned", "with", "and", "attached", "to", "pods", "of", "the", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/caasunitprovisioner/provisioner.go#L350-L394
3,703
juju/juju
apiserver/facades/controller/caasunitprovisioner/provisioner.go
ApplicationsConfig
func (f *Facade) ApplicationsConfig(args params.Entities) (params.ApplicationGetConfigResults, error) { results := params.ApplicationGetConfigResults{ Results: make([]params.ConfigResult, len(args.Entities)), } for i, arg := range args.Entities { result, err := f.getApplicationConfig(arg.Tag) results.Results[i].Config = result results.Results[i].Error = common.ServerError(err) } return results, nil }
go
func (f *Facade) ApplicationsConfig(args params.Entities) (params.ApplicationGetConfigResults, error) { results := params.ApplicationGetConfigResults{ Results: make([]params.ConfigResult, len(args.Entities)), } for i, arg := range args.Entities { result, err := f.getApplicationConfig(arg.Tag) results.Results[i].Config = result results.Results[i].Error = common.ServerError(err) } return results, nil }
[ "func", "(", "f", "*", "Facade", ")", "ApplicationsConfig", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "ApplicationGetConfigResults", ",", "error", ")", "{", "results", ":=", "params", ".", "ApplicationGetConfigResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "ConfigResult", ",", "len", "(", "args", ".", "Entities", ")", ")", ",", "}", "\n", "for", "i", ",", "arg", ":=", "range", "args", ".", "Entities", "{", "result", ",", "err", ":=", "f", ".", "getApplicationConfig", "(", "arg", ".", "Tag", ")", "\n", "results", ".", "Results", "[", "i", "]", ".", "Config", "=", "result", "\n", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// ApplicationsConfig returns the config for the specified applications.
[ "ApplicationsConfig", "returns", "the", "config", "for", "the", "specified", "applications", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/caasunitprovisioner/provisioner.go#L414-L424
3,704
juju/juju
apiserver/facades/controller/caasunitprovisioner/provisioner.go
UpdateApplicationsUnits
func (a *Facade) UpdateApplicationsUnits(args params.UpdateApplicationUnitArgs) (params.ErrorResults, error) { result := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Args)), } if len(args.Args) == 0 { return result, nil } for i, appUpdate := range args.Args { appTag, err := names.ParseApplicationTag(appUpdate.ApplicationTag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } app, err := a.state.Application(appTag.Id()) if err != nil { result.Results[i].Error = common.ServerError(err) continue } appStatus := appUpdate.Status if appStatus.Status != "" && appStatus.Status != status.Unknown { now := a.clock.Now() err = app.SetStatus(status.StatusInfo{ Status: appStatus.Status, Message: appStatus.Info, Data: appStatus.Data, Since: &now, }) if err != nil { result.Results[i].Error = common.ServerError(err) continue } } err = a.updateUnitsFromCloud(app, appUpdate.Scale, appUpdate.Units) if err != nil { // Mask any not found errors as the worker (caller) treats them specially // and they are not relevant here. result.Results[i].Error = common.ServerError(errors.Mask(err)) } } return result, nil }
go
func (a *Facade) UpdateApplicationsUnits(args params.UpdateApplicationUnitArgs) (params.ErrorResults, error) { result := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Args)), } if len(args.Args) == 0 { return result, nil } for i, appUpdate := range args.Args { appTag, err := names.ParseApplicationTag(appUpdate.ApplicationTag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } app, err := a.state.Application(appTag.Id()) if err != nil { result.Results[i].Error = common.ServerError(err) continue } appStatus := appUpdate.Status if appStatus.Status != "" && appStatus.Status != status.Unknown { now := a.clock.Now() err = app.SetStatus(status.StatusInfo{ Status: appStatus.Status, Message: appStatus.Info, Data: appStatus.Data, Since: &now, }) if err != nil { result.Results[i].Error = common.ServerError(err) continue } } err = a.updateUnitsFromCloud(app, appUpdate.Scale, appUpdate.Units) if err != nil { // Mask any not found errors as the worker (caller) treats them specially // and they are not relevant here. result.Results[i].Error = common.ServerError(errors.Mask(err)) } } return result, nil }
[ "func", "(", "a", "*", "Facade", ")", "UpdateApplicationsUnits", "(", "args", "params", ".", "UpdateApplicationUnitArgs", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "result", ":=", "params", ".", "ErrorResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "args", ".", "Args", ")", ")", ",", "}", "\n", "if", "len", "(", "args", ".", "Args", ")", "==", "0", "{", "return", "result", ",", "nil", "\n", "}", "\n", "for", "i", ",", "appUpdate", ":=", "range", "args", ".", "Args", "{", "appTag", ",", "err", ":=", "names", ".", "ParseApplicationTag", "(", "appUpdate", ".", "ApplicationTag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "app", ",", "err", ":=", "a", ".", "state", ".", "Application", "(", "appTag", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "appStatus", ":=", "appUpdate", ".", "Status", "\n", "if", "appStatus", ".", "Status", "!=", "\"", "\"", "&&", "appStatus", ".", "Status", "!=", "status", ".", "Unknown", "{", "now", ":=", "a", ".", "clock", ".", "Now", "(", ")", "\n", "err", "=", "app", ".", "SetStatus", "(", "status", ".", "StatusInfo", "{", "Status", ":", "appStatus", ".", "Status", ",", "Message", ":", "appStatus", ".", "Info", ",", "Data", ":", "appStatus", ".", "Data", ",", "Since", ":", "&", "now", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "}", "\n", "err", "=", "a", ".", "updateUnitsFromCloud", "(", "app", ",", "appUpdate", ".", "Scale", ",", "appUpdate", ".", "Units", ")", "\n", "if", "err", "!=", "nil", "{", "// Mask any not found errors as the worker (caller) treats them specially", "// and they are not relevant here.", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "errors", ".", "Mask", "(", "err", ")", ")", "\n", "}", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// UpdateApplicationsUnits updates the Juju data model to reflect the given // units of the specified application.
[ "UpdateApplicationsUnits", "updates", "the", "Juju", "data", "model", "to", "reflect", "the", "given", "units", "of", "the", "specified", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/caasunitprovisioner/provisioner.go#L440-L480
3,705
juju/juju
apiserver/facades/controller/caasunitprovisioner/provisioner.go
updateStatus
func (a *Facade) updateStatus(params params.ApplicationUnitParams) ( agentStatus *status.StatusInfo, cloudContainerStatus *status.StatusInfo, ) { var containerStatus status.Status switch status.Status(params.Status) { case status.Unknown: // The container runtime can spam us with unimportant // status updates, so ignore any irrelevant ones. return nil, nil case status.Allocating: // The container runtime has decided to restart the pod. agentStatus = &status.StatusInfo{ Status: status.Allocating, Message: params.Info, } containerStatus = status.Waiting case status.Running: // A pod has finished starting so the workload is now active. agentStatus = &status.StatusInfo{ Status: status.Idle, } containerStatus = status.Running case status.Error: agentStatus = &status.StatusInfo{ Status: status.Error, Message: params.Info, Data: params.Data, } containerStatus = status.Error case status.Blocked: containerStatus = status.Blocked agentStatus = &status.StatusInfo{ Status: status.Idle, } } cloudContainerStatus = &status.StatusInfo{ Status: containerStatus, Message: params.Info, Data: params.Data, } return agentStatus, cloudContainerStatus }
go
func (a *Facade) updateStatus(params params.ApplicationUnitParams) ( agentStatus *status.StatusInfo, cloudContainerStatus *status.StatusInfo, ) { var containerStatus status.Status switch status.Status(params.Status) { case status.Unknown: // The container runtime can spam us with unimportant // status updates, so ignore any irrelevant ones. return nil, nil case status.Allocating: // The container runtime has decided to restart the pod. agentStatus = &status.StatusInfo{ Status: status.Allocating, Message: params.Info, } containerStatus = status.Waiting case status.Running: // A pod has finished starting so the workload is now active. agentStatus = &status.StatusInfo{ Status: status.Idle, } containerStatus = status.Running case status.Error: agentStatus = &status.StatusInfo{ Status: status.Error, Message: params.Info, Data: params.Data, } containerStatus = status.Error case status.Blocked: containerStatus = status.Blocked agentStatus = &status.StatusInfo{ Status: status.Idle, } } cloudContainerStatus = &status.StatusInfo{ Status: containerStatus, Message: params.Info, Data: params.Data, } return agentStatus, cloudContainerStatus }
[ "func", "(", "a", "*", "Facade", ")", "updateStatus", "(", "params", "params", ".", "ApplicationUnitParams", ")", "(", "agentStatus", "*", "status", ".", "StatusInfo", ",", "cloudContainerStatus", "*", "status", ".", "StatusInfo", ",", ")", "{", "var", "containerStatus", "status", ".", "Status", "\n", "switch", "status", ".", "Status", "(", "params", ".", "Status", ")", "{", "case", "status", ".", "Unknown", ":", "// The container runtime can spam us with unimportant", "// status updates, so ignore any irrelevant ones.", "return", "nil", ",", "nil", "\n", "case", "status", ".", "Allocating", ":", "// The container runtime has decided to restart the pod.", "agentStatus", "=", "&", "status", ".", "StatusInfo", "{", "Status", ":", "status", ".", "Allocating", ",", "Message", ":", "params", ".", "Info", ",", "}", "\n", "containerStatus", "=", "status", ".", "Waiting", "\n", "case", "status", ".", "Running", ":", "// A pod has finished starting so the workload is now active.", "agentStatus", "=", "&", "status", ".", "StatusInfo", "{", "Status", ":", "status", ".", "Idle", ",", "}", "\n", "containerStatus", "=", "status", ".", "Running", "\n", "case", "status", ".", "Error", ":", "agentStatus", "=", "&", "status", ".", "StatusInfo", "{", "Status", ":", "status", ".", "Error", ",", "Message", ":", "params", ".", "Info", ",", "Data", ":", "params", ".", "Data", ",", "}", "\n", "containerStatus", "=", "status", ".", "Error", "\n", "case", "status", ".", "Blocked", ":", "containerStatus", "=", "status", ".", "Blocked", "\n", "agentStatus", "=", "&", "status", ".", "StatusInfo", "{", "Status", ":", "status", ".", "Idle", ",", "}", "\n", "}", "\n", "cloudContainerStatus", "=", "&", "status", ".", "StatusInfo", "{", "Status", ":", "containerStatus", ",", "Message", ":", "params", ".", "Info", ",", "Data", ":", "params", ".", "Data", ",", "}", "\n", "return", "agentStatus", ",", "cloudContainerStatus", "\n", "}" ]
// updateStatus constructs the agent and cloud container status values.
[ "updateStatus", "constructs", "the", "agent", "and", "cloud", "container", "status", "values", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/caasunitprovisioner/provisioner.go#L483-L525
3,706
juju/juju
apiserver/facades/controller/caasunitprovisioner/provisioner.go
UpdateApplicationsService
func (a *Facade) UpdateApplicationsService(args params.UpdateApplicationServiceArgs) (params.ErrorResults, error) { result := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Args)), } if len(args.Args) == 0 { return result, nil } for i, appUpdate := range args.Args { appTag, err := names.ParseApplicationTag(appUpdate.ApplicationTag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } app, err := a.state.Application(appTag.Id()) if err != nil { result.Results[i].Error = common.ServerError(err) continue } if err := app.UpdateCloudService(appUpdate.ProviderId, params.NetworkAddresses(appUpdate.Addresses...)); err != nil { result.Results[i].Error = common.ServerError(err) } } return result, nil }
go
func (a *Facade) UpdateApplicationsService(args params.UpdateApplicationServiceArgs) (params.ErrorResults, error) { result := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Args)), } if len(args.Args) == 0 { return result, nil } for i, appUpdate := range args.Args { appTag, err := names.ParseApplicationTag(appUpdate.ApplicationTag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } app, err := a.state.Application(appTag.Id()) if err != nil { result.Results[i].Error = common.ServerError(err) continue } if err := app.UpdateCloudService(appUpdate.ProviderId, params.NetworkAddresses(appUpdate.Addresses...)); err != nil { result.Results[i].Error = common.ServerError(err) } } return result, nil }
[ "func", "(", "a", "*", "Facade", ")", "UpdateApplicationsService", "(", "args", "params", ".", "UpdateApplicationServiceArgs", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "result", ":=", "params", ".", "ErrorResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "args", ".", "Args", ")", ")", ",", "}", "\n", "if", "len", "(", "args", ".", "Args", ")", "==", "0", "{", "return", "result", ",", "nil", "\n", "}", "\n", "for", "i", ",", "appUpdate", ":=", "range", "args", ".", "Args", "{", "appTag", ",", "err", ":=", "names", ".", "ParseApplicationTag", "(", "appUpdate", ".", "ApplicationTag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "app", ",", "err", ":=", "a", ".", "state", ".", "Application", "(", "appTag", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "err", ":=", "app", ".", "UpdateCloudService", "(", "appUpdate", ".", "ProviderId", ",", "params", ".", "NetworkAddresses", "(", "appUpdate", ".", "Addresses", "...", ")", ")", ";", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// UpdateApplicationsService updates the Juju data model to reflect the given // service details of the specified application.
[ "UpdateApplicationsService", "updates", "the", "Juju", "data", "model", "to", "reflect", "the", "given", "service", "details", "of", "the", "specified", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/caasunitprovisioner/provisioner.go#L1186-L1209
3,707
juju/juju
apiserver/facades/controller/caasunitprovisioner/provisioner.go
SetOperatorStatus
func (a *Facade) SetOperatorStatus(args params.SetStatus) (params.ErrorResults, error) { result := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Entities)), } for i, arg := range args.Entities { appTag, err := names.ParseApplicationTag(arg.Tag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } app, err := a.state.Application(appTag.Id()) if err != nil { result.Results[i].Error = common.ServerError(err) continue } now := a.clock.Now() s := status.StatusInfo{ Status: status.Status(arg.Status), Message: arg.Info, Data: arg.Data, Since: &now, } if err := app.SetOperatorStatus(s); err != nil { result.Results[i].Error = common.ServerError(err) } } return result, nil }
go
func (a *Facade) SetOperatorStatus(args params.SetStatus) (params.ErrorResults, error) { result := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Entities)), } for i, arg := range args.Entities { appTag, err := names.ParseApplicationTag(arg.Tag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } app, err := a.state.Application(appTag.Id()) if err != nil { result.Results[i].Error = common.ServerError(err) continue } now := a.clock.Now() s := status.StatusInfo{ Status: status.Status(arg.Status), Message: arg.Info, Data: arg.Data, Since: &now, } if err := app.SetOperatorStatus(s); err != nil { result.Results[i].Error = common.ServerError(err) } } return result, nil }
[ "func", "(", "a", "*", "Facade", ")", "SetOperatorStatus", "(", "args", "params", ".", "SetStatus", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "result", ":=", "params", ".", "ErrorResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "args", ".", "Entities", ")", ")", ",", "}", "\n", "for", "i", ",", "arg", ":=", "range", "args", ".", "Entities", "{", "appTag", ",", "err", ":=", "names", ".", "ParseApplicationTag", "(", "arg", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "app", ",", "err", ":=", "a", ".", "state", ".", "Application", "(", "appTag", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "now", ":=", "a", ".", "clock", ".", "Now", "(", ")", "\n", "s", ":=", "status", ".", "StatusInfo", "{", "Status", ":", "status", ".", "Status", "(", "arg", ".", "Status", ")", ",", "Message", ":", "arg", ".", "Info", ",", "Data", ":", "arg", ".", "Data", ",", "Since", ":", "&", "now", ",", "}", "\n", "if", "err", ":=", "app", ".", "SetOperatorStatus", "(", "s", ")", ";", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// SetOperatorStatus updates the operator status for each given application.
[ "SetOperatorStatus", "updates", "the", "operator", "status", "for", "each", "given", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/caasunitprovisioner/provisioner.go#L1212-L1239
3,708
juju/juju
component/all/payload.go
Component
func (c payloadsHookContext) Component(name string) (context.Component, error) { found, err := c.Context.Component(name) if err != nil { return nil, errors.Trace(err) } compCtx, ok := found.(context.Component) if !ok && found != nil { return nil, errors.Errorf("wrong component context type registered: %T", found) } return compCtx, nil }
go
func (c payloadsHookContext) Component(name string) (context.Component, error) { found, err := c.Context.Component(name) if err != nil { return nil, errors.Trace(err) } compCtx, ok := found.(context.Component) if !ok && found != nil { return nil, errors.Errorf("wrong component context type registered: %T", found) } return compCtx, nil }
[ "func", "(", "c", "payloadsHookContext", ")", "Component", "(", "name", "string", ")", "(", "context", ".", "Component", ",", "error", ")", "{", "found", ",", "err", ":=", "c", ".", "Context", ".", "Component", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "compCtx", ",", "ok", ":=", "found", ".", "(", "context", ".", "Component", ")", "\n", "if", "!", "ok", "&&", "found", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "found", ")", "\n", "}", "\n", "return", "compCtx", ",", "nil", "\n", "}" ]
// Component implements context.HookContext.
[ "Component", "implements", "context", ".", "HookContext", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/component/all/payload.go#L94-L104
3,709
juju/juju
core/migration/targetinfo.go
Validate
func (info *TargetInfo) Validate() error { if !names.IsValidModel(info.ControllerTag.Id()) { return errors.NotValidf("ControllerTag") } if len(info.Addrs) < 1 { return errors.NotValidf("empty Addrs") } for _, addr := range info.Addrs { _, err := network.ParseHostPort(addr) if err != nil { return errors.NotValidf("%q in Addrs", addr) } } if info.AuthTag.Id() == "" { return errors.NotValidf("empty AuthTag") } if info.Password == "" && len(info.Macaroons) == 0 { return errors.NotValidf("missing Password & Macaroons") } return nil }
go
func (info *TargetInfo) Validate() error { if !names.IsValidModel(info.ControllerTag.Id()) { return errors.NotValidf("ControllerTag") } if len(info.Addrs) < 1 { return errors.NotValidf("empty Addrs") } for _, addr := range info.Addrs { _, err := network.ParseHostPort(addr) if err != nil { return errors.NotValidf("%q in Addrs", addr) } } if info.AuthTag.Id() == "" { return errors.NotValidf("empty AuthTag") } if info.Password == "" && len(info.Macaroons) == 0 { return errors.NotValidf("missing Password & Macaroons") } return nil }
[ "func", "(", "info", "*", "TargetInfo", ")", "Validate", "(", ")", "error", "{", "if", "!", "names", ".", "IsValidModel", "(", "info", ".", "ControllerTag", ".", "Id", "(", ")", ")", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "len", "(", "info", ".", "Addrs", ")", "<", "1", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "for", "_", ",", "addr", ":=", "range", "info", ".", "Addrs", "{", "_", ",", "err", ":=", "network", ".", "ParseHostPort", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "addr", ")", "\n", "}", "\n", "}", "\n\n", "if", "info", ".", "AuthTag", ".", "Id", "(", ")", "==", "\"", "\"", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "info", ".", "Password", "==", "\"", "\"", "&&", "len", "(", "info", ".", "Macaroons", ")", "==", "0", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Validate returns an error if the TargetInfo contains bad data. Nil // is returned otherwise.
[ "Validate", "returns", "an", "error", "if", "the", "TargetInfo", "contains", "bad", "data", ".", "Nil", "is", "returned", "otherwise", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/migration/targetinfo.go#L50-L74
3,710
juju/juju
environs/imagemetadata/generate.go
IndexStoragePath
func IndexStoragePath() string { return path.Join(storage.BaseImagesPath, simplestreams.UnsignedIndex(currentStreamsVersion, IndexFileVersion)) }
go
func IndexStoragePath() string { return path.Join(storage.BaseImagesPath, simplestreams.UnsignedIndex(currentStreamsVersion, IndexFileVersion)) }
[ "func", "IndexStoragePath", "(", ")", "string", "{", "return", "path", ".", "Join", "(", "storage", ".", "BaseImagesPath", ",", "simplestreams", ".", "UnsignedIndex", "(", "currentStreamsVersion", ",", "IndexFileVersion", ")", ")", "\n", "}" ]
// IndexStoragePath returns the storage path for the image metadata index file.
[ "IndexStoragePath", "returns", "the", "storage", "path", "for", "the", "image", "metadata", "index", "file", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/imagemetadata/generate.go#L20-L22
3,711
juju/juju
environs/imagemetadata/generate.go
readMetadata
func readMetadata(metadataStore storage.Storage) ([]*ImageMetadata, error) { // Read any existing metadata so we can merge the new tools metadata with what's there. dataSource := storage.NewStorageSimpleStreamsDataSource("existing metadata", metadataStore, storage.BaseImagesPath, simplestreams.EXISTING_CLOUD_DATA, false) imageConstraint := NewImageConstraint(simplestreams.LookupParams{}) existingMetadata, _, err := Fetch([]simplestreams.DataSource{dataSource}, imageConstraint) if err != nil && !errors.IsNotFound(err) { return nil, err } return existingMetadata, nil }
go
func readMetadata(metadataStore storage.Storage) ([]*ImageMetadata, error) { // Read any existing metadata so we can merge the new tools metadata with what's there. dataSource := storage.NewStorageSimpleStreamsDataSource("existing metadata", metadataStore, storage.BaseImagesPath, simplestreams.EXISTING_CLOUD_DATA, false) imageConstraint := NewImageConstraint(simplestreams.LookupParams{}) existingMetadata, _, err := Fetch([]simplestreams.DataSource{dataSource}, imageConstraint) if err != nil && !errors.IsNotFound(err) { return nil, err } return existingMetadata, nil }
[ "func", "readMetadata", "(", "metadataStore", "storage", ".", "Storage", ")", "(", "[", "]", "*", "ImageMetadata", ",", "error", ")", "{", "// Read any existing metadata so we can merge the new tools metadata with what's there.", "dataSource", ":=", "storage", ".", "NewStorageSimpleStreamsDataSource", "(", "\"", "\"", ",", "metadataStore", ",", "storage", ".", "BaseImagesPath", ",", "simplestreams", ".", "EXISTING_CLOUD_DATA", ",", "false", ")", "\n", "imageConstraint", ":=", "NewImageConstraint", "(", "simplestreams", ".", "LookupParams", "{", "}", ")", "\n", "existingMetadata", ",", "_", ",", "err", ":=", "Fetch", "(", "[", "]", "simplestreams", ".", "DataSource", "{", "dataSource", "}", ",", "imageConstraint", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "existingMetadata", ",", "nil", "\n", "}" ]
// readMetadata reads the image metadata from metadataStore.
[ "readMetadata", "reads", "the", "image", "metadata", "from", "metadataStore", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/imagemetadata/generate.go#L47-L56
3,712
juju/juju
environs/imagemetadata/generate.go
mapKey
func mapKey(im *ImageMetadata) string { return fmt.Sprintf("%s-%s-%s-%s", im.productId(), im.RegionName, im.VirtType, im.Storage) }
go
func mapKey(im *ImageMetadata) string { return fmt.Sprintf("%s-%s-%s-%s", im.productId(), im.RegionName, im.VirtType, im.Storage) }
[ "func", "mapKey", "(", "im", "*", "ImageMetadata", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "im", ".", "productId", "(", ")", ",", "im", ".", "RegionName", ",", "im", ".", "VirtType", ",", "im", ".", "Storage", ")", "\n", "}" ]
// mapKey returns a key that uniquely identifies image metadata. // The metadata for different images may have similar values // for some parameters. This key ensures that truly distinct // metadata is not overwritten by closely related ones. // This key is similar to image metadata key built in state which combines // parameter values rather than using image id to ensure record uniqueness.
[ "mapKey", "returns", "a", "key", "that", "uniquely", "identifies", "image", "metadata", ".", "The", "metadata", "for", "different", "images", "may", "have", "similar", "values", "for", "some", "parameters", ".", "This", "key", "ensures", "that", "truly", "distinct", "metadata", "is", "not", "overwritten", "by", "closely", "related", "ones", ".", "This", "key", "is", "similar", "to", "image", "metadata", "key", "built", "in", "state", "which", "combines", "parameter", "values", "rather", "than", "using", "image", "id", "to", "ensure", "record", "uniqueness", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/imagemetadata/generate.go#L64-L66
3,713
juju/juju
environs/imagemetadata/generate.go
mergeMetadata
func mergeMetadata(seriesVersion string, cloudSpec *simplestreams.CloudSpec, newMetadata, existingMetadata []*ImageMetadata) ([]*ImageMetadata, []simplestreams.CloudSpec) { regions := make(map[string]bool) var allCloudSpecs = []simplestreams.CloudSpec{} // Each metadata item defines its own cloud specification. // However, when we combine metadata items in the file, we do not want to // repeat common cloud specifications in index definition. // Since region name and endpoint have 1:1 correspondence, // only one distinct cloud specification for each region // is being collected. addDistinctCloudSpec := func(im *ImageMetadata) { if _, ok := regions[im.RegionName]; !ok { regions[im.RegionName] = true aCloudSpec := simplestreams.CloudSpec{ Region: im.RegionName, Endpoint: im.Endpoint, } allCloudSpecs = append(allCloudSpecs, aCloudSpec) } } var toWrite = make([]*ImageMetadata, len(newMetadata)) imageIds := make(map[string]bool) for i, im := range newMetadata { newRecord := *im newRecord.Version = seriesVersion newRecord.RegionName = cloudSpec.Region newRecord.Endpoint = cloudSpec.Endpoint toWrite[i] = &newRecord imageIds[mapKey(&newRecord)] = true addDistinctCloudSpec(&newRecord) } for _, im := range existingMetadata { if _, ok := imageIds[mapKey(im)]; !ok { toWrite = append(toWrite, im) addDistinctCloudSpec(im) } } return toWrite, allCloudSpecs }
go
func mergeMetadata(seriesVersion string, cloudSpec *simplestreams.CloudSpec, newMetadata, existingMetadata []*ImageMetadata) ([]*ImageMetadata, []simplestreams.CloudSpec) { regions := make(map[string]bool) var allCloudSpecs = []simplestreams.CloudSpec{} // Each metadata item defines its own cloud specification. // However, when we combine metadata items in the file, we do not want to // repeat common cloud specifications in index definition. // Since region name and endpoint have 1:1 correspondence, // only one distinct cloud specification for each region // is being collected. addDistinctCloudSpec := func(im *ImageMetadata) { if _, ok := regions[im.RegionName]; !ok { regions[im.RegionName] = true aCloudSpec := simplestreams.CloudSpec{ Region: im.RegionName, Endpoint: im.Endpoint, } allCloudSpecs = append(allCloudSpecs, aCloudSpec) } } var toWrite = make([]*ImageMetadata, len(newMetadata)) imageIds := make(map[string]bool) for i, im := range newMetadata { newRecord := *im newRecord.Version = seriesVersion newRecord.RegionName = cloudSpec.Region newRecord.Endpoint = cloudSpec.Endpoint toWrite[i] = &newRecord imageIds[mapKey(&newRecord)] = true addDistinctCloudSpec(&newRecord) } for _, im := range existingMetadata { if _, ok := imageIds[mapKey(im)]; !ok { toWrite = append(toWrite, im) addDistinctCloudSpec(im) } } return toWrite, allCloudSpecs }
[ "func", "mergeMetadata", "(", "seriesVersion", "string", ",", "cloudSpec", "*", "simplestreams", ".", "CloudSpec", ",", "newMetadata", ",", "existingMetadata", "[", "]", "*", "ImageMetadata", ")", "(", "[", "]", "*", "ImageMetadata", ",", "[", "]", "simplestreams", ".", "CloudSpec", ")", "{", "regions", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "var", "allCloudSpecs", "=", "[", "]", "simplestreams", ".", "CloudSpec", "{", "}", "\n", "// Each metadata item defines its own cloud specification.", "// However, when we combine metadata items in the file, we do not want to", "// repeat common cloud specifications in index definition.", "// Since region name and endpoint have 1:1 correspondence,", "// only one distinct cloud specification for each region", "// is being collected.", "addDistinctCloudSpec", ":=", "func", "(", "im", "*", "ImageMetadata", ")", "{", "if", "_", ",", "ok", ":=", "regions", "[", "im", ".", "RegionName", "]", ";", "!", "ok", "{", "regions", "[", "im", ".", "RegionName", "]", "=", "true", "\n", "aCloudSpec", ":=", "simplestreams", ".", "CloudSpec", "{", "Region", ":", "im", ".", "RegionName", ",", "Endpoint", ":", "im", ".", "Endpoint", ",", "}", "\n", "allCloudSpecs", "=", "append", "(", "allCloudSpecs", ",", "aCloudSpec", ")", "\n", "}", "\n", "}", "\n\n", "var", "toWrite", "=", "make", "(", "[", "]", "*", "ImageMetadata", ",", "len", "(", "newMetadata", ")", ")", "\n", "imageIds", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "i", ",", "im", ":=", "range", "newMetadata", "{", "newRecord", ":=", "*", "im", "\n", "newRecord", ".", "Version", "=", "seriesVersion", "\n", "newRecord", ".", "RegionName", "=", "cloudSpec", ".", "Region", "\n", "newRecord", ".", "Endpoint", "=", "cloudSpec", ".", "Endpoint", "\n", "toWrite", "[", "i", "]", "=", "&", "newRecord", "\n", "imageIds", "[", "mapKey", "(", "&", "newRecord", ")", "]", "=", "true", "\n", "addDistinctCloudSpec", "(", "&", "newRecord", ")", "\n", "}", "\n", "for", "_", ",", "im", ":=", "range", "existingMetadata", "{", "if", "_", ",", "ok", ":=", "imageIds", "[", "mapKey", "(", "im", ")", "]", ";", "!", "ok", "{", "toWrite", "=", "append", "(", "toWrite", ",", "im", ")", "\n", "addDistinctCloudSpec", "(", "im", ")", "\n", "}", "\n", "}", "\n", "return", "toWrite", ",", "allCloudSpecs", "\n", "}" ]
// mergeMetadata merges the newMetadata into existingMetadata, overwriting existing matching image records.
[ "mergeMetadata", "merges", "the", "newMetadata", "into", "existingMetadata", "overwriting", "existing", "matching", "image", "records", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/imagemetadata/generate.go#L69-L109
3,714
juju/juju
environs/imagemetadata/generate.go
writeMetadata
func writeMetadata(metadata []*ImageMetadata, cloudSpec []simplestreams.CloudSpec, metadataStore storage.Storage) error { // TODO(perrito666) 2016-05-02 lp:1558657 index, products, err := MarshalImageMetadataJSON(metadata, cloudSpec, time.Now()) if err != nil { return err } metadataInfo := []MetadataFile{ {IndexStoragePath(), index}, {ProductMetadataStoragePath(), products}, } for _, md := range metadataInfo { err = metadataStore.Put(md.Path, bytes.NewReader(md.Data), int64(len(md.Data))) if err != nil { return err } } return nil }
go
func writeMetadata(metadata []*ImageMetadata, cloudSpec []simplestreams.CloudSpec, metadataStore storage.Storage) error { // TODO(perrito666) 2016-05-02 lp:1558657 index, products, err := MarshalImageMetadataJSON(metadata, cloudSpec, time.Now()) if err != nil { return err } metadataInfo := []MetadataFile{ {IndexStoragePath(), index}, {ProductMetadataStoragePath(), products}, } for _, md := range metadataInfo { err = metadataStore.Put(md.Path, bytes.NewReader(md.Data), int64(len(md.Data))) if err != nil { return err } } return nil }
[ "func", "writeMetadata", "(", "metadata", "[", "]", "*", "ImageMetadata", ",", "cloudSpec", "[", "]", "simplestreams", ".", "CloudSpec", ",", "metadataStore", "storage", ".", "Storage", ")", "error", "{", "// TODO(perrito666) 2016-05-02 lp:1558657", "index", ",", "products", ",", "err", ":=", "MarshalImageMetadataJSON", "(", "metadata", ",", "cloudSpec", ",", "time", ".", "Now", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "metadataInfo", ":=", "[", "]", "MetadataFile", "{", "{", "IndexStoragePath", "(", ")", ",", "index", "}", ",", "{", "ProductMetadataStoragePath", "(", ")", ",", "products", "}", ",", "}", "\n", "for", "_", ",", "md", ":=", "range", "metadataInfo", "{", "err", "=", "metadataStore", ".", "Put", "(", "md", ".", "Path", ",", "bytes", ".", "NewReader", "(", "md", ".", "Data", ")", ",", "int64", "(", "len", "(", "md", ".", "Data", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// writeMetadata generates some basic simplestreams metadata using the specified cloud and image details and writes // it to the supplied store.
[ "writeMetadata", "generates", "some", "basic", "simplestreams", "metadata", "using", "the", "specified", "cloud", "and", "image", "details", "and", "writes", "it", "to", "the", "supplied", "store", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/imagemetadata/generate.go#L118-L137
3,715
juju/juju
state/presence/pruner.go
queueRemoval
func (p *Pruner) queueRemoval(seq int64) { p.toRemove = append(p.toRemove, docIDInt64(p.modelUUID, seq)) }
go
func (p *Pruner) queueRemoval(seq int64) { p.toRemove = append(p.toRemove, docIDInt64(p.modelUUID, seq)) }
[ "func", "(", "p", "*", "Pruner", ")", "queueRemoval", "(", "seq", "int64", ")", "{", "p", ".", "toRemove", "=", "append", "(", "p", ".", "toRemove", ",", "docIDInt64", "(", "p", ".", "modelUUID", ",", "seq", ")", ")", "\n", "}" ]
// queueRemoval includes this sequence as one that has been superseded
[ "queueRemoval", "includes", "this", "sequence", "as", "one", "that", "has", "been", "superseded" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/pruner.go#L63-L65
3,716
juju/juju
state/presence/pruner.go
flushRemovals
func (p *Pruner) flushRemovals() error { if len(p.toRemove) == 0 { return nil } matched, err := p.beingsC.RemoveAll(bson.M{"_id": bson.M{"$in": p.toRemove}}) if err != nil { return err } p.toRemove = p.toRemove[:0] if matched.Removed > 0 { p.removedCount += uint64(matched.Removed) } return err }
go
func (p *Pruner) flushRemovals() error { if len(p.toRemove) == 0 { return nil } matched, err := p.beingsC.RemoveAll(bson.M{"_id": bson.M{"$in": p.toRemove}}) if err != nil { return err } p.toRemove = p.toRemove[:0] if matched.Removed > 0 { p.removedCount += uint64(matched.Removed) } return err }
[ "func", "(", "p", "*", "Pruner", ")", "flushRemovals", "(", ")", "error", "{", "if", "len", "(", "p", ".", "toRemove", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "matched", ",", "err", ":=", "p", ".", "beingsC", ".", "RemoveAll", "(", "bson", ".", "M", "{", "\"", "\"", ":", "bson", ".", "M", "{", "\"", "\"", ":", "p", ".", "toRemove", "}", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "p", ".", "toRemove", "=", "p", ".", "toRemove", "[", ":", "0", "]", "\n", "if", "matched", ".", "Removed", ">", "0", "{", "p", ".", "removedCount", "+=", "uint64", "(", "matched", ".", "Removed", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// flushRemovals makes sure that we've applied all desired removals
[ "flushRemovals", "makes", "sure", "that", "we", "ve", "applied", "all", "desired", "removals" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/pruner.go#L68-L81
3,717
juju/juju
state/presence/pruner.go
NewPruner
func NewPruner(modelUUID string, beings *mgo.Collection, pings *mgo.Collection, delta time.Duration) *Pruner { return &Pruner{ modelUUID: modelUUID, beingsC: beings, maxQueue: 1000, pingsC: pings, delta: delta, } }
go
func NewPruner(modelUUID string, beings *mgo.Collection, pings *mgo.Collection, delta time.Duration) *Pruner { return &Pruner{ modelUUID: modelUUID, beingsC: beings, maxQueue: 1000, pingsC: pings, delta: delta, } }
[ "func", "NewPruner", "(", "modelUUID", "string", ",", "beings", "*", "mgo", ".", "Collection", ",", "pings", "*", "mgo", ".", "Collection", ",", "delta", "time", ".", "Duration", ")", "*", "Pruner", "{", "return", "&", "Pruner", "{", "modelUUID", ":", "modelUUID", ",", "beingsC", ":", "beings", ",", "maxQueue", ":", "1000", ",", "pingsC", ":", "pings", ",", "delta", ":", "delta", ",", "}", "\n", "}" ]
// NewPruner returns an object that is ready to prune the Beings collection // of old beings sequence entries that we no longer need.
[ "NewPruner", "returns", "an", "object", "that", "is", "ready", "to", "prune", "the", "Beings", "collection", "of", "old", "beings", "sequence", "entries", "that", "we", "no", "longer", "need", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/presence/pruner.go#L196-L204
3,718
juju/juju
apiserver/facades/controller/agenttools/agenttools.go
NewFacade
func NewFacade(st *state.State, resources facade.Resources, authorizer facade.Authorizer) (*AgentToolsAPI, error) { newEnviron := func() (environs.Environ, error) { newEnviron := stateenvirons.GetNewEnvironFunc(environs.New) return newEnviron(st) } return NewAgentToolsAPI(st, newEnviron, findTools, envVersionUpdate, authorizer) }
go
func NewFacade(st *state.State, resources facade.Resources, authorizer facade.Authorizer) (*AgentToolsAPI, error) { newEnviron := func() (environs.Environ, error) { newEnviron := stateenvirons.GetNewEnvironFunc(environs.New) return newEnviron(st) } return NewAgentToolsAPI(st, newEnviron, findTools, envVersionUpdate, authorizer) }
[ "func", "NewFacade", "(", "st", "*", "state", ".", "State", ",", "resources", "facade", ".", "Resources", ",", "authorizer", "facade", ".", "Authorizer", ")", "(", "*", "AgentToolsAPI", ",", "error", ")", "{", "newEnviron", ":=", "func", "(", ")", "(", "environs", ".", "Environ", ",", "error", ")", "{", "newEnviron", ":=", "stateenvirons", ".", "GetNewEnvironFunc", "(", "environs", ".", "New", ")", "\n", "return", "newEnviron", "(", "st", ")", "\n", "}", "\n", "return", "NewAgentToolsAPI", "(", "st", ",", "newEnviron", ",", "findTools", ",", "envVersionUpdate", ",", "authorizer", ")", "\n", "}" ]
// NewFacade is used to register the facade.
[ "NewFacade", "is", "used", "to", "register", "the", "facade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/agenttools/agenttools.go#L38-L44
3,719
juju/juju
apiserver/facades/controller/agenttools/agenttools.go
NewAgentToolsAPI
func NewAgentToolsAPI( modelGetter ModelGetter, newEnviron func() (environs.Environ, error), findTools toolsFinder, envVersionUpdate func(*state.Model, version.Number) error, authorizer facade.Authorizer, ) (*AgentToolsAPI, error) { return &AgentToolsAPI{ modelGetter: modelGetter, newEnviron: newEnviron, authorizer: authorizer, findTools: findTools, envVersionUpdate: envVersionUpdate, }, nil }
go
func NewAgentToolsAPI( modelGetter ModelGetter, newEnviron func() (environs.Environ, error), findTools toolsFinder, envVersionUpdate func(*state.Model, version.Number) error, authorizer facade.Authorizer, ) (*AgentToolsAPI, error) { return &AgentToolsAPI{ modelGetter: modelGetter, newEnviron: newEnviron, authorizer: authorizer, findTools: findTools, envVersionUpdate: envVersionUpdate, }, nil }
[ "func", "NewAgentToolsAPI", "(", "modelGetter", "ModelGetter", ",", "newEnviron", "func", "(", ")", "(", "environs", ".", "Environ", ",", "error", ")", ",", "findTools", "toolsFinder", ",", "envVersionUpdate", "func", "(", "*", "state", ".", "Model", ",", "version", ".", "Number", ")", "error", ",", "authorizer", "facade", ".", "Authorizer", ",", ")", "(", "*", "AgentToolsAPI", ",", "error", ")", "{", "return", "&", "AgentToolsAPI", "{", "modelGetter", ":", "modelGetter", ",", "newEnviron", ":", "newEnviron", ",", "authorizer", ":", "authorizer", ",", "findTools", ":", "findTools", ",", "envVersionUpdate", ":", "envVersionUpdate", ",", "}", ",", "nil", "\n", "}" ]
// NewAgentToolsAPI creates a new instance of the Model API.
[ "NewAgentToolsAPI", "creates", "a", "new", "instance", "of", "the", "Model", "API", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/agenttools/agenttools.go#L47-L61
3,720
juju/juju
apiserver/facades/controller/agenttools/agenttools.go
envVersionUpdate
func envVersionUpdate(env *state.Model, ver version.Number) error { return env.UpdateLatestToolsVersion(ver) }
go
func envVersionUpdate(env *state.Model, ver version.Number) error { return env.UpdateLatestToolsVersion(ver) }
[ "func", "envVersionUpdate", "(", "env", "*", "state", ".", "Model", ",", "ver", "version", ".", "Number", ")", "error", "{", "return", "env", ".", "UpdateLatestToolsVersion", "(", "ver", ")", "\n", "}" ]
// Base implementation of envVersionUpdater
[ "Base", "implementation", "of", "envVersionUpdater" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/agenttools/agenttools.go#L106-L108
3,721
juju/juju
apiserver/facades/controller/agenttools/agenttools.go
UpdateToolsAvailable
func (api *AgentToolsAPI) UpdateToolsAvailable() error { if !api.authorizer.AuthController() { return common.ErrPerm } return updateToolsAvailability(api.modelGetter, api.newEnviron, api.findTools, api.envVersionUpdate) }
go
func (api *AgentToolsAPI) UpdateToolsAvailable() error { if !api.authorizer.AuthController() { return common.ErrPerm } return updateToolsAvailability(api.modelGetter, api.newEnviron, api.findTools, api.envVersionUpdate) }
[ "func", "(", "api", "*", "AgentToolsAPI", ")", "UpdateToolsAvailable", "(", ")", "error", "{", "if", "!", "api", ".", "authorizer", ".", "AuthController", "(", ")", "{", "return", "common", ".", "ErrPerm", "\n", "}", "\n", "return", "updateToolsAvailability", "(", "api", ".", "modelGetter", ",", "api", ".", "newEnviron", ",", "api", ".", "findTools", ",", "api", ".", "envVersionUpdate", ")", "\n", "}" ]
// UpdateToolsAvailable invokes a lookup and further update in environ // for new patches of the current tool versions.
[ "UpdateToolsAvailable", "invokes", "a", "lookup", "and", "further", "update", "in", "environ", "for", "new", "patches", "of", "the", "current", "tool", "versions", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/agenttools/agenttools.go#L136-L141
3,722
juju/juju
cmd/juju/crossmodel/findformatter.go
formatFindTabular
func formatFindTabular(writer io.Writer, value interface{}) error { endpoints, ok := value.(map[string]ApplicationOfferResult) if !ok { return errors.Errorf("expected value of type %T, got %T", endpoints, value) } return formatFoundEndpointsTabular(writer, endpoints) }
go
func formatFindTabular(writer io.Writer, value interface{}) error { endpoints, ok := value.(map[string]ApplicationOfferResult) if !ok { return errors.Errorf("expected value of type %T, got %T", endpoints, value) } return formatFoundEndpointsTabular(writer, endpoints) }
[ "func", "formatFindTabular", "(", "writer", "io", ".", "Writer", ",", "value", "interface", "{", "}", ")", "error", "{", "endpoints", ",", "ok", ":=", "value", ".", "(", "map", "[", "string", "]", "ApplicationOfferResult", ")", "\n", "if", "!", "ok", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "endpoints", ",", "value", ")", "\n", "}", "\n", "return", "formatFoundEndpointsTabular", "(", "writer", ",", "endpoints", ")", "\n", "}" ]
// formatFindTabular returns a tabular summary of remote applications or // errors out if parameter is not of expected type.
[ "formatFindTabular", "returns", "a", "tabular", "summary", "of", "remote", "applications", "or", "errors", "out", "if", "parameter", "is", "not", "of", "expected", "type", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/crossmodel/findformatter.go#L20-L26
3,723
juju/juju
cmd/juju/crossmodel/findformatter.go
formatFoundEndpointsTabular
func formatFoundEndpointsTabular(writer io.Writer, all map[string]ApplicationOfferResult) error { tw := output.TabWriter(writer) w := output.Wrapper{tw} w.Println("Store", "URL", "Access", "Interfaces") for urlStr, one := range all { url, err := crossmodel.ParseOfferURL(urlStr) if err != nil { return err } store := url.Source url.Source = "" interfaces := []string{} for name, ep := range one.Endpoints { interfaces = append(interfaces, fmt.Sprintf("%s:%s", ep.Interface, name)) } sort.Strings(interfaces) w.Println(store, url.String(), one.Access, strings.Join(interfaces, ", ")) } tw.Flush() return nil }
go
func formatFoundEndpointsTabular(writer io.Writer, all map[string]ApplicationOfferResult) error { tw := output.TabWriter(writer) w := output.Wrapper{tw} w.Println("Store", "URL", "Access", "Interfaces") for urlStr, one := range all { url, err := crossmodel.ParseOfferURL(urlStr) if err != nil { return err } store := url.Source url.Source = "" interfaces := []string{} for name, ep := range one.Endpoints { interfaces = append(interfaces, fmt.Sprintf("%s:%s", ep.Interface, name)) } sort.Strings(interfaces) w.Println(store, url.String(), one.Access, strings.Join(interfaces, ", ")) } tw.Flush() return nil }
[ "func", "formatFoundEndpointsTabular", "(", "writer", "io", ".", "Writer", ",", "all", "map", "[", "string", "]", "ApplicationOfferResult", ")", "error", "{", "tw", ":=", "output", ".", "TabWriter", "(", "writer", ")", "\n", "w", ":=", "output", ".", "Wrapper", "{", "tw", "}", "\n", "w", ".", "Println", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "for", "urlStr", ",", "one", ":=", "range", "all", "{", "url", ",", "err", ":=", "crossmodel", ".", "ParseOfferURL", "(", "urlStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "store", ":=", "url", ".", "Source", "\n", "url", ".", "Source", "=", "\"", "\"", "\n\n", "interfaces", ":=", "[", "]", "string", "{", "}", "\n", "for", "name", ",", "ep", ":=", "range", "one", ".", "Endpoints", "{", "interfaces", "=", "append", "(", "interfaces", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ep", ".", "Interface", ",", "name", ")", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "interfaces", ")", "\n", "w", ".", "Println", "(", "store", ",", "url", ".", "String", "(", ")", ",", "one", ".", "Access", ",", "strings", ".", "Join", "(", "interfaces", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "tw", ".", "Flush", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// formatFoundEndpointsTabular returns a tabular summary of offered applications' endpoints.
[ "formatFoundEndpointsTabular", "returns", "a", "tabular", "summary", "of", "offered", "applications", "endpoints", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/crossmodel/findformatter.go#L29-L52
3,724
juju/juju
core/crossmodel/offerurl.go
Path
func (u *OfferURL) Path() string { var parts []string if u.User != "" { parts = append(parts, u.User) } if u.ModelName != "" { parts = append(parts, u.ModelName) } path := strings.Join(parts, "/") path = fmt.Sprintf("%s.%s", path, u.ApplicationName) if u.Source == "" { return path } return fmt.Sprintf("%s:%s", u.Source, path) }
go
func (u *OfferURL) Path() string { var parts []string if u.User != "" { parts = append(parts, u.User) } if u.ModelName != "" { parts = append(parts, u.ModelName) } path := strings.Join(parts, "/") path = fmt.Sprintf("%s.%s", path, u.ApplicationName) if u.Source == "" { return path } return fmt.Sprintf("%s:%s", u.Source, path) }
[ "func", "(", "u", "*", "OfferURL", ")", "Path", "(", ")", "string", "{", "var", "parts", "[", "]", "string", "\n", "if", "u", ".", "User", "!=", "\"", "\"", "{", "parts", "=", "append", "(", "parts", ",", "u", ".", "User", ")", "\n", "}", "\n", "if", "u", ".", "ModelName", "!=", "\"", "\"", "{", "parts", "=", "append", "(", "parts", ",", "u", ".", "ModelName", ")", "\n", "}", "\n", "path", ":=", "strings", ".", "Join", "(", "parts", ",", "\"", "\"", ")", "\n", "path", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "path", ",", "u", ".", "ApplicationName", ")", "\n", "if", "u", ".", "Source", "==", "\"", "\"", "{", "return", "path", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "u", ".", "Source", ",", "path", ")", "\n", "}" ]
// Path returns the path component of the URL.
[ "Path", "returns", "the", "path", "component", "of", "the", "URL", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/crossmodel/offerurl.go#L36-L50
3,725
juju/juju
core/crossmodel/offerurl.go
parseOfferURL
func parseOfferURL(urlStr string) (*OfferURL, error) { urlParts, err := parseOfferURLParts(urlStr, false) if err != nil { return nil, err } url := OfferURL(*urlParts) return &url, nil }
go
func parseOfferURL(urlStr string) (*OfferURL, error) { urlParts, err := parseOfferURLParts(urlStr, false) if err != nil { return nil, err } url := OfferURL(*urlParts) return &url, nil }
[ "func", "parseOfferURL", "(", "urlStr", "string", ")", "(", "*", "OfferURL", ",", "error", ")", "{", "urlParts", ",", "err", ":=", "parseOfferURLParts", "(", "urlStr", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "url", ":=", "OfferURL", "(", "*", "urlParts", ")", "\n", "return", "&", "url", ",", "nil", "\n", "}" ]
// parseOfferURL parses the specified URL string into an OfferURL.
[ "parseOfferURL", "parses", "the", "specified", "URL", "string", "into", "an", "OfferURL", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/crossmodel/offerurl.go#L87-L94
3,726
juju/juju
core/crossmodel/offerurl.go
MakeURL
func MakeURL(user, model, application, controller string) string { base := fmt.Sprintf("%s/%s.%s", user, model, application) if controller == "" { return base } return fmt.Sprintf("%s:%s", controller, base) }
go
func MakeURL(user, model, application, controller string) string { base := fmt.Sprintf("%s/%s.%s", user, model, application) if controller == "" { return base } return fmt.Sprintf("%s:%s", controller, base) }
[ "func", "MakeURL", "(", "user", ",", "model", ",", "application", ",", "controller", "string", ")", "string", "{", "base", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "user", ",", "model", ",", "application", ")", "\n", "if", "controller", "==", "\"", "\"", "{", "return", "base", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "controller", ",", "base", ")", "\n", "}" ]
// MakeURL constructs an offer URL from the specified components.
[ "MakeURL", "constructs", "an", "offer", "URL", "from", "the", "specified", "components", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/crossmodel/offerurl.go#L161-L167
3,727
juju/juju
provider/cloudsigma/provider.go
Open
func (environProvider) Open(args environs.OpenParams) (environs.Environ, error) { logger.Infof("opening model %q", args.Config.Name()) if err := validateCloudSpec(args.Cloud); err != nil { return nil, errors.Annotate(err, "validating cloud spec") } client, err := newClient(args.Cloud, args.Config.UUID()) if err != nil { return nil, errors.Trace(err) } env := &environ{ name: args.Config.Name(), cloud: args.Cloud, client: client, } if err := env.SetConfig(args.Config); err != nil { return nil, err } return env, nil }
go
func (environProvider) Open(args environs.OpenParams) (environs.Environ, error) { logger.Infof("opening model %q", args.Config.Name()) if err := validateCloudSpec(args.Cloud); err != nil { return nil, errors.Annotate(err, "validating cloud spec") } client, err := newClient(args.Cloud, args.Config.UUID()) if err != nil { return nil, errors.Trace(err) } env := &environ{ name: args.Config.Name(), cloud: args.Cloud, client: client, } if err := env.SetConfig(args.Config); err != nil { return nil, err } return env, nil }
[ "func", "(", "environProvider", ")", "Open", "(", "args", "environs", ".", "OpenParams", ")", "(", "environs", ".", "Environ", ",", "error", ")", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "args", ".", "Config", ".", "Name", "(", ")", ")", "\n", "if", "err", ":=", "validateCloudSpec", "(", "args", ".", "Cloud", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "client", ",", "err", ":=", "newClient", "(", "args", ".", "Cloud", ",", "args", ".", "Config", ".", "UUID", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "env", ":=", "&", "environ", "{", "name", ":", "args", ".", "Config", ".", "Name", "(", ")", ",", "cloud", ":", "args", ".", "Cloud", ",", "client", ":", "client", ",", "}", "\n", "if", "err", ":=", "env", ".", "SetConfig", "(", "args", ".", "Config", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "env", ",", "nil", "\n", "}" ]
// Open opens the environment and returns it. // The configuration must have come from a previously // prepared environment.
[ "Open", "opens", "the", "environment", "and", "returns", "it", ".", "The", "configuration", "must", "have", "come", "from", "a", "previously", "prepared", "environment", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/cloudsigma/provider.go#L69-L89
3,728
juju/juju
provider/cloudsigma/provider.go
Validate
func (environProvider) Validate(cfg, old *config.Config) (*config.Config, error) { logger.Infof("validating model %q", cfg.Name()) // You should almost certainly not change this method; if you need to change // how configs are validated, you should edit validateConfig itself, to ensure // that your checks are always applied. newEcfg, err := validateConfig(cfg, nil) if err != nil { return nil, errors.Errorf("invalid config: %v", err) } if old != nil { oldEcfg, err := validateConfig(old, nil) if err != nil { return nil, errors.Errorf("invalid base config: %v", err) } if newEcfg, err = validateConfig(cfg, oldEcfg); err != nil { return nil, errors.Errorf("invalid config change: %v", err) } } return newEcfg.Config, nil }
go
func (environProvider) Validate(cfg, old *config.Config) (*config.Config, error) { logger.Infof("validating model %q", cfg.Name()) // You should almost certainly not change this method; if you need to change // how configs are validated, you should edit validateConfig itself, to ensure // that your checks are always applied. newEcfg, err := validateConfig(cfg, nil) if err != nil { return nil, errors.Errorf("invalid config: %v", err) } if old != nil { oldEcfg, err := validateConfig(old, nil) if err != nil { return nil, errors.Errorf("invalid base config: %v", err) } if newEcfg, err = validateConfig(cfg, oldEcfg); err != nil { return nil, errors.Errorf("invalid config change: %v", err) } } return newEcfg.Config, nil }
[ "func", "(", "environProvider", ")", "Validate", "(", "cfg", ",", "old", "*", "config", ".", "Config", ")", "(", "*", "config", ".", "Config", ",", "error", ")", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "cfg", ".", "Name", "(", ")", ")", "\n\n", "// You should almost certainly not change this method; if you need to change", "// how configs are validated, you should edit validateConfig itself, to ensure", "// that your checks are always applied.", "newEcfg", ",", "err", ":=", "validateConfig", "(", "cfg", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "old", "!=", "nil", "{", "oldEcfg", ",", "err", ":=", "validateConfig", "(", "old", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "newEcfg", ",", "err", "=", "validateConfig", "(", "cfg", ",", "oldEcfg", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "newEcfg", ".", "Config", ",", "nil", "\n", "}" ]
// Validate ensures that config is a valid configuration for this // provider, applying changes to it if necessary, and returns the // validated configuration. // If old is not nil, it holds the previous environment configuration // for consideration when validating changes.
[ "Validate", "ensures", "that", "config", "is", "a", "valid", "configuration", "for", "this", "provider", "applying", "changes", "to", "it", "if", "necessary", "and", "returns", "the", "validated", "configuration", ".", "If", "old", "is", "not", "nil", "it", "holds", "the", "previous", "environment", "configuration", "for", "consideration", "when", "validating", "changes", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/cloudsigma/provider.go#L115-L136
3,729
juju/juju
worker/metricworker/cleanup.go
newCleanup
func newCleanup(client metricsmanager.MetricsManagerClient, notify chan string) worker.Worker { f := func(stopCh <-chan struct{}) error { err := client.CleanupOldMetrics() if err != nil { cleanupLogger.Warningf("failed to cleanup %v - will retry later", err) return nil } select { case notify <- "cleanupCalled": default: } return nil } return jworker.NewPeriodicWorker(f, cleanupPeriod, jworker.NewTimer) }
go
func newCleanup(client metricsmanager.MetricsManagerClient, notify chan string) worker.Worker { f := func(stopCh <-chan struct{}) error { err := client.CleanupOldMetrics() if err != nil { cleanupLogger.Warningf("failed to cleanup %v - will retry later", err) return nil } select { case notify <- "cleanupCalled": default: } return nil } return jworker.NewPeriodicWorker(f, cleanupPeriod, jworker.NewTimer) }
[ "func", "newCleanup", "(", "client", "metricsmanager", ".", "MetricsManagerClient", ",", "notify", "chan", "string", ")", "worker", ".", "Worker", "{", "f", ":=", "func", "(", "stopCh", "<-", "chan", "struct", "{", "}", ")", "error", "{", "err", ":=", "client", ".", "CleanupOldMetrics", "(", ")", "\n", "if", "err", "!=", "nil", "{", "cleanupLogger", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n", "select", "{", "case", "notify", "<-", "\"", "\"", ":", "default", ":", "}", "\n", "return", "nil", "\n", "}", "\n", "return", "jworker", ".", "NewPeriodicWorker", "(", "f", ",", "cleanupPeriod", ",", "jworker", ".", "NewTimer", ")", "\n", "}" ]
// NewCleanup creates a new periodic worker that calls the CleanupOldMetrics api.
[ "NewCleanup", "creates", "a", "new", "periodic", "worker", "that", "calls", "the", "CleanupOldMetrics", "api", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/metricworker/cleanup.go#L21-L35
3,730
juju/juju
provider/oci/networking.go
ensureNetworksAndSubnets
func (e *Environ) ensureNetworksAndSubnets(ctx envcontext.ProviderCallContext, controllerUUID, modelUUID string) (map[string][]ociCore.Subnet, error) { // if we have the subnets field populated, it means we already checked/created // the necessary resources. Simply return. if e.subnets != nil { return e.subnets, nil } vcn, err := e.ensureVCN(controllerUUID, modelUUID) if err != nil { providerCommon.HandleCredentialError(err, ctx) return nil, errors.Trace(err) } // NOTE(gsamfira): There are some limitations at the moment in regards to // security lists: // * Security lists can only be applied on subnets // * Once subnet is created, you may not attach a new security list to that subnet // * there is no way to apply a security list on an instance/VNIC // * We cannot create a model level security list, unless we create a new subnet for that model // ** that means at least 3 subnets per model, which is something we probably don't want // * There is no way to specify the target prefix for an Ingress/Egress rule, thus making // instance level firewalling, impossible. // For now, we open all ports until we decide how to properly take care of this. secList, err := e.ensureSecurityList(controllerUUID, modelUUID, vcn.Id) if err != nil { providerCommon.HandleCredentialError(err, ctx) return nil, errors.Trace(err) } ig, err := e.ensureInternetGateway(controllerUUID, modelUUID, vcn.Id) if err != nil { providerCommon.HandleCredentialError(err, ctx) return nil, errors.Trace(err) } // Create a default route through the gateway created above // as a default gateway prefix := AllowAllPrefix routeRules := []ociCore.RouteRule{ { CidrBlock: &prefix, NetworkEntityId: ig.Id, }, } routeTable, err := e.ensureRouteTable(controllerUUID, modelUUID, vcn.Id, routeRules) if err != nil { providerCommon.HandleCredentialError(err, ctx) return nil, errors.Trace(err) } subnets, err := e.ensureSubnets(ctx, vcn, secList, controllerUUID, modelUUID, routeTable.Id) if err != nil { providerCommon.HandleCredentialError(err, ctx) return nil, errors.Trace(err) } // TODO(gsamfira): should we use a lock here? e.subnets = subnets return e.subnets, nil }
go
func (e *Environ) ensureNetworksAndSubnets(ctx envcontext.ProviderCallContext, controllerUUID, modelUUID string) (map[string][]ociCore.Subnet, error) { // if we have the subnets field populated, it means we already checked/created // the necessary resources. Simply return. if e.subnets != nil { return e.subnets, nil } vcn, err := e.ensureVCN(controllerUUID, modelUUID) if err != nil { providerCommon.HandleCredentialError(err, ctx) return nil, errors.Trace(err) } // NOTE(gsamfira): There are some limitations at the moment in regards to // security lists: // * Security lists can only be applied on subnets // * Once subnet is created, you may not attach a new security list to that subnet // * there is no way to apply a security list on an instance/VNIC // * We cannot create a model level security list, unless we create a new subnet for that model // ** that means at least 3 subnets per model, which is something we probably don't want // * There is no way to specify the target prefix for an Ingress/Egress rule, thus making // instance level firewalling, impossible. // For now, we open all ports until we decide how to properly take care of this. secList, err := e.ensureSecurityList(controllerUUID, modelUUID, vcn.Id) if err != nil { providerCommon.HandleCredentialError(err, ctx) return nil, errors.Trace(err) } ig, err := e.ensureInternetGateway(controllerUUID, modelUUID, vcn.Id) if err != nil { providerCommon.HandleCredentialError(err, ctx) return nil, errors.Trace(err) } // Create a default route through the gateway created above // as a default gateway prefix := AllowAllPrefix routeRules := []ociCore.RouteRule{ { CidrBlock: &prefix, NetworkEntityId: ig.Id, }, } routeTable, err := e.ensureRouteTable(controllerUUID, modelUUID, vcn.Id, routeRules) if err != nil { providerCommon.HandleCredentialError(err, ctx) return nil, errors.Trace(err) } subnets, err := e.ensureSubnets(ctx, vcn, secList, controllerUUID, modelUUID, routeTable.Id) if err != nil { providerCommon.HandleCredentialError(err, ctx) return nil, errors.Trace(err) } // TODO(gsamfira): should we use a lock here? e.subnets = subnets return e.subnets, nil }
[ "func", "(", "e", "*", "Environ", ")", "ensureNetworksAndSubnets", "(", "ctx", "envcontext", ".", "ProviderCallContext", ",", "controllerUUID", ",", "modelUUID", "string", ")", "(", "map", "[", "string", "]", "[", "]", "ociCore", ".", "Subnet", ",", "error", ")", "{", "// if we have the subnets field populated, it means we already checked/created", "// the necessary resources. Simply return.", "if", "e", ".", "subnets", "!=", "nil", "{", "return", "e", ".", "subnets", ",", "nil", "\n", "}", "\n", "vcn", ",", "err", ":=", "e", ".", "ensureVCN", "(", "controllerUUID", ",", "modelUUID", ")", "\n", "if", "err", "!=", "nil", "{", "providerCommon", ".", "HandleCredentialError", "(", "err", ",", "ctx", ")", "\n", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// NOTE(gsamfira): There are some limitations at the moment in regards to", "// security lists:", "// * Security lists can only be applied on subnets", "// * Once subnet is created, you may not attach a new security list to that subnet", "// * there is no way to apply a security list on an instance/VNIC", "// * We cannot create a model level security list, unless we create a new subnet for that model", "// ** that means at least 3 subnets per model, which is something we probably don't want", "// * There is no way to specify the target prefix for an Ingress/Egress rule, thus making", "// instance level firewalling, impossible.", "// For now, we open all ports until we decide how to properly take care of this.", "secList", ",", "err", ":=", "e", ".", "ensureSecurityList", "(", "controllerUUID", ",", "modelUUID", ",", "vcn", ".", "Id", ")", "\n", "if", "err", "!=", "nil", "{", "providerCommon", ".", "HandleCredentialError", "(", "err", ",", "ctx", ")", "\n", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "ig", ",", "err", ":=", "e", ".", "ensureInternetGateway", "(", "controllerUUID", ",", "modelUUID", ",", "vcn", ".", "Id", ")", "\n", "if", "err", "!=", "nil", "{", "providerCommon", ".", "HandleCredentialError", "(", "err", ",", "ctx", ")", "\n", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// Create a default route through the gateway created above", "// as a default gateway", "prefix", ":=", "AllowAllPrefix", "\n", "routeRules", ":=", "[", "]", "ociCore", ".", "RouteRule", "{", "{", "CidrBlock", ":", "&", "prefix", ",", "NetworkEntityId", ":", "ig", ".", "Id", ",", "}", ",", "}", "\n", "routeTable", ",", "err", ":=", "e", ".", "ensureRouteTable", "(", "controllerUUID", ",", "modelUUID", ",", "vcn", ".", "Id", ",", "routeRules", ")", "\n", "if", "err", "!=", "nil", "{", "providerCommon", ".", "HandleCredentialError", "(", "err", ",", "ctx", ")", "\n", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "subnets", ",", "err", ":=", "e", ".", "ensureSubnets", "(", "ctx", ",", "vcn", ",", "secList", ",", "controllerUUID", ",", "modelUUID", ",", "routeTable", ".", "Id", ")", "\n", "if", "err", "!=", "nil", "{", "providerCommon", ".", "HandleCredentialError", "(", "err", ",", "ctx", ")", "\n", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "// TODO(gsamfira): should we use a lock here?", "e", ".", "subnets", "=", "subnets", "\n", "return", "e", ".", "subnets", ",", "nil", "\n", "}" ]
// ensureNetworksAndSubnets creates VCNs, security lists and subnets that will // be used throughout the life-cycle of this juju deployment.
[ "ensureNetworksAndSubnets", "creates", "VCNs", "security", "lists", "and", "subnets", "that", "will", "be", "used", "throughout", "the", "life", "-", "cycle", "of", "this", "juju", "deployment", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oci/networking.go#L449-L506
3,731
juju/juju
provider/oci/networking.go
cleanupNetworksAndSubnets
func (e *Environ) cleanupNetworksAndSubnets(controllerUUID, modelUUID string) error { vcns, err := e.allVCNs(controllerUUID, modelUUID) if err != nil { return errors.Trace(err) } if len(vcns) == 0 { return nil } for _, vcn := range vcns { allSubnets, err := e.allSubnets(controllerUUID, modelUUID, vcn.Id) if err != nil { return errors.Trace(err) } if err := e.removeSubnets(allSubnets); err != nil { return errors.Trace(err) } secList, err := e.allSecurityLists(controllerUUID, modelUUID, vcn.Id) if err != nil { return errors.Trace(err) } if err := e.removeSeclist(secList); err != nil { return errors.Trace(err) } if err := e.deleteRouteTable(controllerUUID, modelUUID, vcn.Id); err != nil { return errors.Trace(err) } if err := e.deleteInternetGateway(vcn.Id); err != nil { return errors.Trace(err) } if err := e.removeVCN(vcn); err != nil { return errors.Trace(err) } } return nil }
go
func (e *Environ) cleanupNetworksAndSubnets(controllerUUID, modelUUID string) error { vcns, err := e.allVCNs(controllerUUID, modelUUID) if err != nil { return errors.Trace(err) } if len(vcns) == 0 { return nil } for _, vcn := range vcns { allSubnets, err := e.allSubnets(controllerUUID, modelUUID, vcn.Id) if err != nil { return errors.Trace(err) } if err := e.removeSubnets(allSubnets); err != nil { return errors.Trace(err) } secList, err := e.allSecurityLists(controllerUUID, modelUUID, vcn.Id) if err != nil { return errors.Trace(err) } if err := e.removeSeclist(secList); err != nil { return errors.Trace(err) } if err := e.deleteRouteTable(controllerUUID, modelUUID, vcn.Id); err != nil { return errors.Trace(err) } if err := e.deleteInternetGateway(vcn.Id); err != nil { return errors.Trace(err) } if err := e.removeVCN(vcn); err != nil { return errors.Trace(err) } } return nil }
[ "func", "(", "e", "*", "Environ", ")", "cleanupNetworksAndSubnets", "(", "controllerUUID", ",", "modelUUID", "string", ")", "error", "{", "vcns", ",", "err", ":=", "e", ".", "allVCNs", "(", "controllerUUID", ",", "modelUUID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "vcns", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "for", "_", ",", "vcn", ":=", "range", "vcns", "{", "allSubnets", ",", "err", ":=", "e", ".", "allSubnets", "(", "controllerUUID", ",", "modelUUID", ",", "vcn", ".", "Id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "e", ".", "removeSubnets", "(", "allSubnets", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "secList", ",", "err", ":=", "e", ".", "allSecurityLists", "(", "controllerUUID", ",", "modelUUID", ",", "vcn", ".", "Id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "e", ".", "removeSeclist", "(", "secList", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "e", ".", "deleteRouteTable", "(", "controllerUUID", ",", "modelUUID", ",", "vcn", ".", "Id", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "e", ".", "deleteInternetGateway", "(", "vcn", ".", "Id", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "e", ".", "removeVCN", "(", "vcn", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// cleanupNetworksAndSubnets destroys all subnets, VCNs and security lists that have // been used by this juju deployment. This function should only be called when // destroying the environment, and only after destroying any resources that may be attached // to a network.
[ "cleanupNetworksAndSubnets", "destroys", "all", "subnets", "VCNs", "and", "security", "lists", "that", "have", "been", "used", "by", "this", "juju", "deployment", ".", "This", "function", "should", "only", "be", "called", "when", "destroying", "the", "environment", "and", "only", "after", "destroying", "any", "resources", "that", "may", "be", "attached", "to", "a", "network", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oci/networking.go#L588-L630
3,732
juju/juju
state/metrics.go
validate
func (m *MetricBatch) validate() error { charmURL, err := charm.ParseURL(m.doc.CharmURL) if err != nil { return errors.Trace(err) } chrm, err := m.st.Charm(charmURL) if err != nil { return errors.Trace(err) } chrmMetrics := chrm.Metrics() if chrmMetrics == nil { return errors.Errorf("charm doesn't implement metrics") } for _, m := range m.doc.Metrics { if err := chrmMetrics.ValidateMetric(m.Key, m.Value); err != nil { return errors.Trace(err) } } return nil }
go
func (m *MetricBatch) validate() error { charmURL, err := charm.ParseURL(m.doc.CharmURL) if err != nil { return errors.Trace(err) } chrm, err := m.st.Charm(charmURL) if err != nil { return errors.Trace(err) } chrmMetrics := chrm.Metrics() if chrmMetrics == nil { return errors.Errorf("charm doesn't implement metrics") } for _, m := range m.doc.Metrics { if err := chrmMetrics.ValidateMetric(m.Key, m.Value); err != nil { return errors.Trace(err) } } return nil }
[ "func", "(", "m", "*", "MetricBatch", ")", "validate", "(", ")", "error", "{", "charmURL", ",", "err", ":=", "charm", ".", "ParseURL", "(", "m", ".", "doc", ".", "CharmURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "chrm", ",", "err", ":=", "m", ".", "st", ".", "Charm", "(", "charmURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "chrmMetrics", ":=", "chrm", ".", "Metrics", "(", ")", "\n", "if", "chrmMetrics", "==", "nil", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "for", "_", ",", "m", ":=", "range", "m", ".", "doc", ".", "Metrics", "{", "if", "err", ":=", "chrmMetrics", ".", "ValidateMetric", "(", "m", ".", "Key", ",", "m", ".", "Value", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validate checks that the MetricBatch contains valid metrics.
[ "validate", "checks", "that", "the", "MetricBatch", "contains", "valid", "metrics", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/metrics.go#L98-L117
3,733
juju/juju
state/metrics.go
AddMetrics
func (st *State) AddMetrics(batch BatchParam) (*MetricBatch, error) { if len(batch.Metrics) == 0 { return nil, errors.New("cannot add a batch of 0 metrics") } charmURL, err := charm.ParseURL(batch.CharmURL) if err != nil { return nil, errors.NewNotValid(err, "could not parse charm URL") } unit, err := st.Unit(batch.Unit.Id()) if err != nil { return nil, errors.Trace(err) } application, err := unit.Application() slaCreds, err := st.SLACredential() if err != nil { return nil, errors.Trace(err) } metric := &MetricBatch{ st: st, doc: metricBatchDoc{ UUID: batch.UUID, ModelUUID: st.ModelUUID(), Unit: batch.Unit.Id(), CharmURL: charmURL.String(), Sent: false, Created: batch.Created, Metrics: batch.Metrics, Credentials: application.MetricCredentials(), SLACredentials: slaCreds, }, } if err := metric.validate(); err != nil { return nil, err } buildTxn := func(attempt int) ([]txn.Op, error) { if attempt > 0 { notDead, err := isNotDead(st, unitsC, batch.Unit.Id()) if err != nil || !notDead { return nil, errors.NotFoundf(batch.Unit.Id()) } exists, err := st.MetricBatch(batch.UUID) if exists != nil && err == nil { return nil, errors.AlreadyExistsf("metrics batch UUID %q", batch.UUID) } if !errors.IsNotFound(err) { return nil, errors.Trace(err) } } ops := []txn.Op{{ C: unitsC, Id: st.docID(batch.Unit.Id()), Assert: notDeadDoc, }, { C: metricsC, Id: metric.UUID(), Assert: txn.DocMissing, Insert: &metric.doc, }} return ops, nil } err = st.db().Run(buildTxn) if err != nil { return nil, errors.Trace(err) } return metric, nil }
go
func (st *State) AddMetrics(batch BatchParam) (*MetricBatch, error) { if len(batch.Metrics) == 0 { return nil, errors.New("cannot add a batch of 0 metrics") } charmURL, err := charm.ParseURL(batch.CharmURL) if err != nil { return nil, errors.NewNotValid(err, "could not parse charm URL") } unit, err := st.Unit(batch.Unit.Id()) if err != nil { return nil, errors.Trace(err) } application, err := unit.Application() slaCreds, err := st.SLACredential() if err != nil { return nil, errors.Trace(err) } metric := &MetricBatch{ st: st, doc: metricBatchDoc{ UUID: batch.UUID, ModelUUID: st.ModelUUID(), Unit: batch.Unit.Id(), CharmURL: charmURL.String(), Sent: false, Created: batch.Created, Metrics: batch.Metrics, Credentials: application.MetricCredentials(), SLACredentials: slaCreds, }, } if err := metric.validate(); err != nil { return nil, err } buildTxn := func(attempt int) ([]txn.Op, error) { if attempt > 0 { notDead, err := isNotDead(st, unitsC, batch.Unit.Id()) if err != nil || !notDead { return nil, errors.NotFoundf(batch.Unit.Id()) } exists, err := st.MetricBatch(batch.UUID) if exists != nil && err == nil { return nil, errors.AlreadyExistsf("metrics batch UUID %q", batch.UUID) } if !errors.IsNotFound(err) { return nil, errors.Trace(err) } } ops := []txn.Op{{ C: unitsC, Id: st.docID(batch.Unit.Id()), Assert: notDeadDoc, }, { C: metricsC, Id: metric.UUID(), Assert: txn.DocMissing, Insert: &metric.doc, }} return ops, nil } err = st.db().Run(buildTxn) if err != nil { return nil, errors.Trace(err) } return metric, nil }
[ "func", "(", "st", "*", "State", ")", "AddMetrics", "(", "batch", "BatchParam", ")", "(", "*", "MetricBatch", ",", "error", ")", "{", "if", "len", "(", "batch", ".", "Metrics", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "charmURL", ",", "err", ":=", "charm", ".", "ParseURL", "(", "batch", ".", "CharmURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "NewNotValid", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "unit", ",", "err", ":=", "st", ".", "Unit", "(", "batch", ".", "Unit", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "application", ",", "err", ":=", "unit", ".", "Application", "(", ")", "\n\n", "slaCreds", ",", "err", ":=", "st", ".", "SLACredential", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "metric", ":=", "&", "MetricBatch", "{", "st", ":", "st", ",", "doc", ":", "metricBatchDoc", "{", "UUID", ":", "batch", ".", "UUID", ",", "ModelUUID", ":", "st", ".", "ModelUUID", "(", ")", ",", "Unit", ":", "batch", ".", "Unit", ".", "Id", "(", ")", ",", "CharmURL", ":", "charmURL", ".", "String", "(", ")", ",", "Sent", ":", "false", ",", "Created", ":", "batch", ".", "Created", ",", "Metrics", ":", "batch", ".", "Metrics", ",", "Credentials", ":", "application", ".", "MetricCredentials", "(", ")", ",", "SLACredentials", ":", "slaCreds", ",", "}", ",", "}", "\n", "if", "err", ":=", "metric", ".", "validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "if", "attempt", ">", "0", "{", "notDead", ",", "err", ":=", "isNotDead", "(", "st", ",", "unitsC", ",", "batch", ".", "Unit", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "||", "!", "notDead", "{", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "batch", ".", "Unit", ".", "Id", "(", ")", ")", "\n", "}", "\n", "exists", ",", "err", ":=", "st", ".", "MetricBatch", "(", "batch", ".", "UUID", ")", "\n", "if", "exists", "!=", "nil", "&&", "err", "==", "nil", "{", "return", "nil", ",", "errors", ".", "AlreadyExistsf", "(", "\"", "\"", ",", "batch", ".", "UUID", ")", "\n", "}", "\n", "if", "!", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "ops", ":=", "[", "]", "txn", ".", "Op", "{", "{", "C", ":", "unitsC", ",", "Id", ":", "st", ".", "docID", "(", "batch", ".", "Unit", ".", "Id", "(", ")", ")", ",", "Assert", ":", "notDeadDoc", ",", "}", ",", "{", "C", ":", "metricsC", ",", "Id", ":", "metric", ".", "UUID", "(", ")", ",", "Assert", ":", "txn", ".", "DocMissing", ",", "Insert", ":", "&", "metric", ".", "doc", ",", "}", "}", "\n", "return", "ops", ",", "nil", "\n", "}", "\n", "err", "=", "st", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "metric", ",", "nil", "\n", "}" ]
// AddMetrics adds a new batch of metrics to the database.
[ "AddMetrics", "adds", "a", "new", "batch", "of", "metrics", "to", "the", "database", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/metrics.go#L138-L207
3,734
juju/juju
state/metrics.go
AddModelMetrics
func (st *State) AddModelMetrics(batch ModelBatchParam) (*MetricBatch, error) { if len(batch.Metrics) == 0 { return nil, errors.New("cannot add a batch of 0 metrics") } slaCreds, err := st.SLACredential() if err != nil { return nil, errors.Trace(err) } metric := &MetricBatch{ st: st, doc: metricBatchDoc{ UUID: batch.UUID, ModelUUID: st.ModelUUID(), Sent: false, Created: batch.Created, Metrics: batch.Metrics, SLACredentials: slaCreds, }, } buildTxn := func(attempt int) ([]txn.Op, error) { if attempt > 0 { exists, err := st.MetricBatch(batch.UUID) if exists != nil && err == nil { return nil, errors.AlreadyExistsf("metrics batch UUID %q", batch.UUID) } if !errors.IsNotFound(err) { return nil, errors.Trace(err) } } ops := []txn.Op{{ C: metricsC, Id: metric.UUID(), Assert: txn.DocMissing, Insert: &metric.doc, }} return ops, nil } err = st.db().Run(buildTxn) if err != nil { return nil, errors.Trace(err) } return metric, nil }
go
func (st *State) AddModelMetrics(batch ModelBatchParam) (*MetricBatch, error) { if len(batch.Metrics) == 0 { return nil, errors.New("cannot add a batch of 0 metrics") } slaCreds, err := st.SLACredential() if err != nil { return nil, errors.Trace(err) } metric := &MetricBatch{ st: st, doc: metricBatchDoc{ UUID: batch.UUID, ModelUUID: st.ModelUUID(), Sent: false, Created: batch.Created, Metrics: batch.Metrics, SLACredentials: slaCreds, }, } buildTxn := func(attempt int) ([]txn.Op, error) { if attempt > 0 { exists, err := st.MetricBatch(batch.UUID) if exists != nil && err == nil { return nil, errors.AlreadyExistsf("metrics batch UUID %q", batch.UUID) } if !errors.IsNotFound(err) { return nil, errors.Trace(err) } } ops := []txn.Op{{ C: metricsC, Id: metric.UUID(), Assert: txn.DocMissing, Insert: &metric.doc, }} return ops, nil } err = st.db().Run(buildTxn) if err != nil { return nil, errors.Trace(err) } return metric, nil }
[ "func", "(", "st", "*", "State", ")", "AddModelMetrics", "(", "batch", "ModelBatchParam", ")", "(", "*", "MetricBatch", ",", "error", ")", "{", "if", "len", "(", "batch", ".", "Metrics", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "slaCreds", ",", "err", ":=", "st", ".", "SLACredential", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "metric", ":=", "&", "MetricBatch", "{", "st", ":", "st", ",", "doc", ":", "metricBatchDoc", "{", "UUID", ":", "batch", ".", "UUID", ",", "ModelUUID", ":", "st", ".", "ModelUUID", "(", ")", ",", "Sent", ":", "false", ",", "Created", ":", "batch", ".", "Created", ",", "Metrics", ":", "batch", ".", "Metrics", ",", "SLACredentials", ":", "slaCreds", ",", "}", ",", "}", "\n", "buildTxn", ":=", "func", "(", "attempt", "int", ")", "(", "[", "]", "txn", ".", "Op", ",", "error", ")", "{", "if", "attempt", ">", "0", "{", "exists", ",", "err", ":=", "st", ".", "MetricBatch", "(", "batch", ".", "UUID", ")", "\n", "if", "exists", "!=", "nil", "&&", "err", "==", "nil", "{", "return", "nil", ",", "errors", ".", "AlreadyExistsf", "(", "\"", "\"", ",", "batch", ".", "UUID", ")", "\n", "}", "\n", "if", "!", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "ops", ":=", "[", "]", "txn", ".", "Op", "{", "{", "C", ":", "metricsC", ",", "Id", ":", "metric", ".", "UUID", "(", ")", ",", "Assert", ":", "txn", ".", "DocMissing", ",", "Insert", ":", "&", "metric", ".", "doc", ",", "}", "}", "\n", "return", "ops", ",", "nil", "\n", "}", "\n", "err", "=", "st", ".", "db", "(", ")", ".", "Run", "(", "buildTxn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "metric", ",", "nil", "\n", "}" ]
// AddModelMetrics adds a new model-centric batch of metrics to the database.
[ "AddModelMetrics", "adds", "a", "new", "model", "-", "centric", "batch", "of", "metrics", "to", "the", "database", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/metrics.go#L210-L253
3,735
juju/juju
state/metrics.go
MetricBatchesForUnit
func (st *State) MetricBatchesForUnit(unit string) ([]MetricBatch, error) { _, err := st.Unit(unit) if err != nil { return nil, errors.Trace(err) } return st.queryMetricBatches(bson.M{"unit": unit}) }
go
func (st *State) MetricBatchesForUnit(unit string) ([]MetricBatch, error) { _, err := st.Unit(unit) if err != nil { return nil, errors.Trace(err) } return st.queryMetricBatches(bson.M{"unit": unit}) }
[ "func", "(", "st", "*", "State", ")", "MetricBatchesForUnit", "(", "unit", "string", ")", "(", "[", "]", "MetricBatch", ",", "error", ")", "{", "_", ",", "err", ":=", "st", ".", "Unit", "(", "unit", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "st", ".", "queryMetricBatches", "(", "bson", ".", "M", "{", "\"", "\"", ":", "unit", "}", ")", "\n", "}" ]
// MetricBatchesForUnit returns metric batches for the given unit.
[ "MetricBatchesForUnit", "returns", "metric", "batches", "for", "the", "given", "unit", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/metrics.go#L290-L296
3,736
juju/juju
state/metrics.go
MetricBatchesForModel
func (st *State) MetricBatchesForModel() ([]MetricBatch, error) { return st.queryMetricBatches(bson.M{"model-uuid": st.ModelUUID()}) }
go
func (st *State) MetricBatchesForModel() ([]MetricBatch, error) { return st.queryMetricBatches(bson.M{"model-uuid": st.ModelUUID()}) }
[ "func", "(", "st", "*", "State", ")", "MetricBatchesForModel", "(", ")", "(", "[", "]", "MetricBatch", ",", "error", ")", "{", "return", "st", ".", "queryMetricBatches", "(", "bson", ".", "M", "{", "\"", "\"", ":", "st", ".", "ModelUUID", "(", ")", "}", ")", "\n", "}" ]
// MetricBatchesForModel returns metric batches for all the units in the model.
[ "MetricBatchesForModel", "returns", "metric", "batches", "for", "all", "the", "units", "in", "the", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/metrics.go#L299-L301
3,737
juju/juju
state/metrics.go
MetricBatchesForApplication
func (st *State) MetricBatchesForApplication(application string) ([]MetricBatch, error) { app, err := st.Application(application) if err != nil { return nil, errors.Trace(err) } units, err := app.AllUnits() if err != nil { return nil, errors.Trace(err) } unitNames := make([]bson.M, len(units)) for i, u := range units { unitNames[i] = bson.M{"unit": u.Name()} } return st.queryMetricBatches(bson.M{"$or": unitNames}) }
go
func (st *State) MetricBatchesForApplication(application string) ([]MetricBatch, error) { app, err := st.Application(application) if err != nil { return nil, errors.Trace(err) } units, err := app.AllUnits() if err != nil { return nil, errors.Trace(err) } unitNames := make([]bson.M, len(units)) for i, u := range units { unitNames[i] = bson.M{"unit": u.Name()} } return st.queryMetricBatches(bson.M{"$or": unitNames}) }
[ "func", "(", "st", "*", "State", ")", "MetricBatchesForApplication", "(", "application", "string", ")", "(", "[", "]", "MetricBatch", ",", "error", ")", "{", "app", ",", "err", ":=", "st", ".", "Application", "(", "application", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "units", ",", "err", ":=", "app", ".", "AllUnits", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "unitNames", ":=", "make", "(", "[", "]", "bson", ".", "M", ",", "len", "(", "units", ")", ")", "\n", "for", "i", ",", "u", ":=", "range", "units", "{", "unitNames", "[", "i", "]", "=", "bson", ".", "M", "{", "\"", "\"", ":", "u", ".", "Name", "(", ")", "}", "\n", "}", "\n", "return", "st", ".", "queryMetricBatches", "(", "bson", ".", "M", "{", "\"", "\"", ":", "unitNames", "}", ")", "\n", "}" ]
// MetricBatchesForApplication returns metric batches for the given application.
[ "MetricBatchesForApplication", "returns", "metric", "batches", "for", "the", "given", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/metrics.go#L304-L318
3,738
juju/juju
state/metrics.go
MetricBatch
func (st *State) MetricBatch(id string) (*MetricBatch, error) { c, closer := st.db().GetCollection(metricsC) defer closer() doc := metricBatchDoc{} err := c.Find(bson.M{"_id": id}).One(&doc) if err == mgo.ErrNotFound { return nil, errors.NotFoundf("metric %v", id) } if err != nil { return nil, err } return &MetricBatch{st: st, doc: doc}, nil }
go
func (st *State) MetricBatch(id string) (*MetricBatch, error) { c, closer := st.db().GetCollection(metricsC) defer closer() doc := metricBatchDoc{} err := c.Find(bson.M{"_id": id}).One(&doc) if err == mgo.ErrNotFound { return nil, errors.NotFoundf("metric %v", id) } if err != nil { return nil, err } return &MetricBatch{st: st, doc: doc}, nil }
[ "func", "(", "st", "*", "State", ")", "MetricBatch", "(", "id", "string", ")", "(", "*", "MetricBatch", ",", "error", ")", "{", "c", ",", "closer", ":=", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "metricsC", ")", "\n", "defer", "closer", "(", ")", "\n", "doc", ":=", "metricBatchDoc", "{", "}", "\n", "err", ":=", "c", ".", "Find", "(", "bson", ".", "M", "{", "\"", "\"", ":", "id", "}", ")", ".", "One", "(", "&", "doc", ")", "\n", "if", "err", "==", "mgo", ".", "ErrNotFound", "{", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "id", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "MetricBatch", "{", "st", ":", "st", ",", "doc", ":", "doc", "}", ",", "nil", "\n", "}" ]
// MetricBatch returns the metric batch with the given id.
[ "MetricBatch", "returns", "the", "metric", "batch", "with", "the", "given", "id", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/metrics.go#L321-L333
3,739
juju/juju
state/metrics.go
MetricsToSend
func (st *State) MetricsToSend(batchSize int) ([]*MetricBatch, error) { var docs []metricBatchDoc c, closer := st.db().GetCollection(metricsC) defer closer() q := bson.M{ "model-uuid": st.ModelUUID(), "sent": false, } err := c.Find(q).Limit(batchSize).All(&docs) if err != nil { return nil, errors.Trace(err) } batch := make([]*MetricBatch, len(docs)) for i, doc := range docs { batch[i] = &MetricBatch{st: st, doc: doc} } return batch, nil }
go
func (st *State) MetricsToSend(batchSize int) ([]*MetricBatch, error) { var docs []metricBatchDoc c, closer := st.db().GetCollection(metricsC) defer closer() q := bson.M{ "model-uuid": st.ModelUUID(), "sent": false, } err := c.Find(q).Limit(batchSize).All(&docs) if err != nil { return nil, errors.Trace(err) } batch := make([]*MetricBatch, len(docs)) for i, doc := range docs { batch[i] = &MetricBatch{st: st, doc: doc} } return batch, nil }
[ "func", "(", "st", "*", "State", ")", "MetricsToSend", "(", "batchSize", "int", ")", "(", "[", "]", "*", "MetricBatch", ",", "error", ")", "{", "var", "docs", "[", "]", "metricBatchDoc", "\n", "c", ",", "closer", ":=", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "metricsC", ")", "\n", "defer", "closer", "(", ")", "\n\n", "q", ":=", "bson", ".", "M", "{", "\"", "\"", ":", "st", ".", "ModelUUID", "(", ")", ",", "\"", "\"", ":", "false", ",", "}", "\n", "err", ":=", "c", ".", "Find", "(", "q", ")", ".", "Limit", "(", "batchSize", ")", ".", "All", "(", "&", "docs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "batch", ":=", "make", "(", "[", "]", "*", "MetricBatch", ",", "len", "(", "docs", ")", ")", "\n", "for", "i", ",", "doc", ":=", "range", "docs", "{", "batch", "[", "i", "]", "=", "&", "MetricBatch", "{", "st", ":", "st", ",", "doc", ":", "doc", "}", "\n\n", "}", "\n\n", "return", "batch", ",", "nil", "\n", "}" ]
// MetricsToSend returns batchSize metrics that need to be sent // to the collector
[ "MetricsToSend", "returns", "batchSize", "metrics", "that", "need", "to", "be", "sent", "to", "the", "collector" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/metrics.go#L359-L380
3,740
juju/juju
state/metrics.go
CountOfUnsentMetrics
func (st *State) CountOfUnsentMetrics() (int, error) { c, closer := st.db().GetCollection(metricsC) defer closer() return c.Find(bson.M{ "model-uuid": st.ModelUUID(), "sent": false, }).Count() }
go
func (st *State) CountOfUnsentMetrics() (int, error) { c, closer := st.db().GetCollection(metricsC) defer closer() return c.Find(bson.M{ "model-uuid": st.ModelUUID(), "sent": false, }).Count() }
[ "func", "(", "st", "*", "State", ")", "CountOfUnsentMetrics", "(", ")", "(", "int", ",", "error", ")", "{", "c", ",", "closer", ":=", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "metricsC", ")", "\n", "defer", "closer", "(", ")", "\n", "return", "c", ".", "Find", "(", "bson", ".", "M", "{", "\"", "\"", ":", "st", ".", "ModelUUID", "(", ")", ",", "\"", "\"", ":", "false", ",", "}", ")", ".", "Count", "(", ")", "\n", "}" ]
// CountOfUnsentMetrics returns the number of metrics that // haven't been sent to the collection service.
[ "CountOfUnsentMetrics", "returns", "the", "number", "of", "metrics", "that", "haven", "t", "been", "sent", "to", "the", "collection", "service", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/metrics.go#L384-L391
3,741
juju/juju
state/metrics.go
CountOfSentMetrics
func (st *State) CountOfSentMetrics() (int, error) { c, closer := st.db().GetCollection(metricsC) defer closer() return c.Find(bson.M{ "model-uuid": st.ModelUUID(), "sent": true, }).Count() }
go
func (st *State) CountOfSentMetrics() (int, error) { c, closer := st.db().GetCollection(metricsC) defer closer() return c.Find(bson.M{ "model-uuid": st.ModelUUID(), "sent": true, }).Count() }
[ "func", "(", "st", "*", "State", ")", "CountOfSentMetrics", "(", ")", "(", "int", ",", "error", ")", "{", "c", ",", "closer", ":=", "st", ".", "db", "(", ")", ".", "GetCollection", "(", "metricsC", ")", "\n", "defer", "closer", "(", ")", "\n", "return", "c", ".", "Find", "(", "bson", ".", "M", "{", "\"", "\"", ":", "st", ".", "ModelUUID", "(", ")", ",", "\"", "\"", ":", "true", ",", "}", ")", ".", "Count", "(", ")", "\n", "}" ]
// CountOfSentMetrics returns the number of metrics that // have been sent to the collection service and have not // been removed by the cleanup worker.
[ "CountOfSentMetrics", "returns", "the", "number", "of", "metrics", "that", "have", "been", "sent", "to", "the", "collection", "service", "and", "have", "not", "been", "removed", "by", "the", "cleanup", "worker", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/metrics.go#L396-L403
3,742
juju/juju
state/metrics.go
Metrics
func (m *MetricBatch) Metrics() []Metric { result := make([]Metric, len(m.doc.Metrics)) copy(result, m.doc.Metrics) return result }
go
func (m *MetricBatch) Metrics() []Metric { result := make([]Metric, len(m.doc.Metrics)) copy(result, m.doc.Metrics) return result }
[ "func", "(", "m", "*", "MetricBatch", ")", "Metrics", "(", ")", "[", "]", "Metric", "{", "result", ":=", "make", "(", "[", "]", "Metric", ",", "len", "(", "m", ".", "doc", ".", "Metrics", ")", ")", "\n", "copy", "(", "result", ",", "m", ".", "doc", ".", "Metrics", ")", "\n", "return", "result", "\n", "}" ]
// Metrics returns the metrics in this batch.
[ "Metrics", "returns", "the", "metrics", "in", "this", "batch", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/metrics.go#L443-L447
3,743
juju/juju
state/metrics.go
UniqueMetrics
func (m *MetricBatch) UniqueMetrics() []Metric { metrics := m.Metrics() sort.Sort(byTime(metrics)) uniq := map[string]Metric{} for _, m := range metrics { uniq[fmt.Sprintf("%s-%s", m.Key, labelsKey(m.Labels))] = m } results := make([]Metric, len(uniq)) i := 0 for _, m := range uniq { results[i] = m i++ } sort.Sort(byKey(results)) return results }
go
func (m *MetricBatch) UniqueMetrics() []Metric { metrics := m.Metrics() sort.Sort(byTime(metrics)) uniq := map[string]Metric{} for _, m := range metrics { uniq[fmt.Sprintf("%s-%s", m.Key, labelsKey(m.Labels))] = m } results := make([]Metric, len(uniq)) i := 0 for _, m := range uniq { results[i] = m i++ } sort.Sort(byKey(results)) return results }
[ "func", "(", "m", "*", "MetricBatch", ")", "UniqueMetrics", "(", ")", "[", "]", "Metric", "{", "metrics", ":=", "m", ".", "Metrics", "(", ")", "\n", "sort", ".", "Sort", "(", "byTime", "(", "metrics", ")", ")", "\n", "uniq", ":=", "map", "[", "string", "]", "Metric", "{", "}", "\n", "for", "_", ",", "m", ":=", "range", "metrics", "{", "uniq", "[", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "m", ".", "Key", ",", "labelsKey", "(", "m", ".", "Labels", ")", ")", "]", "=", "m", "\n", "}", "\n", "results", ":=", "make", "(", "[", "]", "Metric", ",", "len", "(", "uniq", ")", ")", "\n", "i", ":=", "0", "\n", "for", "_", ",", "m", ":=", "range", "uniq", "{", "results", "[", "i", "]", "=", "m", "\n", "i", "++", "\n", "}", "\n", "sort", ".", "Sort", "(", "byKey", "(", "results", ")", ")", "\n", "return", "results", "\n", "}" ]
// UniqueMetrics returns only the last value for each // metric key in this batch.
[ "UniqueMetrics", "returns", "only", "the", "last", "value", "for", "each", "metric", "key", "in", "this", "batch", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/metrics.go#L451-L466
3,744
juju/juju
state/metrics.go
SetSent
func (m *MetricBatch) SetSent(t time.Time) error { deleteTime := t.UTC().Add(CleanupAge) ops := setSentOps([]string{m.UUID()}, deleteTime) if err := m.st.db().RunTransaction(ops); err != nil { return errors.Annotatef(err, "cannot set metric sent for metric %q", m.UUID()) } m.doc.Sent = true m.doc.DeleteTime = deleteTime return nil }
go
func (m *MetricBatch) SetSent(t time.Time) error { deleteTime := t.UTC().Add(CleanupAge) ops := setSentOps([]string{m.UUID()}, deleteTime) if err := m.st.db().RunTransaction(ops); err != nil { return errors.Annotatef(err, "cannot set metric sent for metric %q", m.UUID()) } m.doc.Sent = true m.doc.DeleteTime = deleteTime return nil }
[ "func", "(", "m", "*", "MetricBatch", ")", "SetSent", "(", "t", "time", ".", "Time", ")", "error", "{", "deleteTime", ":=", "t", ".", "UTC", "(", ")", ".", "Add", "(", "CleanupAge", ")", "\n", "ops", ":=", "setSentOps", "(", "[", "]", "string", "{", "m", ".", "UUID", "(", ")", "}", ",", "deleteTime", ")", "\n", "if", "err", ":=", "m", ".", "st", ".", "db", "(", ")", ".", "RunTransaction", "(", "ops", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "m", ".", "UUID", "(", ")", ")", "\n", "}", "\n\n", "m", ".", "doc", ".", "Sent", "=", "true", "\n", "m", ".", "doc", ".", "DeleteTime", "=", "deleteTime", "\n", "return", "nil", "\n", "}" ]
// SetSent marks the metric has having been sent at // the specified time.
[ "SetSent", "marks", "the", "metric", "has", "having", "been", "sent", "at", "the", "specified", "time", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/metrics.go#L470-L480
3,745
juju/juju
state/metrics.go
SetMetricBatchesSent
func (st *State) SetMetricBatchesSent(batchUUIDs []string) error { deleteTime := st.clock().Now().UTC().Add(CleanupAge) ops := setSentOps(batchUUIDs, deleteTime) if err := st.db().RunTransaction(ops); err != nil { return errors.Annotatef(err, "cannot set metric sent in bulk call") } return nil }
go
func (st *State) SetMetricBatchesSent(batchUUIDs []string) error { deleteTime := st.clock().Now().UTC().Add(CleanupAge) ops := setSentOps(batchUUIDs, deleteTime) if err := st.db().RunTransaction(ops); err != nil { return errors.Annotatef(err, "cannot set metric sent in bulk call") } return nil }
[ "func", "(", "st", "*", "State", ")", "SetMetricBatchesSent", "(", "batchUUIDs", "[", "]", "string", ")", "error", "{", "deleteTime", ":=", "st", ".", "clock", "(", ")", ".", "Now", "(", ")", ".", "UTC", "(", ")", ".", "Add", "(", "CleanupAge", ")", "\n", "ops", ":=", "setSentOps", "(", "batchUUIDs", ",", "deleteTime", ")", "\n", "if", "err", ":=", "st", ".", "db", "(", ")", ".", "RunTransaction", "(", "ops", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetMetricBatchesSent sets sent on each MetricBatch corresponding to the uuids provided.
[ "SetMetricBatchesSent", "sets", "sent", "on", "each", "MetricBatch", "corresponding", "to", "the", "uuids", "provided", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/metrics.go#L506-L513
3,746
juju/juju
worker/uniter/runner/jujuc/action-set.go
NewActionSetCommand
func NewActionSetCommand(ctx Context) (cmd.Command, error) { return &ActionSetCommand{ctx: ctx}, nil }
go
func NewActionSetCommand(ctx Context) (cmd.Command, error) { return &ActionSetCommand{ctx: ctx}, nil }
[ "func", "NewActionSetCommand", "(", "ctx", "Context", ")", "(", "cmd", ".", "Command", ",", "error", ")", "{", "return", "&", "ActionSetCommand", "{", "ctx", ":", "ctx", "}", ",", "nil", "\n", "}" ]
// NewActionSetCommand returns a new ActionSetCommand with the given context.
[ "NewActionSetCommand", "returns", "a", "new", "ActionSetCommand", "with", "the", "given", "context", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/jujuc/action-set.go#L27-L29
3,747
juju/juju
core/cache/hash.go
hash
func hash(settings map[string]interface{}) (string, error) { bytes, err := yaml.Marshal(settings) if err != nil { return "", errors.Trace(err) } hash := sha256.New() _, err = hash.Write(bytes) if err != nil { return "", errors.Trace(err) } return hex.EncodeToString(hash.Sum(nil)), nil }
go
func hash(settings map[string]interface{}) (string, error) { bytes, err := yaml.Marshal(settings) if err != nil { return "", errors.Trace(err) } hash := sha256.New() _, err = hash.Write(bytes) if err != nil { return "", errors.Trace(err) } return hex.EncodeToString(hash.Sum(nil)), nil }
[ "func", "hash", "(", "settings", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "string", ",", "error", ")", "{", "bytes", ",", "err", ":=", "yaml", ".", "Marshal", "(", "settings", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "hash", ":=", "sha256", ".", "New", "(", ")", "\n", "_", ",", "err", "=", "hash", ".", "Write", "(", "bytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "hex", ".", "EncodeToString", "(", "hash", ".", "Sum", "(", "nil", ")", ")", ",", "nil", "\n", "}" ]
// hash returns a hash of the yaml serialized settings. // If the settings are not able to be serialized an error is returned.
[ "hash", "returns", "a", "hash", "of", "the", "yaml", "serialized", "settings", ".", "If", "the", "settings", "are", "not", "able", "to", "be", "serialized", "an", "error", "is", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/cache/hash.go#L99-L110
3,748
juju/juju
api/controller/controller.go
NewClient
func NewClient(st base.APICallCloser) *Client { frontend, backend := base.NewClientFacade(st, "Controller") return &Client{ ClientFacade: frontend, facade: backend, ControllerConfigAPI: common.NewControllerConfig(backend), ModelStatusAPI: common.NewModelStatusAPI(backend), } }
go
func NewClient(st base.APICallCloser) *Client { frontend, backend := base.NewClientFacade(st, "Controller") return &Client{ ClientFacade: frontend, facade: backend, ControllerConfigAPI: common.NewControllerConfig(backend), ModelStatusAPI: common.NewModelStatusAPI(backend), } }
[ "func", "NewClient", "(", "st", "base", ".", "APICallCloser", ")", "*", "Client", "{", "frontend", ",", "backend", ":=", "base", ".", "NewClientFacade", "(", "st", ",", "\"", "\"", ")", "\n", "return", "&", "Client", "{", "ClientFacade", ":", "frontend", ",", "facade", ":", "backend", ",", "ControllerConfigAPI", ":", "common", ".", "NewControllerConfig", "(", "backend", ")", ",", "ModelStatusAPI", ":", "common", ".", "NewModelStatusAPI", "(", "backend", ")", ",", "}", "\n", "}" ]
// NewClient creates a new `Client` based on an existing authenticated API // connection.
[ "NewClient", "creates", "a", "new", "Client", "based", "on", "an", "existing", "authenticated", "API", "connection", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/controller/controller.go#L35-L43
3,749
juju/juju
api/controller/controller.go
CloudSpec
func (c *Client) CloudSpec(modelTag names.ModelTag) (environs.CloudSpec, error) { api := cloudspec.NewCloudSpecAPI(c.facade, modelTag) return api.CloudSpec() }
go
func (c *Client) CloudSpec(modelTag names.ModelTag) (environs.CloudSpec, error) { api := cloudspec.NewCloudSpecAPI(c.facade, modelTag) return api.CloudSpec() }
[ "func", "(", "c", "*", "Client", ")", "CloudSpec", "(", "modelTag", "names", ".", "ModelTag", ")", "(", "environs", ".", "CloudSpec", ",", "error", ")", "{", "api", ":=", "cloudspec", ".", "NewCloudSpecAPI", "(", "c", ".", "facade", ",", "modelTag", ")", "\n", "return", "api", ".", "CloudSpec", "(", ")", "\n", "}" ]
// CloudSpec returns a CloudSpec for the specified model.
[ "CloudSpec", "returns", "a", "CloudSpec", "for", "the", "specified", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/controller/controller.go#L75-L78
3,750
juju/juju
api/controller/controller.go
HostedModelConfigs
func (c *Client) HostedModelConfigs() ([]HostedConfig, error) { result := params.HostedModelConfigsResults{} err := c.facade.FacadeCall("HostedModelConfigs", nil, &result) if err != nil { return nil, errors.Trace(err) } // If we get to here, we have some values. Each value may or // may not have an error, but it should at least have a name // and owner. hostedConfigs := make([]HostedConfig, len(result.Models)) for i, modelConfig := range result.Models { hostedConfigs[i].Name = modelConfig.Name tag, err := names.ParseUserTag(modelConfig.OwnerTag) if err != nil { hostedConfigs[i].Error = errors.Trace(err) continue } hostedConfigs[i].Owner = tag if modelConfig.Error != nil { hostedConfigs[i].Error = errors.Trace(modelConfig.Error) continue } hostedConfigs[i].Config = modelConfig.Config spec, err := c.MakeCloudSpec(modelConfig.CloudSpec) if err != nil { hostedConfigs[i].Error = errors.Trace(err) continue } hostedConfigs[i].CloudSpec = spec } return hostedConfigs, err }
go
func (c *Client) HostedModelConfigs() ([]HostedConfig, error) { result := params.HostedModelConfigsResults{} err := c.facade.FacadeCall("HostedModelConfigs", nil, &result) if err != nil { return nil, errors.Trace(err) } // If we get to here, we have some values. Each value may or // may not have an error, but it should at least have a name // and owner. hostedConfigs := make([]HostedConfig, len(result.Models)) for i, modelConfig := range result.Models { hostedConfigs[i].Name = modelConfig.Name tag, err := names.ParseUserTag(modelConfig.OwnerTag) if err != nil { hostedConfigs[i].Error = errors.Trace(err) continue } hostedConfigs[i].Owner = tag if modelConfig.Error != nil { hostedConfigs[i].Error = errors.Trace(modelConfig.Error) continue } hostedConfigs[i].Config = modelConfig.Config spec, err := c.MakeCloudSpec(modelConfig.CloudSpec) if err != nil { hostedConfigs[i].Error = errors.Trace(err) continue } hostedConfigs[i].CloudSpec = spec } return hostedConfigs, err }
[ "func", "(", "c", "*", "Client", ")", "HostedModelConfigs", "(", ")", "(", "[", "]", "HostedConfig", ",", "error", ")", "{", "result", ":=", "params", ".", "HostedModelConfigsResults", "{", "}", "\n", "err", ":=", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "nil", ",", "&", "result", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "// If we get to here, we have some values. Each value may or", "// may not have an error, but it should at least have a name", "// and owner.", "hostedConfigs", ":=", "make", "(", "[", "]", "HostedConfig", ",", "len", "(", "result", ".", "Models", ")", ")", "\n", "for", "i", ",", "modelConfig", ":=", "range", "result", ".", "Models", "{", "hostedConfigs", "[", "i", "]", ".", "Name", "=", "modelConfig", ".", "Name", "\n", "tag", ",", "err", ":=", "names", ".", "ParseUserTag", "(", "modelConfig", ".", "OwnerTag", ")", "\n", "if", "err", "!=", "nil", "{", "hostedConfigs", "[", "i", "]", ".", "Error", "=", "errors", ".", "Trace", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "hostedConfigs", "[", "i", "]", ".", "Owner", "=", "tag", "\n", "if", "modelConfig", ".", "Error", "!=", "nil", "{", "hostedConfigs", "[", "i", "]", ".", "Error", "=", "errors", ".", "Trace", "(", "modelConfig", ".", "Error", ")", "\n", "continue", "\n", "}", "\n", "hostedConfigs", "[", "i", "]", ".", "Config", "=", "modelConfig", ".", "Config", "\n", "spec", ",", "err", ":=", "c", ".", "MakeCloudSpec", "(", "modelConfig", ".", "CloudSpec", ")", "\n", "if", "err", "!=", "nil", "{", "hostedConfigs", "[", "i", "]", ".", "Error", "=", "errors", ".", "Trace", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "hostedConfigs", "[", "i", "]", ".", "CloudSpec", "=", "spec", "\n", "}", "\n", "return", "hostedConfigs", ",", "err", "\n", "}" ]
// HostedModelsConfig returns all model settings for the // controller model.
[ "HostedModelsConfig", "returns", "all", "model", "settings", "for", "the", "controller", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/controller/controller.go#L104-L135
3,751
juju/juju
api/controller/controller.go
DestroyController
func (c *Client) DestroyController(args DestroyControllerParams) error { if c.BestAPIVersion() < 4 { if args.DestroyStorage == nil || !*args.DestroyStorage { return errors.New("this Juju controller requires DestroyStorage to be true") } args.DestroyStorage = nil } return c.facade.FacadeCall("DestroyController", params.DestroyControllerArgs{ DestroyModels: args.DestroyModels, DestroyStorage: args.DestroyStorage, }, nil) }
go
func (c *Client) DestroyController(args DestroyControllerParams) error { if c.BestAPIVersion() < 4 { if args.DestroyStorage == nil || !*args.DestroyStorage { return errors.New("this Juju controller requires DestroyStorage to be true") } args.DestroyStorage = nil } return c.facade.FacadeCall("DestroyController", params.DestroyControllerArgs{ DestroyModels: args.DestroyModels, DestroyStorage: args.DestroyStorage, }, nil) }
[ "func", "(", "c", "*", "Client", ")", "DestroyController", "(", "args", "DestroyControllerParams", ")", "error", "{", "if", "c", ".", "BestAPIVersion", "(", ")", "<", "4", "{", "if", "args", ".", "DestroyStorage", "==", "nil", "||", "!", "*", "args", ".", "DestroyStorage", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "args", ".", "DestroyStorage", "=", "nil", "\n", "}", "\n", "return", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "params", ".", "DestroyControllerArgs", "{", "DestroyModels", ":", "args", ".", "DestroyModels", ",", "DestroyStorage", ":", "args", ".", "DestroyStorage", ",", "}", ",", "nil", ")", "\n", "}" ]
// DestroyController puts the controller model into a "dying" state, // and removes all non-manager machine instances.
[ "DestroyController", "puts", "the", "controller", "model", "into", "a", "dying", "state", "and", "removes", "all", "non", "-", "manager", "machine", "instances", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/controller/controller.go#L155-L166
3,752
juju/juju
api/controller/controller.go
ListBlockedModels
func (c *Client) ListBlockedModels() ([]params.ModelBlockInfo, error) { result := params.ModelBlockInfoList{} err := c.facade.FacadeCall("ListBlockedModels", nil, &result) return result.Models, err }
go
func (c *Client) ListBlockedModels() ([]params.ModelBlockInfo, error) { result := params.ModelBlockInfoList{} err := c.facade.FacadeCall("ListBlockedModels", nil, &result) return result.Models, err }
[ "func", "(", "c", "*", "Client", ")", "ListBlockedModels", "(", ")", "(", "[", "]", "params", ".", "ModelBlockInfo", ",", "error", ")", "{", "result", ":=", "params", ".", "ModelBlockInfoList", "{", "}", "\n", "err", ":=", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "nil", ",", "&", "result", ")", "\n", "return", "result", ".", "Models", ",", "err", "\n", "}" ]
// ListBlockedModels returns a list of all models within the controller // which have at least one block in place.
[ "ListBlockedModels", "returns", "a", "list", "of", "all", "models", "within", "the", "controller", "which", "have", "at", "least", "one", "block", "in", "place", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/controller/controller.go#L170-L174
3,753
juju/juju
api/controller/controller.go
GrantController
func (c *Client) GrantController(user, access string) error { return c.modifyControllerUser(params.GrantControllerAccess, user, access) }
go
func (c *Client) GrantController(user, access string) error { return c.modifyControllerUser(params.GrantControllerAccess, user, access) }
[ "func", "(", "c", "*", "Client", ")", "GrantController", "(", "user", ",", "access", "string", ")", "error", "{", "return", "c", ".", "modifyControllerUser", "(", "params", ".", "GrantControllerAccess", ",", "user", ",", "access", ")", "\n", "}" ]
// GrantController grants a user access to the controller.
[ "GrantController", "grants", "a", "user", "access", "to", "the", "controller", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/controller/controller.go#L193-L195
3,754
juju/juju
api/controller/controller.go
RevokeController
func (c *Client) RevokeController(user, access string) error { return c.modifyControllerUser(params.RevokeControllerAccess, user, access) }
go
func (c *Client) RevokeController(user, access string) error { return c.modifyControllerUser(params.RevokeControllerAccess, user, access) }
[ "func", "(", "c", "*", "Client", ")", "RevokeController", "(", "user", ",", "access", "string", ")", "error", "{", "return", "c", ".", "modifyControllerUser", "(", "params", ".", "RevokeControllerAccess", ",", "user", ",", "access", ")", "\n", "}" ]
// RevokeController revokes a user's access to the controller.
[ "RevokeController", "revokes", "a", "user", "s", "access", "to", "the", "controller", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/controller/controller.go#L198-L200
3,755
juju/juju
api/controller/controller.go
GetControllerAccess
func (c *Client) GetControllerAccess(user string) (permission.Access, error) { if !names.IsValidUser(user) { return "", errors.Errorf("invalid username: %q", user) } entities := params.Entities{Entities: []params.Entity{{names.NewUserTag(user).String()}}} var results params.UserAccessResults err := c.facade.FacadeCall("GetControllerAccess", entities, &results) if err != nil { return "", errors.Trace(err) } if len(results.Results) != 1 { return "", errors.Errorf("expected 1 result, got %d", len(results.Results)) } if err := results.Results[0].Error; err != nil { return "", errors.Trace(err) } return permission.Access(results.Results[0].Result.Access), nil }
go
func (c *Client) GetControllerAccess(user string) (permission.Access, error) { if !names.IsValidUser(user) { return "", errors.Errorf("invalid username: %q", user) } entities := params.Entities{Entities: []params.Entity{{names.NewUserTag(user).String()}}} var results params.UserAccessResults err := c.facade.FacadeCall("GetControllerAccess", entities, &results) if err != nil { return "", errors.Trace(err) } if len(results.Results) != 1 { return "", errors.Errorf("expected 1 result, got %d", len(results.Results)) } if err := results.Results[0].Error; err != nil { return "", errors.Trace(err) } return permission.Access(results.Results[0].Result.Access), nil }
[ "func", "(", "c", "*", "Client", ")", "GetControllerAccess", "(", "user", "string", ")", "(", "permission", ".", "Access", ",", "error", ")", "{", "if", "!", "names", ".", "IsValidUser", "(", "user", ")", "{", "return", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "user", ")", "\n", "}", "\n", "entities", ":=", "params", ".", "Entities", "{", "Entities", ":", "[", "]", "params", ".", "Entity", "{", "{", "names", ".", "NewUserTag", "(", "user", ")", ".", "String", "(", ")", "}", "}", "}", "\n", "var", "results", "params", ".", "UserAccessResults", "\n", "err", ":=", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "entities", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "results", ".", "Results", ")", "!=", "1", "{", "return", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "results", ".", "Results", ")", ")", "\n", "}", "\n", "if", "err", ":=", "results", ".", "Results", "[", "0", "]", ".", "Error", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "permission", ".", "Access", "(", "results", ".", "Results", "[", "0", "]", ".", "Result", ".", "Access", ")", ",", "nil", "\n", "}" ]
// GetControllerAccess returns the access level the user has on the controller.
[ "GetControllerAccess", "returns", "the", "access", "level", "the", "user", "has", "on", "the", "controller", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/controller/controller.go#L229-L246
3,756
juju/juju
api/controller/controller.go
ConfigSet
func (c *Client) ConfigSet(values map[string]interface{}) error { if c.BestAPIVersion() < 5 { return errors.Errorf("this controller version doesn't support updating controller config") } return errors.Trace( c.facade.FacadeCall("ConfigSet", params.ControllerConfigSet{Config: values}, nil), ) }
go
func (c *Client) ConfigSet(values map[string]interface{}) error { if c.BestAPIVersion() < 5 { return errors.Errorf("this controller version doesn't support updating controller config") } return errors.Trace( c.facade.FacadeCall("ConfigSet", params.ControllerConfigSet{Config: values}, nil), ) }
[ "func", "(", "c", "*", "Client", ")", "ConfigSet", "(", "values", "map", "[", "string", "]", "interface", "{", "}", ")", "error", "{", "if", "c", ".", "BestAPIVersion", "(", ")", "<", "5", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "params", ".", "ControllerConfigSet", "{", "Config", ":", "values", "}", ",", "nil", ")", ",", ")", "\n", "}" ]
// ConfigSet updates the passed controller configuration values. Any // settings that aren't passed will be left with their previous // values.
[ "ConfigSet", "updates", "the", "passed", "controller", "configuration", "values", ".", "Any", "settings", "that", "aren", "t", "passed", "will", "be", "left", "with", "their", "previous", "values", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/controller/controller.go#L251-L258
3,757
juju/juju
api/controller/controller.go
Validate
func (s *MigrationSpec) Validate() error { if !names.IsValidModel(s.ModelUUID) { return errors.NotValidf("model UUID") } if !names.IsValidModel(s.TargetControllerUUID) { return errors.NotValidf("controller UUID") } if len(s.TargetAddrs) < 1 { return errors.NotValidf("empty target API addresses") } if !names.IsValidUser(s.TargetUser) { return errors.NotValidf("target user") } if s.TargetPassword == "" && len(s.TargetMacaroons) == 0 { return errors.NotValidf("missing authentication secrets") } return nil }
go
func (s *MigrationSpec) Validate() error { if !names.IsValidModel(s.ModelUUID) { return errors.NotValidf("model UUID") } if !names.IsValidModel(s.TargetControllerUUID) { return errors.NotValidf("controller UUID") } if len(s.TargetAddrs) < 1 { return errors.NotValidf("empty target API addresses") } if !names.IsValidUser(s.TargetUser) { return errors.NotValidf("target user") } if s.TargetPassword == "" && len(s.TargetMacaroons) == 0 { return errors.NotValidf("missing authentication secrets") } return nil }
[ "func", "(", "s", "*", "MigrationSpec", ")", "Validate", "(", ")", "error", "{", "if", "!", "names", ".", "IsValidModel", "(", "s", ".", "ModelUUID", ")", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "names", ".", "IsValidModel", "(", "s", ".", "TargetControllerUUID", ")", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "s", ".", "TargetAddrs", ")", "<", "1", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "names", ".", "IsValidUser", "(", "s", ".", "TargetUser", ")", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "s", ".", "TargetPassword", "==", "\"", "\"", "&&", "len", "(", "s", ".", "TargetMacaroons", ")", "==", "0", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate performs sanity checks on the migration configuration it // holds.
[ "Validate", "performs", "sanity", "checks", "on", "the", "migration", "configuration", "it", "holds", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/controller/controller.go#L275-L292
3,758
juju/juju
apiserver/facades/agent/uniter/status.go
NewStatusAPI
func NewStatusAPI(st *state.State, getCanModify common.GetAuthFunc, leadershipChecker leadership.Checker) *StatusAPI { // TODO(fwereade): so *all* of these have exactly the same auth // characteristics? I think not. unitSetter := common.NewStatusSetter(st, getCanModify) unitGetter := common.NewStatusGetter(st, getCanModify) applicationSetter := common.NewApplicationStatusSetter(st, getCanModify, leadershipChecker) applicationGetter := common.NewApplicationStatusGetter(st, getCanModify, leadershipChecker) agentSetter := common.NewStatusSetter(&common.UnitAgentFinder{st}, getCanModify) return &StatusAPI{ agentSetter: agentSetter, unitSetter: unitSetter, unitGetter: unitGetter, applicationSetter: applicationSetter, applicationGetter: applicationGetter, getCanModify: getCanModify, } }
go
func NewStatusAPI(st *state.State, getCanModify common.GetAuthFunc, leadershipChecker leadership.Checker) *StatusAPI { // TODO(fwereade): so *all* of these have exactly the same auth // characteristics? I think not. unitSetter := common.NewStatusSetter(st, getCanModify) unitGetter := common.NewStatusGetter(st, getCanModify) applicationSetter := common.NewApplicationStatusSetter(st, getCanModify, leadershipChecker) applicationGetter := common.NewApplicationStatusGetter(st, getCanModify, leadershipChecker) agentSetter := common.NewStatusSetter(&common.UnitAgentFinder{st}, getCanModify) return &StatusAPI{ agentSetter: agentSetter, unitSetter: unitSetter, unitGetter: unitGetter, applicationSetter: applicationSetter, applicationGetter: applicationGetter, getCanModify: getCanModify, } }
[ "func", "NewStatusAPI", "(", "st", "*", "state", ".", "State", ",", "getCanModify", "common", ".", "GetAuthFunc", ",", "leadershipChecker", "leadership", ".", "Checker", ")", "*", "StatusAPI", "{", "// TODO(fwereade): so *all* of these have exactly the same auth", "// characteristics? I think not.", "unitSetter", ":=", "common", ".", "NewStatusSetter", "(", "st", ",", "getCanModify", ")", "\n", "unitGetter", ":=", "common", ".", "NewStatusGetter", "(", "st", ",", "getCanModify", ")", "\n", "applicationSetter", ":=", "common", ".", "NewApplicationStatusSetter", "(", "st", ",", "getCanModify", ",", "leadershipChecker", ")", "\n", "applicationGetter", ":=", "common", ".", "NewApplicationStatusGetter", "(", "st", ",", "getCanModify", ",", "leadershipChecker", ")", "\n", "agentSetter", ":=", "common", ".", "NewStatusSetter", "(", "&", "common", ".", "UnitAgentFinder", "{", "st", "}", ",", "getCanModify", ")", "\n", "return", "&", "StatusAPI", "{", "agentSetter", ":", "agentSetter", ",", "unitSetter", ":", "unitSetter", ",", "unitGetter", ":", "unitGetter", ",", "applicationSetter", ":", "applicationSetter", ",", "applicationGetter", ":", "applicationGetter", ",", "getCanModify", ":", "getCanModify", ",", "}", "\n", "}" ]
// NewStatusAPI creates a new server-side Status setter API facade.
[ "NewStatusAPI", "creates", "a", "new", "server", "-", "side", "Status", "setter", "API", "facade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/uniter/status.go#L26-L42
3,759
juju/juju
apiserver/facades/agent/uniter/status.go
SetStatus
func (s *StatusAPI) SetStatus(args params.SetStatus) (params.ErrorResults, error) { return s.SetAgentStatus(args) }
go
func (s *StatusAPI) SetStatus(args params.SetStatus) (params.ErrorResults, error) { return s.SetAgentStatus(args) }
[ "func", "(", "s", "*", "StatusAPI", ")", "SetStatus", "(", "args", "params", ".", "SetStatus", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "return", "s", ".", "SetAgentStatus", "(", "args", ")", "\n", "}" ]
// SetStatus will set status for a entities passed in args. If the entity is // a Unit it will instead set status to its agent, to emulate backwards // compatibility.
[ "SetStatus", "will", "set", "status", "for", "a", "entities", "passed", "in", "args", ".", "If", "the", "entity", "is", "a", "Unit", "it", "will", "instead", "set", "status", "to", "its", "agent", "to", "emulate", "backwards", "compatibility", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/uniter/status.go#L47-L49
3,760
juju/juju
apiserver/facades/agent/uniter/status.go
SetUnitStatus
func (s *StatusAPI) SetUnitStatus(args params.SetStatus) (params.ErrorResults, error) { return s.unitSetter.SetStatus(args) }
go
func (s *StatusAPI) SetUnitStatus(args params.SetStatus) (params.ErrorResults, error) { return s.unitSetter.SetStatus(args) }
[ "func", "(", "s", "*", "StatusAPI", ")", "SetUnitStatus", "(", "args", "params", ".", "SetStatus", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "return", "s", ".", "unitSetter", ".", "SetStatus", "(", "args", ")", "\n", "}" ]
// SetUnitStatus sets status for all elements passed in args, the difference // with SetStatus is that if an entity is a Unit it will set its status instead // of its agent.
[ "SetUnitStatus", "sets", "status", "for", "all", "elements", "passed", "in", "args", "the", "difference", "with", "SetStatus", "is", "that", "if", "an", "entity", "is", "a", "Unit", "it", "will", "set", "its", "status", "instead", "of", "its", "agent", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/uniter/status.go#L60-L62
3,761
juju/juju
apiserver/facades/agent/uniter/status.go
SetApplicationStatus
func (s *StatusAPI) SetApplicationStatus(args params.SetStatus) (params.ErrorResults, error) { return s.applicationSetter.SetStatus(args) }
go
func (s *StatusAPI) SetApplicationStatus(args params.SetStatus) (params.ErrorResults, error) { return s.applicationSetter.SetStatus(args) }
[ "func", "(", "s", "*", "StatusAPI", ")", "SetApplicationStatus", "(", "args", "params", ".", "SetStatus", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "return", "s", ".", "applicationSetter", ".", "SetStatus", "(", "args", ")", "\n", "}" ]
// SetApplicationStatus sets the status for all the Applications in args if the given Unit is // the leader.
[ "SetApplicationStatus", "sets", "the", "status", "for", "all", "the", "Applications", "in", "args", "if", "the", "given", "Unit", "is", "the", "leader", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/uniter/status.go#L66-L68
3,762
juju/juju
apiserver/facades/agent/uniter/status.go
UnitStatus
func (s *StatusAPI) UnitStatus(args params.Entities) (params.StatusResults, error) { return s.unitGetter.Status(args) }
go
func (s *StatusAPI) UnitStatus(args params.Entities) (params.StatusResults, error) { return s.unitGetter.Status(args) }
[ "func", "(", "s", "*", "StatusAPI", ")", "UnitStatus", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "StatusResults", ",", "error", ")", "{", "return", "s", ".", "unitGetter", ".", "Status", "(", "args", ")", "\n", "}" ]
// UnitStatus returns the workload status information for the unit.
[ "UnitStatus", "returns", "the", "workload", "status", "information", "for", "the", "unit", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/uniter/status.go#L71-L73
3,763
juju/juju
apiserver/facades/agent/uniter/status.go
ApplicationStatus
func (s *StatusAPI) ApplicationStatus(args params.Entities) (params.ApplicationStatusResults, error) { return s.applicationGetter.Status(args) }
go
func (s *StatusAPI) ApplicationStatus(args params.Entities) (params.ApplicationStatusResults, error) { return s.applicationGetter.Status(args) }
[ "func", "(", "s", "*", "StatusAPI", ")", "ApplicationStatus", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "ApplicationStatusResults", ",", "error", ")", "{", "return", "s", ".", "applicationGetter", ".", "Status", "(", "args", ")", "\n", "}" ]
// ApplicationStatus returns the status of the Applications and its workloads // if the given unit is the leader.
[ "ApplicationStatus", "returns", "the", "status", "of", "the", "Applications", "and", "its", "workloads", "if", "the", "given", "unit", "is", "the", "leader", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/uniter/status.go#L77-L79
3,764
juju/juju
cmd/juju/firewall/listformatter.go
formatFirewallRulesTabular
func formatFirewallRulesTabular(writer io.Writer, rules firewallRules) { tw := output.TabWriter(writer) w := output.Wrapper{tw} sort.Sort(rules) w.Println("Service", "Whitelist subnets") for _, rule := range rules { w.Println(rule.KnownService, strings.Join(rule.WhitelistCIDRS, ",")) } tw.Flush() }
go
func formatFirewallRulesTabular(writer io.Writer, rules firewallRules) { tw := output.TabWriter(writer) w := output.Wrapper{tw} sort.Sort(rules) w.Println("Service", "Whitelist subnets") for _, rule := range rules { w.Println(rule.KnownService, strings.Join(rule.WhitelistCIDRS, ",")) } tw.Flush() }
[ "func", "formatFirewallRulesTabular", "(", "writer", "io", ".", "Writer", ",", "rules", "firewallRules", ")", "{", "tw", ":=", "output", ".", "TabWriter", "(", "writer", ")", "\n", "w", ":=", "output", ".", "Wrapper", "{", "tw", "}", "\n\n", "sort", ".", "Sort", "(", "rules", ")", "\n\n", "w", ".", "Println", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "for", "_", ",", "rule", ":=", "range", "rules", "{", "w", ".", "Println", "(", "rule", ".", "KnownService", ",", "strings", ".", "Join", "(", "rule", ".", "WhitelistCIDRS", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "tw", ".", "Flush", "(", ")", "\n", "}" ]
// formatFirewallRulesTabular returns a tabular summary of firewall rules.
[ "formatFirewallRulesTabular", "returns", "a", "tabular", "summary", "of", "firewall", "rules", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/firewall/listformatter.go#L39-L50
3,765
juju/juju
worker/raft/synclogstore.go
FirstIndex
func (s *syncLogStore) FirstIndex() (uint64, error) { s.mu.Lock() defer s.mu.Unlock() return s.store.FirstIndex() }
go
func (s *syncLogStore) FirstIndex() (uint64, error) { s.mu.Lock() defer s.mu.Unlock() return s.store.FirstIndex() }
[ "func", "(", "s", "*", "syncLogStore", ")", "FirstIndex", "(", ")", "(", "uint64", ",", "error", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "store", ".", "FirstIndex", "(", ")", "\n", "}" ]
// FirstIndex is part of raft.LogStore.
[ "FirstIndex", "is", "part", "of", "raft", ".", "LogStore", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/raft/synclogstore.go#L31-L35
3,766
juju/juju
worker/raft/synclogstore.go
GetLog
func (s *syncLogStore) GetLog(index uint64, log *raft.Log) error { s.mu.Lock() defer s.mu.Unlock() return s.store.GetLog(index, log) }
go
func (s *syncLogStore) GetLog(index uint64, log *raft.Log) error { s.mu.Lock() defer s.mu.Unlock() return s.store.GetLog(index, log) }
[ "func", "(", "s", "*", "syncLogStore", ")", "GetLog", "(", "index", "uint64", ",", "log", "*", "raft", ".", "Log", ")", "error", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "store", ".", "GetLog", "(", "index", ",", "log", ")", "\n", "}" ]
// GetLog is part of raft.LogStore.
[ "GetLog", "is", "part", "of", "raft", ".", "LogStore", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/raft/synclogstore.go#L45-L49
3,767
juju/juju
worker/raft/synclogstore.go
StoreLog
func (s *syncLogStore) StoreLog(log *raft.Log) error { s.mu.Lock() defer s.mu.Unlock() return s.store.StoreLog(log) }
go
func (s *syncLogStore) StoreLog(log *raft.Log) error { s.mu.Lock() defer s.mu.Unlock() return s.store.StoreLog(log) }
[ "func", "(", "s", "*", "syncLogStore", ")", "StoreLog", "(", "log", "*", "raft", ".", "Log", ")", "error", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "store", ".", "StoreLog", "(", "log", ")", "\n", "}" ]
// StoreLog is part of raft.LogStore.
[ "StoreLog", "is", "part", "of", "raft", ".", "LogStore", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/raft/synclogstore.go#L52-L56
3,768
juju/juju
worker/raft/synclogstore.go
StoreLogs
func (s *syncLogStore) StoreLogs(logs []*raft.Log) error { s.mu.Lock() defer s.mu.Unlock() return s.store.StoreLogs(logs) }
go
func (s *syncLogStore) StoreLogs(logs []*raft.Log) error { s.mu.Lock() defer s.mu.Unlock() return s.store.StoreLogs(logs) }
[ "func", "(", "s", "*", "syncLogStore", ")", "StoreLogs", "(", "logs", "[", "]", "*", "raft", ".", "Log", ")", "error", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "store", ".", "StoreLogs", "(", "logs", ")", "\n", "}" ]
// StoreLogs is part of raft.LogStore.
[ "StoreLogs", "is", "part", "of", "raft", ".", "LogStore", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/raft/synclogstore.go#L59-L63
3,769
juju/juju
worker/raft/synclogstore.go
DeleteRange
func (s *syncLogStore) DeleteRange(min, max uint64) error { s.mu.Lock() defer s.mu.Unlock() return s.store.DeleteRange(min, max) }
go
func (s *syncLogStore) DeleteRange(min, max uint64) error { s.mu.Lock() defer s.mu.Unlock() return s.store.DeleteRange(min, max) }
[ "func", "(", "s", "*", "syncLogStore", ")", "DeleteRange", "(", "min", ",", "max", "uint64", ")", "error", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "store", ".", "DeleteRange", "(", "min", ",", "max", ")", "\n", "}" ]
// DeleteRange is part of raft.LogStore.
[ "DeleteRange", "is", "part", "of", "raft", ".", "LogStore", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/raft/synclogstore.go#L66-L70
3,770
juju/juju
worker/raft/synclogstore.go
Close
func (s *syncLogStore) Close() error { s.mu.Lock() defer s.mu.Unlock() return s.store.Close() }
go
func (s *syncLogStore) Close() error { s.mu.Lock() defer s.mu.Unlock() return s.store.Close() }
[ "func", "(", "s", "*", "syncLogStore", ")", "Close", "(", ")", "error", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "store", ".", "Close", "(", ")", "\n", "}" ]
// Close closes the underlying logstore.
[ "Close", "closes", "the", "underlying", "logstore", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/raft/synclogstore.go#L73-L77
3,771
juju/juju
state/backups/storage.go
docAsMetadata
func docAsMetadata(doc *storageMetaDoc) *Metadata { meta := NewMetadata() meta.Started = metadocUnixToTime(doc.Started) meta.Notes = doc.Notes meta.Origin.Model = doc.Model meta.Origin.Machine = doc.Machine meta.Origin.Hostname = doc.Hostname meta.Origin.Version = doc.Version meta.Origin.Series = doc.Series meta.SetID(doc.ID) if doc.Finished != 0 { finished := metadocUnixToTime(doc.Finished) meta.Finished = &finished } if doc.isFileInfoComplete() { // Set the file-related fields. // The doc should have already been validated when stored. meta.FileMetadata.Raw.Size = doc.Size meta.FileMetadata.Raw.Checksum = doc.Checksum meta.FileMetadata.Raw.ChecksumFormat = doc.ChecksumFormat } if doc.Stored != 0 { stored := metadocUnixToTime(doc.Stored) meta.SetStored(&stored) } return meta }
go
func docAsMetadata(doc *storageMetaDoc) *Metadata { meta := NewMetadata() meta.Started = metadocUnixToTime(doc.Started) meta.Notes = doc.Notes meta.Origin.Model = doc.Model meta.Origin.Machine = doc.Machine meta.Origin.Hostname = doc.Hostname meta.Origin.Version = doc.Version meta.Origin.Series = doc.Series meta.SetID(doc.ID) if doc.Finished != 0 { finished := metadocUnixToTime(doc.Finished) meta.Finished = &finished } if doc.isFileInfoComplete() { // Set the file-related fields. // The doc should have already been validated when stored. meta.FileMetadata.Raw.Size = doc.Size meta.FileMetadata.Raw.Checksum = doc.Checksum meta.FileMetadata.Raw.ChecksumFormat = doc.ChecksumFormat } if doc.Stored != 0 { stored := metadocUnixToTime(doc.Stored) meta.SetStored(&stored) } return meta }
[ "func", "docAsMetadata", "(", "doc", "*", "storageMetaDoc", ")", "*", "Metadata", "{", "meta", ":=", "NewMetadata", "(", ")", "\n", "meta", ".", "Started", "=", "metadocUnixToTime", "(", "doc", ".", "Started", ")", "\n", "meta", ".", "Notes", "=", "doc", ".", "Notes", "\n\n", "meta", ".", "Origin", ".", "Model", "=", "doc", ".", "Model", "\n", "meta", ".", "Origin", ".", "Machine", "=", "doc", ".", "Machine", "\n", "meta", ".", "Origin", ".", "Hostname", "=", "doc", ".", "Hostname", "\n", "meta", ".", "Origin", ".", "Version", "=", "doc", ".", "Version", "\n", "meta", ".", "Origin", ".", "Series", "=", "doc", ".", "Series", "\n\n", "meta", ".", "SetID", "(", "doc", ".", "ID", ")", "\n\n", "if", "doc", ".", "Finished", "!=", "0", "{", "finished", ":=", "metadocUnixToTime", "(", "doc", ".", "Finished", ")", "\n", "meta", ".", "Finished", "=", "&", "finished", "\n", "}", "\n\n", "if", "doc", ".", "isFileInfoComplete", "(", ")", "{", "// Set the file-related fields.", "// The doc should have already been validated when stored.", "meta", ".", "FileMetadata", ".", "Raw", ".", "Size", "=", "doc", ".", "Size", "\n", "meta", ".", "FileMetadata", ".", "Raw", ".", "Checksum", "=", "doc", ".", "Checksum", "\n", "meta", ".", "FileMetadata", ".", "Raw", ".", "ChecksumFormat", "=", "doc", ".", "ChecksumFormat", "\n", "}", "\n\n", "if", "doc", ".", "Stored", "!=", "0", "{", "stored", ":=", "metadocUnixToTime", "(", "doc", ".", "Stored", ")", "\n", "meta", ".", "SetStored", "(", "&", "stored", ")", "\n", "}", "\n\n", "return", "meta", "\n", "}" ]
// docAsMetadata returns a new backups.Metadata based on the storageMetaDoc.
[ "docAsMetadata", "returns", "a", "new", "backups", ".", "Metadata", "based", "on", "the", "storageMetaDoc", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/storage.go#L123-L156
3,772
juju/juju
state/backups/storage.go
newStorageMetaDoc
func newStorageMetaDoc(meta *Metadata) storageMetaDoc { var doc storageMetaDoc // Ignore metadata.ID. It will be set by storage later. doc.Checksum = meta.Checksum() doc.ChecksumFormat = meta.ChecksumFormat() doc.Size = meta.Size() if meta.Stored() != nil { stored := meta.Stored() doc.Stored = metadocTimeToUnix(*stored) } doc.Started = metadocTimeToUnix(meta.Started) if meta.Finished != nil { doc.Finished = metadocTimeToUnix(*meta.Finished) } doc.Notes = meta.Notes doc.Model = meta.Origin.Model doc.Machine = meta.Origin.Machine doc.Hostname = meta.Origin.Hostname doc.Version = meta.Origin.Version doc.Series = meta.Origin.Series return doc }
go
func newStorageMetaDoc(meta *Metadata) storageMetaDoc { var doc storageMetaDoc // Ignore metadata.ID. It will be set by storage later. doc.Checksum = meta.Checksum() doc.ChecksumFormat = meta.ChecksumFormat() doc.Size = meta.Size() if meta.Stored() != nil { stored := meta.Stored() doc.Stored = metadocTimeToUnix(*stored) } doc.Started = metadocTimeToUnix(meta.Started) if meta.Finished != nil { doc.Finished = metadocTimeToUnix(*meta.Finished) } doc.Notes = meta.Notes doc.Model = meta.Origin.Model doc.Machine = meta.Origin.Machine doc.Hostname = meta.Origin.Hostname doc.Version = meta.Origin.Version doc.Series = meta.Origin.Series return doc }
[ "func", "newStorageMetaDoc", "(", "meta", "*", "Metadata", ")", "storageMetaDoc", "{", "var", "doc", "storageMetaDoc", "\n\n", "// Ignore metadata.ID. It will be set by storage later.", "doc", ".", "Checksum", "=", "meta", ".", "Checksum", "(", ")", "\n", "doc", ".", "ChecksumFormat", "=", "meta", ".", "ChecksumFormat", "(", ")", "\n", "doc", ".", "Size", "=", "meta", ".", "Size", "(", ")", "\n", "if", "meta", ".", "Stored", "(", ")", "!=", "nil", "{", "stored", ":=", "meta", ".", "Stored", "(", ")", "\n", "doc", ".", "Stored", "=", "metadocTimeToUnix", "(", "*", "stored", ")", "\n", "}", "\n\n", "doc", ".", "Started", "=", "metadocTimeToUnix", "(", "meta", ".", "Started", ")", "\n", "if", "meta", ".", "Finished", "!=", "nil", "{", "doc", ".", "Finished", "=", "metadocTimeToUnix", "(", "*", "meta", ".", "Finished", ")", "\n", "}", "\n", "doc", ".", "Notes", "=", "meta", ".", "Notes", "\n\n", "doc", ".", "Model", "=", "meta", ".", "Origin", ".", "Model", "\n", "doc", ".", "Machine", "=", "meta", ".", "Origin", ".", "Machine", "\n", "doc", ".", "Hostname", "=", "meta", ".", "Origin", ".", "Hostname", "\n", "doc", ".", "Version", "=", "meta", ".", "Origin", ".", "Version", "\n", "doc", ".", "Series", "=", "meta", ".", "Origin", ".", "Series", "\n\n", "return", "doc", "\n", "}" ]
// newStorageMetaDoc creates a storageMetaDoc using the corresponding // values from the backup Metadata.
[ "newStorageMetaDoc", "creates", "a", "storageMetaDoc", "using", "the", "corresponding", "values", "from", "the", "backup", "Metadata", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/storage.go#L160-L186
3,773
juju/juju
state/backups/storage.go
newStorageDBWrapper
func newStorageDBWrapper(db *mgo.Database, metaColl, modelUUID string) *storageDBWrapper { session := db.Session.Copy() db = db.With(session) coll := db.C(metaColl) txnRunner := jujutxn.NewRunner(jujutxn.RunnerParams{ Database: db, ServerSideTransactions: false, }) dbWrap := storageDBWrapper{ session: session, db: db, metaColl: coll, txnRunner: txnRunner, modelUUID: modelUUID, } return &dbWrap }
go
func newStorageDBWrapper(db *mgo.Database, metaColl, modelUUID string) *storageDBWrapper { session := db.Session.Copy() db = db.With(session) coll := db.C(metaColl) txnRunner := jujutxn.NewRunner(jujutxn.RunnerParams{ Database: db, ServerSideTransactions: false, }) dbWrap := storageDBWrapper{ session: session, db: db, metaColl: coll, txnRunner: txnRunner, modelUUID: modelUUID, } return &dbWrap }
[ "func", "newStorageDBWrapper", "(", "db", "*", "mgo", ".", "Database", ",", "metaColl", ",", "modelUUID", "string", ")", "*", "storageDBWrapper", "{", "session", ":=", "db", ".", "Session", ".", "Copy", "(", ")", "\n", "db", "=", "db", ".", "With", "(", "session", ")", "\n\n", "coll", ":=", "db", ".", "C", "(", "metaColl", ")", "\n", "txnRunner", ":=", "jujutxn", ".", "NewRunner", "(", "jujutxn", ".", "RunnerParams", "{", "Database", ":", "db", ",", "ServerSideTransactions", ":", "false", ",", "}", ")", "\n", "dbWrap", ":=", "storageDBWrapper", "{", "session", ":", "session", ",", "db", ":", "db", ",", "metaColl", ":", "coll", ",", "txnRunner", ":", "txnRunner", ",", "modelUUID", ":", "modelUUID", ",", "}", "\n", "return", "&", "dbWrap", "\n", "}" ]
// newStorageDBWrapper returns a DB operator for the , with its own session.
[ "newStorageDBWrapper", "returns", "a", "DB", "operator", "for", "the", "with", "its", "own", "session", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/storage.go#L204-L221
3,774
juju/juju
state/backups/storage.go
metadata
func (b *storageDBWrapper) metadata(id string, doc interface{}) error { err := b.metaColl.FindId(id).One(doc) if err == mgo.ErrNotFound { return errors.NotFoundf("backup metadata %q", id) } return errors.Trace(err) }
go
func (b *storageDBWrapper) metadata(id string, doc interface{}) error { err := b.metaColl.FindId(id).One(doc) if err == mgo.ErrNotFound { return errors.NotFoundf("backup metadata %q", id) } return errors.Trace(err) }
[ "func", "(", "b", "*", "storageDBWrapper", ")", "metadata", "(", "id", "string", ",", "doc", "interface", "{", "}", ")", "error", "{", "err", ":=", "b", ".", "metaColl", ".", "FindId", "(", "id", ")", ".", "One", "(", "doc", ")", "\n", "if", "err", "==", "mgo", ".", "ErrNotFound", "{", "return", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "id", ")", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// metadata populates doc with the document matching the ID.
[ "metadata", "populates", "doc", "with", "the", "document", "matching", "the", "ID", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/storage.go#L224-L230
3,775
juju/juju
state/backups/storage.go
allMetadata
func (b *storageDBWrapper) allMetadata(docs interface{}) error { err := b.metaColl.Find(nil).All(docs) return errors.Trace(err) }
go
func (b *storageDBWrapper) allMetadata(docs interface{}) error { err := b.metaColl.Find(nil).All(docs) return errors.Trace(err) }
[ "func", "(", "b", "*", "storageDBWrapper", ")", "allMetadata", "(", "docs", "interface", "{", "}", ")", "error", "{", "err", ":=", "b", ".", "metaColl", ".", "Find", "(", "nil", ")", ".", "All", "(", "docs", ")", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// allMetadata populates docs with the list of documents in storage.
[ "allMetadata", "populates", "docs", "with", "the", "list", "of", "documents", "in", "storage", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/storage.go#L233-L236
3,776
juju/juju
state/backups/storage.go
removeMetadataID
func (b *storageDBWrapper) removeMetadataID(id string) error { err := b.metaColl.RemoveId(id) return errors.Trace(err) }
go
func (b *storageDBWrapper) removeMetadataID(id string) error { err := b.metaColl.RemoveId(id) return errors.Trace(err) }
[ "func", "(", "b", "*", "storageDBWrapper", ")", "removeMetadataID", "(", "id", "string", ")", "error", "{", "err", ":=", "b", ".", "metaColl", ".", "RemoveId", "(", "id", ")", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// removeMetadataID removes the identified metadata from storage.
[ "removeMetadataID", "removes", "the", "identified", "metadata", "from", "storage", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/storage.go#L239-L242
3,777
juju/juju
state/backups/storage.go
txnOpBase
func (b *storageDBWrapper) txnOpBase(id string) txn.Op { op := txn.Op{ C: b.metaColl.Name, Id: id, } return op }
go
func (b *storageDBWrapper) txnOpBase(id string) txn.Op { op := txn.Op{ C: b.metaColl.Name, Id: id, } return op }
[ "func", "(", "b", "*", "storageDBWrapper", ")", "txnOpBase", "(", "id", "string", ")", "txn", ".", "Op", "{", "op", ":=", "txn", ".", "Op", "{", "C", ":", "b", ".", "metaColl", ".", "Name", ",", "Id", ":", "id", ",", "}", "\n", "return", "op", "\n", "}" ]
// txnOp returns a single transaction operation populated with the id // and the metadata collection name. The caller should set other op // values as needed.
[ "txnOp", "returns", "a", "single", "transaction", "operation", "populated", "with", "the", "id", "and", "the", "metadata", "collection", "name", ".", "The", "caller", "should", "set", "other", "op", "values", "as", "needed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/storage.go#L247-L253
3,778
juju/juju
state/backups/storage.go
txnOpInsert
func (b *storageDBWrapper) txnOpInsert(id string, doc interface{}) txn.Op { op := b.txnOpBase(id) op.Assert = txn.DocMissing op.Insert = doc return op }
go
func (b *storageDBWrapper) txnOpInsert(id string, doc interface{}) txn.Op { op := b.txnOpBase(id) op.Assert = txn.DocMissing op.Insert = doc return op }
[ "func", "(", "b", "*", "storageDBWrapper", ")", "txnOpInsert", "(", "id", "string", ",", "doc", "interface", "{", "}", ")", "txn", ".", "Op", "{", "op", ":=", "b", ".", "txnOpBase", "(", "id", ")", "\n", "op", ".", "Assert", "=", "txn", ".", "DocMissing", "\n", "op", ".", "Insert", "=", "doc", "\n", "return", "op", "\n", "}" ]
// txnOpInsert returns a single transaction operation that will insert // the document into storage.
[ "txnOpInsert", "returns", "a", "single", "transaction", "operation", "that", "will", "insert", "the", "document", "into", "storage", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/storage.go#L257-L262
3,779
juju/juju
state/backups/storage.go
txnOpUpdate
func (b *storageDBWrapper) txnOpUpdate(id string, updates ...bson.DocElem) txn.Op { op := b.txnOpBase(id) op.Assert = txn.DocExists op.Update = bson.D{{"$set", bson.D(updates)}} return op }
go
func (b *storageDBWrapper) txnOpUpdate(id string, updates ...bson.DocElem) txn.Op { op := b.txnOpBase(id) op.Assert = txn.DocExists op.Update = bson.D{{"$set", bson.D(updates)}} return op }
[ "func", "(", "b", "*", "storageDBWrapper", ")", "txnOpUpdate", "(", "id", "string", ",", "updates", "...", "bson", ".", "DocElem", ")", "txn", ".", "Op", "{", "op", ":=", "b", ".", "txnOpBase", "(", "id", ")", "\n", "op", ".", "Assert", "=", "txn", ".", "DocExists", "\n", "op", ".", "Update", "=", "bson", ".", "D", "{", "{", "\"", "\"", ",", "bson", ".", "D", "(", "updates", ")", "}", "}", "\n", "return", "op", "\n", "}" ]
// txnOpInsert returns a single transaction operation that will update // the already stored document.
[ "txnOpInsert", "returns", "a", "single", "transaction", "operation", "that", "will", "update", "the", "already", "stored", "document", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/storage.go#L266-L271
3,780
juju/juju
state/backups/storage.go
runTransaction
func (b *storageDBWrapper) runTransaction(ops []txn.Op) error { err := b.txnRunner.RunTransaction(&jujutxn.Transaction{Ops: ops}) return errors.Trace(err) }
go
func (b *storageDBWrapper) runTransaction(ops []txn.Op) error { err := b.txnRunner.RunTransaction(&jujutxn.Transaction{Ops: ops}) return errors.Trace(err) }
[ "func", "(", "b", "*", "storageDBWrapper", ")", "runTransaction", "(", "ops", "[", "]", "txn", ".", "Op", ")", "error", "{", "err", ":=", "b", ".", "txnRunner", ".", "RunTransaction", "(", "&", "jujutxn", ".", "Transaction", "{", "Ops", ":", "ops", "}", ")", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// runTransaction runs the DB operations within a single transaction.
[ "runTransaction", "runs", "the", "DB", "operations", "within", "a", "single", "transaction", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/storage.go#L274-L277
3,781
juju/juju
state/backups/storage.go
blobStorage
func (b *storageDBWrapper) blobStorage(blobDB string) blobstore.ManagedStorage { dataStore := blobstore.NewGridFS(blobDB, blobDB, b.session) return blobstore.NewManagedStorage(b.db, dataStore) }
go
func (b *storageDBWrapper) blobStorage(blobDB string) blobstore.ManagedStorage { dataStore := blobstore.NewGridFS(blobDB, blobDB, b.session) return blobstore.NewManagedStorage(b.db, dataStore) }
[ "func", "(", "b", "*", "storageDBWrapper", ")", "blobStorage", "(", "blobDB", "string", ")", "blobstore", ".", "ManagedStorage", "{", "dataStore", ":=", "blobstore", ".", "NewGridFS", "(", "blobDB", ",", "blobDB", ",", "b", ".", "session", ")", "\n", "return", "blobstore", ".", "NewManagedStorage", "(", "b", ".", "db", ",", "dataStore", ")", "\n", "}" ]
// blobStorage returns a ManagedStorage matching the env storage and the blobDB.
[ "blobStorage", "returns", "a", "ManagedStorage", "matching", "the", "env", "storage", "and", "the", "blobDB", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/storage.go#L280-L283
3,782
juju/juju
state/backups/storage.go
Copy
func (b *storageDBWrapper) Copy() *storageDBWrapper { session := b.session.Copy() coll := b.metaColl.With(session) db := coll.Database txnRunner := jujutxn.NewRunner(jujutxn.RunnerParams{ Database: db, ServerSideTransactions: false, }) dbWrap := storageDBWrapper{ session: session, db: db, metaColl: coll, txnRunner: txnRunner, modelUUID: b.modelUUID, } return &dbWrap }
go
func (b *storageDBWrapper) Copy() *storageDBWrapper { session := b.session.Copy() coll := b.metaColl.With(session) db := coll.Database txnRunner := jujutxn.NewRunner(jujutxn.RunnerParams{ Database: db, ServerSideTransactions: false, }) dbWrap := storageDBWrapper{ session: session, db: db, metaColl: coll, txnRunner: txnRunner, modelUUID: b.modelUUID, } return &dbWrap }
[ "func", "(", "b", "*", "storageDBWrapper", ")", "Copy", "(", ")", "*", "storageDBWrapper", "{", "session", ":=", "b", ".", "session", ".", "Copy", "(", ")", "\n\n", "coll", ":=", "b", ".", "metaColl", ".", "With", "(", "session", ")", "\n", "db", ":=", "coll", ".", "Database", "\n", "txnRunner", ":=", "jujutxn", ".", "NewRunner", "(", "jujutxn", ".", "RunnerParams", "{", "Database", ":", "db", ",", "ServerSideTransactions", ":", "false", ",", "}", ")", "\n", "dbWrap", ":=", "storageDBWrapper", "{", "session", ":", "session", ",", "db", ":", "db", ",", "metaColl", ":", "coll", ",", "txnRunner", ":", "txnRunner", ",", "modelUUID", ":", "b", ".", "modelUUID", ",", "}", "\n", "return", "&", "dbWrap", "\n", "}" ]
// Copy returns a copy of the operator.
[ "Copy", "returns", "a", "copy", "of", "the", "operator", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/storage.go#L286-L303
3,783
juju/juju
state/backups/storage.go
addStorageMetadata
func addStorageMetadata(dbWrap *storageDBWrapper, doc *storageMetaDoc) (string, error) { // We use our own mongo _id value since the auto-generated one from // mongo may contain sensitive data (see bson.ObjectID). id := newStorageID(doc) doc.ID = id if err := doc.validate(); err != nil { return "", errors.Trace(err) } op := dbWrap.txnOpInsert(id, doc) if err := dbWrap.runTransaction([]txn.Op{op}); err != nil { if errors.Cause(err) == txn.ErrAborted { return "", errors.AlreadyExistsf("backup metadata %q", doc.ID) } return "", errors.Annotate(err, "while running transaction") } return id, nil }
go
func addStorageMetadata(dbWrap *storageDBWrapper, doc *storageMetaDoc) (string, error) { // We use our own mongo _id value since the auto-generated one from // mongo may contain sensitive data (see bson.ObjectID). id := newStorageID(doc) doc.ID = id if err := doc.validate(); err != nil { return "", errors.Trace(err) } op := dbWrap.txnOpInsert(id, doc) if err := dbWrap.runTransaction([]txn.Op{op}); err != nil { if errors.Cause(err) == txn.ErrAborted { return "", errors.AlreadyExistsf("backup metadata %q", doc.ID) } return "", errors.Annotate(err, "while running transaction") } return id, nil }
[ "func", "addStorageMetadata", "(", "dbWrap", "*", "storageDBWrapper", ",", "doc", "*", "storageMetaDoc", ")", "(", "string", ",", "error", ")", "{", "// We use our own mongo _id value since the auto-generated one from", "// mongo may contain sensitive data (see bson.ObjectID).", "id", ":=", "newStorageID", "(", "doc", ")", "\n\n", "doc", ".", "ID", "=", "id", "\n", "if", "err", ":=", "doc", ".", "validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "op", ":=", "dbWrap", ".", "txnOpInsert", "(", "id", ",", "doc", ")", "\n\n", "if", "err", ":=", "dbWrap", ".", "runTransaction", "(", "[", "]", "txn", ".", "Op", "{", "op", "}", ")", ";", "err", "!=", "nil", "{", "if", "errors", ".", "Cause", "(", "err", ")", "==", "txn", ".", "ErrAborted", "{", "return", "\"", "\"", ",", "errors", ".", "AlreadyExistsf", "(", "\"", "\"", ",", "doc", ".", "ID", ")", "\n", "}", "\n", "return", "\"", "\"", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "id", ",", "nil", "\n", "}" ]
// addStorageMetadata stores metadata for a backup where it can be // accessed later. It returns a new ID that is associated with the // backup. If the provided metadata already has an ID set, it is // ignored. The new ID is set on the doc, even when there is an error.
[ "addStorageMetadata", "stores", "metadata", "for", "a", "backup", "where", "it", "can", "be", "accessed", "later", ".", "It", "returns", "a", "new", "ID", "that", "is", "associated", "with", "the", "backup", ".", "If", "the", "provided", "metadata", "already", "has", "an", "ID", "set", "it", "is", "ignored", ".", "The", "new", "ID", "is", "set", "on", "the", "doc", "even", "when", "there", "is", "an", "error", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/storage.go#L345-L365
3,784
juju/juju
state/backups/storage.go
AddDoc
func (s *backupsDocStorage) AddDoc(doc filestorage.Document) (string, error) { metadata, ok := doc.(*Metadata) if !ok { return "", errors.Errorf("doc must be of type *backups.Metadata") } metaDoc := newStorageMetaDoc(metadata) dbWrap := s.dbWrap.Copy() defer dbWrap.Close() id, err := addStorageMetadata(dbWrap, &metaDoc) return id, errors.Trace(err) }
go
func (s *backupsDocStorage) AddDoc(doc filestorage.Document) (string, error) { metadata, ok := doc.(*Metadata) if !ok { return "", errors.Errorf("doc must be of type *backups.Metadata") } metaDoc := newStorageMetaDoc(metadata) dbWrap := s.dbWrap.Copy() defer dbWrap.Close() id, err := addStorageMetadata(dbWrap, &metaDoc) return id, errors.Trace(err) }
[ "func", "(", "s", "*", "backupsDocStorage", ")", "AddDoc", "(", "doc", "filestorage", ".", "Document", ")", "(", "string", ",", "error", ")", "{", "metadata", ",", "ok", ":=", "doc", ".", "(", "*", "Metadata", ")", "\n", "if", "!", "ok", "{", "return", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "metaDoc", ":=", "newStorageMetaDoc", "(", "metadata", ")", "\n\n", "dbWrap", ":=", "s", ".", "dbWrap", ".", "Copy", "(", ")", "\n", "defer", "dbWrap", ".", "Close", "(", ")", "\n\n", "id", ",", "err", ":=", "addStorageMetadata", "(", "dbWrap", ",", "&", "metaDoc", ")", "\n", "return", "id", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// AddDoc adds the document to storage and returns the new ID.
[ "AddDoc", "adds", "the", "document", "to", "storage", "and", "returns", "the", "new", "ID", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/storage.go#L408-L420
3,785
juju/juju
state/backups/storage.go
Doc
func (s *backupsDocStorage) Doc(id string) (filestorage.Document, error) { dbWrap := s.dbWrap.Copy() defer dbWrap.Close() doc, err := getStorageMetadata(dbWrap, id) if err != nil { return nil, errors.Trace(err) } metadata := docAsMetadata(doc) return metadata, nil }
go
func (s *backupsDocStorage) Doc(id string) (filestorage.Document, error) { dbWrap := s.dbWrap.Copy() defer dbWrap.Close() doc, err := getStorageMetadata(dbWrap, id) if err != nil { return nil, errors.Trace(err) } metadata := docAsMetadata(doc) return metadata, nil }
[ "func", "(", "s", "*", "backupsDocStorage", ")", "Doc", "(", "id", "string", ")", "(", "filestorage", ".", "Document", ",", "error", ")", "{", "dbWrap", ":=", "s", ".", "dbWrap", ".", "Copy", "(", ")", "\n", "defer", "dbWrap", ".", "Close", "(", ")", "\n\n", "doc", ",", "err", ":=", "getStorageMetadata", "(", "dbWrap", ",", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "metadata", ":=", "docAsMetadata", "(", "doc", ")", "\n", "return", "metadata", ",", "nil", "\n", "}" ]
// Doc returns the stored document associated with the given ID.
[ "Doc", "returns", "the", "stored", "document", "associated", "with", "the", "given", "ID", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/storage.go#L423-L434
3,786
juju/juju
state/backups/storage.go
ListDocs
func (s *backupsDocStorage) ListDocs() ([]filestorage.Document, error) { dbWrap := s.dbWrap.Copy() defer dbWrap.Close() var docs []storageMetaDoc if err := dbWrap.allMetadata(&docs); err != nil { return nil, errors.Trace(err) } list := make([]filestorage.Document, len(docs)) for i, doc := range docs { meta := docAsMetadata(&doc) list[i] = meta } return list, nil }
go
func (s *backupsDocStorage) ListDocs() ([]filestorage.Document, error) { dbWrap := s.dbWrap.Copy() defer dbWrap.Close() var docs []storageMetaDoc if err := dbWrap.allMetadata(&docs); err != nil { return nil, errors.Trace(err) } list := make([]filestorage.Document, len(docs)) for i, doc := range docs { meta := docAsMetadata(&doc) list[i] = meta } return list, nil }
[ "func", "(", "s", "*", "backupsDocStorage", ")", "ListDocs", "(", ")", "(", "[", "]", "filestorage", ".", "Document", ",", "error", ")", "{", "dbWrap", ":=", "s", ".", "dbWrap", ".", "Copy", "(", ")", "\n", "defer", "dbWrap", ".", "Close", "(", ")", "\n\n", "var", "docs", "[", "]", "storageMetaDoc", "\n", "if", "err", ":=", "dbWrap", ".", "allMetadata", "(", "&", "docs", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "list", ":=", "make", "(", "[", "]", "filestorage", ".", "Document", ",", "len", "(", "docs", ")", ")", "\n", "for", "i", ",", "doc", ":=", "range", "docs", "{", "meta", ":=", "docAsMetadata", "(", "&", "doc", ")", "\n", "list", "[", "i", "]", "=", "meta", "\n", "}", "\n", "return", "list", ",", "nil", "\n", "}" ]
// ListDocs returns the list of all stored documents.
[ "ListDocs", "returns", "the", "list", "of", "all", "stored", "documents", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/storage.go#L437-L452
3,787
juju/juju
state/backups/storage.go
RemoveDoc
func (s *backupsDocStorage) RemoveDoc(id string) error { dbWrap := s.dbWrap.Copy() defer dbWrap.Close() return errors.Trace(dbWrap.removeMetadataID(id)) }
go
func (s *backupsDocStorage) RemoveDoc(id string) error { dbWrap := s.dbWrap.Copy() defer dbWrap.Close() return errors.Trace(dbWrap.removeMetadataID(id)) }
[ "func", "(", "s", "*", "backupsDocStorage", ")", "RemoveDoc", "(", "id", "string", ")", "error", "{", "dbWrap", ":=", "s", ".", "dbWrap", ".", "Copy", "(", ")", "\n", "defer", "dbWrap", ".", "Close", "(", ")", "\n\n", "return", "errors", ".", "Trace", "(", "dbWrap", ".", "removeMetadataID", "(", "id", ")", ")", "\n", "}" ]
// RemoveDoc removes the identified document from storage.
[ "RemoveDoc", "removes", "the", "identified", "document", "from", "storage", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/storage.go#L455-L460
3,788
juju/juju
state/backups/storage.go
SetStored
func (s *backupsMetadataStorage) SetStored(id string) error { dbWrap := newStorageDBWrapper(s.db, storageMetaName, s.modelUUID) defer dbWrap.Close() // TODO(perrito666) 2016-05-02 lp:1558657 err := setStorageStoredTime(dbWrap, id, time.Now()) return errors.Trace(err) }
go
func (s *backupsMetadataStorage) SetStored(id string) error { dbWrap := newStorageDBWrapper(s.db, storageMetaName, s.modelUUID) defer dbWrap.Close() // TODO(perrito666) 2016-05-02 lp:1558657 err := setStorageStoredTime(dbWrap, id, time.Now()) return errors.Trace(err) }
[ "func", "(", "s", "*", "backupsMetadataStorage", ")", "SetStored", "(", "id", "string", ")", "error", "{", "dbWrap", ":=", "newStorageDBWrapper", "(", "s", ".", "db", ",", "storageMetaName", ",", "s", ".", "modelUUID", ")", "\n", "defer", "dbWrap", ".", "Close", "(", ")", "\n\n", "// TODO(perrito666) 2016-05-02 lp:1558657", "err", ":=", "setStorageStoredTime", "(", "dbWrap", ",", "id", ",", "time", ".", "Now", "(", ")", ")", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// SetStored records in the metadata the fact that the file was stored.
[ "SetStored", "records", "in", "the", "metadata", "the", "fact", "that", "the", "file", "was", "stored", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/storage.go#L468-L475
3,789
juju/juju
state/backups/storage.go
File
func (s *backupBlobStorage) File(id string) (io.ReadCloser, error) { file, _, err := s.storeImpl.GetForBucket(s.modelUUID, s.path(id)) return file, errors.Trace(err) }
go
func (s *backupBlobStorage) File(id string) (io.ReadCloser, error) { file, _, err := s.storeImpl.GetForBucket(s.modelUUID, s.path(id)) return file, errors.Trace(err) }
[ "func", "(", "s", "*", "backupBlobStorage", ")", "File", "(", "id", "string", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "file", ",", "_", ",", "err", ":=", "s", ".", "storeImpl", ".", "GetForBucket", "(", "s", ".", "modelUUID", ",", "s", ".", "path", "(", "id", ")", ")", "\n", "return", "file", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// File returns the identified file from storage.
[ "File", "returns", "the", "identified", "file", "from", "storage", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/storage.go#L510-L513
3,790
juju/juju
state/backups/storage.go
AddFile
func (s *backupBlobStorage) AddFile(id string, file io.Reader, size int64) error { return s.storeImpl.PutForBucket(s.modelUUID, s.path(id), file, size) }
go
func (s *backupBlobStorage) AddFile(id string, file io.Reader, size int64) error { return s.storeImpl.PutForBucket(s.modelUUID, s.path(id), file, size) }
[ "func", "(", "s", "*", "backupBlobStorage", ")", "AddFile", "(", "id", "string", ",", "file", "io", ".", "Reader", ",", "size", "int64", ")", "error", "{", "return", "s", ".", "storeImpl", ".", "PutForBucket", "(", "s", ".", "modelUUID", ",", "s", ".", "path", "(", "id", ")", ",", "file", ",", "size", ")", "\n", "}" ]
// AddFile adds the file to storage.
[ "AddFile", "adds", "the", "file", "to", "storage", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/storage.go#L516-L518
3,791
juju/juju
state/backups/storage.go
RemoveFile
func (s *backupBlobStorage) RemoveFile(id string) error { return s.storeImpl.RemoveForBucket(s.modelUUID, s.path(id)) }
go
func (s *backupBlobStorage) RemoveFile(id string) error { return s.storeImpl.RemoveForBucket(s.modelUUID, s.path(id)) }
[ "func", "(", "s", "*", "backupBlobStorage", ")", "RemoveFile", "(", "id", "string", ")", "error", "{", "return", "s", ".", "storeImpl", ".", "RemoveForBucket", "(", "s", ".", "modelUUID", ",", "s", ".", "path", "(", "id", ")", ")", "\n", "}" ]
// RemoveFile removes the identified file from storage.
[ "RemoveFile", "removes", "the", "identified", "file", "from", "storage", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/storage.go#L521-L523
3,792
juju/juju
apiserver/facades/agent/upgrader/unitupgrader.go
NewUnitUpgraderAPI
func NewUnitUpgraderAPI( st *state.State, resources facade.Resources, authorizer facade.Authorizer, ) (*UnitUpgraderAPI, error) { if !authorizer.AuthUnitAgent() { return nil, common.ErrPerm } getCanWrite := func() (common.AuthFunc, error) { return authorizer.AuthOwner, nil } return &UnitUpgraderAPI{ ToolsSetter: common.NewToolsSetter(st, getCanWrite), st: st, resources: resources, authorizer: authorizer, }, nil }
go
func NewUnitUpgraderAPI( st *state.State, resources facade.Resources, authorizer facade.Authorizer, ) (*UnitUpgraderAPI, error) { if !authorizer.AuthUnitAgent() { return nil, common.ErrPerm } getCanWrite := func() (common.AuthFunc, error) { return authorizer.AuthOwner, nil } return &UnitUpgraderAPI{ ToolsSetter: common.NewToolsSetter(st, getCanWrite), st: st, resources: resources, authorizer: authorizer, }, nil }
[ "func", "NewUnitUpgraderAPI", "(", "st", "*", "state", ".", "State", ",", "resources", "facade", ".", "Resources", ",", "authorizer", "facade", ".", "Authorizer", ",", ")", "(", "*", "UnitUpgraderAPI", ",", "error", ")", "{", "if", "!", "authorizer", ".", "AuthUnitAgent", "(", ")", "{", "return", "nil", ",", "common", ".", "ErrPerm", "\n", "}", "\n\n", "getCanWrite", ":=", "func", "(", ")", "(", "common", ".", "AuthFunc", ",", "error", ")", "{", "return", "authorizer", ".", "AuthOwner", ",", "nil", "\n", "}", "\n", "return", "&", "UnitUpgraderAPI", "{", "ToolsSetter", ":", "common", ".", "NewToolsSetter", "(", "st", ",", "getCanWrite", ")", ",", "st", ":", "st", ",", "resources", ":", "resources", ",", "authorizer", ":", "authorizer", ",", "}", ",", "nil", "\n", "}" ]
// NewUnitUpgraderAPI creates a new server-side UnitUpgraderAPI facade.
[ "NewUnitUpgraderAPI", "creates", "a", "new", "server", "-", "side", "UnitUpgraderAPI", "facade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/upgrader/unitupgrader.go#L28-L46
3,793
juju/juju
apiserver/facades/agent/upgrader/unitupgrader.go
WatchAPIVersion
func (u *UnitUpgraderAPI) WatchAPIVersion(args params.Entities) (params.NotifyWatchResults, error) { result := params.NotifyWatchResults{ Results: make([]params.NotifyWatchResult, len(args.Entities)), } for i, agent := range args.Entities { tag, err := names.ParseTag(agent.Tag) if err != nil { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } err = common.ErrPerm if u.authorizer.AuthOwner(tag) { var watcherId string watcherId, err = u.watchAssignedMachine(tag) if err == nil { result.Results[i].NotifyWatcherId = watcherId } } result.Results[i].Error = common.ServerError(err) } return result, nil }
go
func (u *UnitUpgraderAPI) WatchAPIVersion(args params.Entities) (params.NotifyWatchResults, error) { result := params.NotifyWatchResults{ Results: make([]params.NotifyWatchResult, len(args.Entities)), } for i, agent := range args.Entities { tag, err := names.ParseTag(agent.Tag) if err != nil { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } err = common.ErrPerm if u.authorizer.AuthOwner(tag) { var watcherId string watcherId, err = u.watchAssignedMachine(tag) if err == nil { result.Results[i].NotifyWatcherId = watcherId } } result.Results[i].Error = common.ServerError(err) } return result, nil }
[ "func", "(", "u", "*", "UnitUpgraderAPI", ")", "WatchAPIVersion", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "NotifyWatchResults", ",", "error", ")", "{", "result", ":=", "params", ".", "NotifyWatchResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "NotifyWatchResult", ",", "len", "(", "args", ".", "Entities", ")", ")", ",", "}", "\n", "for", "i", ",", "agent", ":=", "range", "args", ".", "Entities", "{", "tag", ",", "err", ":=", "names", ".", "ParseTag", "(", "agent", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "common", ".", "ErrPerm", ")", "\n", "continue", "\n", "}", "\n", "err", "=", "common", ".", "ErrPerm", "\n", "if", "u", ".", "authorizer", ".", "AuthOwner", "(", "tag", ")", "{", "var", "watcherId", "string", "\n", "watcherId", ",", "err", "=", "u", ".", "watchAssignedMachine", "(", "tag", ")", "\n", "if", "err", "==", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "NotifyWatcherId", "=", "watcherId", "\n", "}", "\n", "}", "\n", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// WatchAPIVersion starts a watcher to track if there is a new version // of the API that we want to upgrade to. The watcher tracks changes to // the unit's assigned machine since that's where the required agent version is stored.
[ "WatchAPIVersion", "starts", "a", "watcher", "to", "track", "if", "there", "is", "a", "new", "version", "of", "the", "API", "that", "we", "want", "to", "upgrade", "to", ".", "The", "watcher", "tracks", "changes", "to", "the", "unit", "s", "assigned", "machine", "since", "that", "s", "where", "the", "required", "agent", "version", "is", "stored", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/upgrader/unitupgrader.go#L67-L88
3,794
juju/juju
apiserver/facades/agent/upgrader/unitupgrader.go
DesiredVersion
func (u *UnitUpgraderAPI) DesiredVersion(args params.Entities) (params.VersionResults, error) { result := make([]params.VersionResult, len(args.Entities)) for i, entity := range args.Entities { tag, err := names.ParseTag(entity.Tag) if err != nil { result[i].Error = common.ServerError(common.ErrPerm) continue } err = common.ErrPerm if u.authorizer.AuthOwner(tag) { result[i].Version, err = u.getMachineToolsVersion(tag) } result[i].Error = common.ServerError(err) } return params.VersionResults{Results: result}, nil }
go
func (u *UnitUpgraderAPI) DesiredVersion(args params.Entities) (params.VersionResults, error) { result := make([]params.VersionResult, len(args.Entities)) for i, entity := range args.Entities { tag, err := names.ParseTag(entity.Tag) if err != nil { result[i].Error = common.ServerError(common.ErrPerm) continue } err = common.ErrPerm if u.authorizer.AuthOwner(tag) { result[i].Version, err = u.getMachineToolsVersion(tag) } result[i].Error = common.ServerError(err) } return params.VersionResults{Results: result}, nil }
[ "func", "(", "u", "*", "UnitUpgraderAPI", ")", "DesiredVersion", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "VersionResults", ",", "error", ")", "{", "result", ":=", "make", "(", "[", "]", "params", ".", "VersionResult", ",", "len", "(", "args", ".", "Entities", ")", ")", "\n", "for", "i", ",", "entity", ":=", "range", "args", ".", "Entities", "{", "tag", ",", "err", ":=", "names", ".", "ParseTag", "(", "entity", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "result", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "common", ".", "ErrPerm", ")", "\n", "continue", "\n", "}", "\n", "err", "=", "common", ".", "ErrPerm", "\n", "if", "u", ".", "authorizer", ".", "AuthOwner", "(", "tag", ")", "{", "result", "[", "i", "]", ".", "Version", ",", "err", "=", "u", ".", "getMachineToolsVersion", "(", "tag", ")", "\n", "}", "\n", "result", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "return", "params", ".", "VersionResults", "{", "Results", ":", "result", "}", ",", "nil", "\n", "}" ]
// DesiredVersion reports the Agent Version that we want that unit to be running. // The desired version is what the unit's assigned machine is running.
[ "DesiredVersion", "reports", "the", "Agent", "Version", "that", "we", "want", "that", "unit", "to", "be", "running", ".", "The", "desired", "version", "is", "what", "the", "unit", "s", "assigned", "machine", "is", "running", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/upgrader/unitupgrader.go#L92-L107
3,795
juju/juju
worker/uniter/runner/jujuc/goal-state.go
formatGoalState
func formatGoalState(gs application.GoalState) formattedGoalState { result := formattedGoalState{} copyUnits := func(units application.UnitsGoalState) unitsGoalStateContents { copiedUnits := unitsGoalStateContents{} for name, gs := range units { copiedUnits[name] = goalStateStatusContents{ Status: gs.Status, Since: common.FormatTime(gs.Since, true), } } return copiedUnits } result.Units = copyUnits(gs.Units) result.Relations = make(map[string]unitsGoalStateContents, len(gs.Relations)) for relation, units := range gs.Relations { result.Relations[relation] = copyUnits(units) } return result }
go
func formatGoalState(gs application.GoalState) formattedGoalState { result := formattedGoalState{} copyUnits := func(units application.UnitsGoalState) unitsGoalStateContents { copiedUnits := unitsGoalStateContents{} for name, gs := range units { copiedUnits[name] = goalStateStatusContents{ Status: gs.Status, Since: common.FormatTime(gs.Since, true), } } return copiedUnits } result.Units = copyUnits(gs.Units) result.Relations = make(map[string]unitsGoalStateContents, len(gs.Relations)) for relation, units := range gs.Relations { result.Relations[relation] = copyUnits(units) } return result }
[ "func", "formatGoalState", "(", "gs", "application", ".", "GoalState", ")", "formattedGoalState", "{", "result", ":=", "formattedGoalState", "{", "}", "\n\n", "copyUnits", ":=", "func", "(", "units", "application", ".", "UnitsGoalState", ")", "unitsGoalStateContents", "{", "copiedUnits", ":=", "unitsGoalStateContents", "{", "}", "\n", "for", "name", ",", "gs", ":=", "range", "units", "{", "copiedUnits", "[", "name", "]", "=", "goalStateStatusContents", "{", "Status", ":", "gs", ".", "Status", ",", "Since", ":", "common", ".", "FormatTime", "(", "gs", ".", "Since", ",", "true", ")", ",", "}", "\n", "}", "\n", "return", "copiedUnits", "\n", "}", "\n\n", "result", ".", "Units", "=", "copyUnits", "(", "gs", ".", "Units", ")", "\n", "result", ".", "Relations", "=", "make", "(", "map", "[", "string", "]", "unitsGoalStateContents", ",", "len", "(", "gs", ".", "Relations", ")", ")", "\n", "for", "relation", ",", "units", ":=", "range", "gs", ".", "Relations", "{", "result", ".", "Relations", "[", "relation", "]", "=", "copyUnits", "(", "units", ")", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// formatGoalState moves information from application GoalState struct to // application GoalState struct.
[ "formatGoalState", "moves", "information", "from", "application", "GoalState", "struct", "to", "application", "GoalState", "struct", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/jujuc/goal-state.go#L76-L97
3,796
juju/juju
core/model/model.go
ValidateSeries
func ValidateSeries(modelType ModelType, charmSeries string) error { os, err := series.GetOSFromSeries(charmSeries) if err != nil { return errors.Trace(err) } switch modelType { case CAAS: if !caasOS.Contains(os.String()) { return errors.NotValidf("series %q in a kubernetes model", charmSeries) } case IAAS: if caasOS.Contains(os.String()) { return errors.NotValidf("series %q in a non container model", charmSeries) } } return nil }
go
func ValidateSeries(modelType ModelType, charmSeries string) error { os, err := series.GetOSFromSeries(charmSeries) if err != nil { return errors.Trace(err) } switch modelType { case CAAS: if !caasOS.Contains(os.String()) { return errors.NotValidf("series %q in a kubernetes model", charmSeries) } case IAAS: if caasOS.Contains(os.String()) { return errors.NotValidf("series %q in a non container model", charmSeries) } } return nil }
[ "func", "ValidateSeries", "(", "modelType", "ModelType", ",", "charmSeries", "string", ")", "error", "{", "os", ",", "err", ":=", "series", ".", "GetOSFromSeries", "(", "charmSeries", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "switch", "modelType", "{", "case", "CAAS", ":", "if", "!", "caasOS", ".", "Contains", "(", "os", ".", "String", "(", ")", ")", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "charmSeries", ")", "\n", "}", "\n", "case", "IAAS", ":", "if", "caasOS", ".", "Contains", "(", "os", ".", "String", "(", ")", ")", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "charmSeries", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ValidateSeries ensures the charm series is valid for the model type.
[ "ValidateSeries", "ensures", "the", "charm", "series", "is", "valid", "for", "the", "model", "type", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/core/model/model.go#L44-L60
3,797
juju/juju
apiserver/facades/client/firewallrules/backend.go
NewStateBackend
func NewStateBackend(st *state.State) (Backend, error) { m, err := st.Model() if err != nil { return nil, err } if m.Type() != state.ModelTypeIAAS { return nil, errors.NotSupportedf("Firewall Rules for non-IAAS models") } return &stateShim{ State: st, Model: m, }, nil }
go
func NewStateBackend(st *state.State) (Backend, error) { m, err := st.Model() if err != nil { return nil, err } if m.Type() != state.ModelTypeIAAS { return nil, errors.NotSupportedf("Firewall Rules for non-IAAS models") } return &stateShim{ State: st, Model: m, }, nil }
[ "func", "NewStateBackend", "(", "st", "*", "state", ".", "State", ")", "(", "Backend", ",", "error", ")", "{", "m", ",", "err", ":=", "st", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "m", ".", "Type", "(", ")", "!=", "state", ".", "ModelTypeIAAS", "{", "return", "nil", ",", "errors", ".", "NotSupportedf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "&", "stateShim", "{", "State", ":", "st", ",", "Model", ":", "m", ",", "}", ",", "nil", "\n", "}" ]
// NewStateBackend converts a state.State into a Backend.
[ "NewStateBackend", "converts", "a", "state", ".", "State", "into", "a", "Backend", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/firewallrules/backend.go#L37-L49
3,798
juju/juju
api/provisioner/machine.go
ModelAgentVersion
func (m *Machine) ModelAgentVersion() (*version.Number, error) { mc, err := m.st.ModelConfig() if err != nil { return nil, errors.Trace(err) } if v, ok := mc.AgentVersion(); ok { return &v, nil } return nil, errors.New("failed to get model's agent version.") }
go
func (m *Machine) ModelAgentVersion() (*version.Number, error) { mc, err := m.st.ModelConfig() if err != nil { return nil, errors.Trace(err) } if v, ok := mc.AgentVersion(); ok { return &v, nil } return nil, errors.New("failed to get model's agent version.") }
[ "func", "(", "m", "*", "Machine", ")", "ModelAgentVersion", "(", ")", "(", "*", "version", ".", "Number", ",", "error", ")", "{", "mc", ",", "err", ":=", "m", ".", "st", ".", "ModelConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "v", ",", "ok", ":=", "mc", ".", "AgentVersion", "(", ")", ";", "ok", "{", "return", "&", "v", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// ModelAgentVersion implements MachineProvisioner.ModelAgentVersion.
[ "ModelAgentVersion", "implements", "MachineProvisioner", ".", "ModelAgentVersion", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/provisioner/machine.go#L140-L151
3,799
juju/juju
api/provisioner/machine.go
ProvisioningInfo
func (m *Machine) ProvisioningInfo() (*params.ProvisioningInfo, error) { var results params.ProvisioningInfoResults args := params.Entities{Entities: []params.Entity{{m.tag.String()}}} err := m.st.facade.FacadeCall("ProvisioningInfo", args, &results) if err != nil { return nil, err } if len(results.Results) != 1 { return nil, fmt.Errorf("expected 1 result, got %d", len(results.Results)) } result := results.Results[0] if result.Error != nil { return nil, result.Error } return result.Result, nil }
go
func (m *Machine) ProvisioningInfo() (*params.ProvisioningInfo, error) { var results params.ProvisioningInfoResults args := params.Entities{Entities: []params.Entity{{m.tag.String()}}} err := m.st.facade.FacadeCall("ProvisioningInfo", args, &results) if err != nil { return nil, err } if len(results.Results) != 1 { return nil, fmt.Errorf("expected 1 result, got %d", len(results.Results)) } result := results.Results[0] if result.Error != nil { return nil, result.Error } return result.Result, nil }
[ "func", "(", "m", "*", "Machine", ")", "ProvisioningInfo", "(", ")", "(", "*", "params", ".", "ProvisioningInfo", ",", "error", ")", "{", "var", "results", "params", ".", "ProvisioningInfoResults", "\n", "args", ":=", "params", ".", "Entities", "{", "Entities", ":", "[", "]", "params", ".", "Entity", "{", "{", "m", ".", "tag", ".", "String", "(", ")", "}", "}", "}", "\n", "err", ":=", "m", ".", "st", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "results", ".", "Results", ")", "!=", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "results", ".", "Results", ")", ")", "\n", "}", "\n", "result", ":=", "results", ".", "Results", "[", "0", "]", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "result", ".", "Error", "\n", "}", "\n", "return", "result", ".", "Result", ",", "nil", "\n", "}" ]
// ProvisioningInfo implements MachineProvisioner.ProvisioningInfo.
[ "ProvisioningInfo", "implements", "MachineProvisioner", ".", "ProvisioningInfo", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/provisioner/machine.go#L184-L199