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
4,100
juju/juju
worker/upgradeseries/worker.go
unpinLeaders
func (w *upgradeSeriesWorker) unpinLeaders() error { results, err := w.UnpinMachineApplications() if err != nil { return errors.Trace(err) } var lastErr error for app, err := range results { if err == nil { w.logger.Infof("unpinned leader for application %q", app) continue } w.logger.Errorf("failed to unpin leader for application %q: %s", app, err.Error()) lastErr = err } if lastErr == nil { w.leadersPinned = false return nil } return errors.Trace(lastErr) }
go
func (w *upgradeSeriesWorker) unpinLeaders() error { results, err := w.UnpinMachineApplications() if err != nil { return errors.Trace(err) } var lastErr error for app, err := range results { if err == nil { w.logger.Infof("unpinned leader for application %q", app) continue } w.logger.Errorf("failed to unpin leader for application %q: %s", app, err.Error()) lastErr = err } if lastErr == nil { w.leadersPinned = false return nil } return errors.Trace(lastErr) }
[ "func", "(", "w", "*", "upgradeSeriesWorker", ")", "unpinLeaders", "(", ")", "error", "{", "results", ",", "err", ":=", "w", ".", "UnpinMachineApplications", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "var", "lastErr", "error", "\n", "for", "app", ",", "err", ":=", "range", "results", "{", "if", "err", "==", "nil", "{", "w", ".", "logger", ".", "Infof", "(", "\"", "\"", ",", "app", ")", "\n", "continue", "\n", "}", "\n", "w", ".", "logger", ".", "Errorf", "(", "\"", "\"", ",", "app", ",", "err", ".", "Error", "(", ")", ")", "\n", "lastErr", "=", "err", "\n", "}", "\n\n", "if", "lastErr", "==", "nil", "{", "w", ".", "leadersPinned", "=", "false", "\n", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "lastErr", ")", "\n", "}" ]
// unpinLeaders unpins leadership for applications // represented by units running on this machine.
[ "unpinLeaders", "unpins", "leadership", "for", "applications", "represented", "by", "units", "running", "on", "this", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/worker.go#L386-L407
4,101
juju/juju
worker/upgradeseries/worker.go
unitServices
func (w *upgradeSeriesWorker) unitServices() (map[string]string, error) { services, err := w.service.ListServices() if err != nil { return nil, errors.Trace(err) } return service.FindUnitServiceNames(services), nil }
go
func (w *upgradeSeriesWorker) unitServices() (map[string]string, error) { services, err := w.service.ListServices() if err != nil { return nil, errors.Trace(err) } return service.FindUnitServiceNames(services), nil }
[ "func", "(", "w", "*", "upgradeSeriesWorker", ")", "unitServices", "(", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "services", ",", "err", ":=", "w", ".", "service", ".", "ListServices", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "service", ".", "FindUnitServiceNames", "(", "services", ")", ",", "nil", "\n", "}" ]
// Unit services returns a map of unit agent service names, // keyed on their unit IDs.
[ "Unit", "services", "returns", "a", "map", "of", "unit", "agent", "service", "names", "keyed", "on", "their", "unit", "IDs", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/worker.go#L411-L417
4,102
juju/juju
worker/upgradeseries/worker.go
unitNames
func unitNames(units map[string]string) string { unitIds := make([]string, len(units)) i := 0 for u := range units { unitIds[i] = u i++ } return strings.Join(unitIds, ", ") }
go
func unitNames(units map[string]string) string { unitIds := make([]string, len(units)) i := 0 for u := range units { unitIds[i] = u i++ } return strings.Join(unitIds, ", ") }
[ "func", "unitNames", "(", "units", "map", "[", "string", "]", "string", ")", "string", "{", "unitIds", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "units", ")", ")", "\n", "i", ":=", "0", "\n", "for", "u", ":=", "range", "units", "{", "unitIds", "[", "i", "]", "=", "u", "\n", "i", "++", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "unitIds", ",", "\"", "\"", ")", "\n", "}" ]
// unitNames returns a comma-delimited string of unit names based on the input // map of unit agent services.
[ "unitNames", "returns", "a", "comma", "-", "delimited", "string", "of", "unit", "names", "based", "on", "the", "input", "map", "of", "unit", "agent", "services", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/worker.go#L464-L472
4,103
juju/juju
resource/api/http.go
NewEndpointPath
func NewEndpointPath(application, name string) string { return fmt.Sprintf(HTTPEndpointPath, application, name) }
go
func NewEndpointPath(application, name string) string { return fmt.Sprintf(HTTPEndpointPath, application, name) }
[ "func", "NewEndpointPath", "(", "application", ",", "name", "string", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "HTTPEndpointPath", ",", "application", ",", "name", ")", "\n", "}" ]
// NewEndpointPath returns the API URL path for the identified resource.
[ "NewEndpointPath", "returns", "the", "API", "URL", "path", "for", "the", "identified", "resource", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/api/http.go#L59-L61
4,104
juju/juju
resource/api/http.go
ExtractEndpointDetails
func ExtractEndpointDetails(url *url.URL) (application, name string) { application = url.Query().Get(":application") name = url.Query().Get(":resource") return application, name }
go
func ExtractEndpointDetails(url *url.URL) (application, name string) { application = url.Query().Get(":application") name = url.Query().Get(":resource") return application, name }
[ "func", "ExtractEndpointDetails", "(", "url", "*", "url", ".", "URL", ")", "(", "application", ",", "name", "string", ")", "{", "application", "=", "url", ".", "Query", "(", ")", ".", "Get", "(", "\"", "\"", ")", "\n", "name", "=", "url", ".", "Query", "(", ")", ".", "Get", "(", "\"", "\"", ")", "\n", "return", "application", ",", "name", "\n", "}" ]
// ExtractEndpointDetails pulls the endpoint wildcard values from // the provided URL.
[ "ExtractEndpointDetails", "pulls", "the", "endpoint", "wildcard", "values", "from", "the", "provided", "URL", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/api/http.go#L65-L69
4,105
juju/juju
resource/api/http.go
SendHTTPStatusAndJSON
func SendHTTPStatusAndJSON(w http.ResponseWriter, statusCode int, response interface{}) { body, err := json.Marshal(response) if err != nil { http.Error(w, errors.Annotatef(err, "cannot marshal JSON result %#v", response).Error(), 504) return } if statusCode == http.StatusUnauthorized { w.Header().Set("WWW-Authenticate", `Basic realm="juju"`) } w.Header().Set("Content-Type", params.ContentTypeJSON) w.Header().Set("Content-Length", fmt.Sprint(len(body))) w.WriteHeader(statusCode) w.Write(body) }
go
func SendHTTPStatusAndJSON(w http.ResponseWriter, statusCode int, response interface{}) { body, err := json.Marshal(response) if err != nil { http.Error(w, errors.Annotatef(err, "cannot marshal JSON result %#v", response).Error(), 504) return } if statusCode == http.StatusUnauthorized { w.Header().Set("WWW-Authenticate", `Basic realm="juju"`) } w.Header().Set("Content-Type", params.ContentTypeJSON) w.Header().Set("Content-Length", fmt.Sprint(len(body))) w.WriteHeader(statusCode) w.Write(body) }
[ "func", "SendHTTPStatusAndJSON", "(", "w", "http", ".", "ResponseWriter", ",", "statusCode", "int", ",", "response", "interface", "{", "}", ")", "{", "body", ",", "err", ":=", "json", ".", "Marshal", "(", "response", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "response", ")", ".", "Error", "(", ")", ",", "504", ")", "\n", "return", "\n", "}", "\n\n", "if", "statusCode", "==", "http", ".", "StatusUnauthorized", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "`Basic realm=\"juju\"`", ")", "\n", "}", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "params", ".", "ContentTypeJSON", ")", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "fmt", ".", "Sprint", "(", "len", "(", "body", ")", ")", ")", "\n", "w", ".", "WriteHeader", "(", "statusCode", ")", "\n", "w", ".", "Write", "(", "body", ")", "\n", "}" ]
// SendHTTPStatusAndJSON sends an HTTP status code and // a JSON-encoded response to a client.
[ "SendHTTPStatusAndJSON", "sends", "an", "HTTP", "status", "code", "and", "a", "JSON", "-", "encoded", "response", "to", "a", "client", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/api/http.go#L85-L99
4,106
juju/juju
worker/caasenvironupgrader/worker.go
NewWorker
func NewWorker(config Config) (worker.Worker, error) { if err := config.Validate(); err != nil { return nil, errors.Trace(err) } // There are no upgrade steps for a CAAS model. // We just set the status to available and unlock the gate. return jujuworker.NewSimpleWorker(func(<-chan struct{}) error { setStatus := func(s status.Status, info string) error { return config.Facade.SetModelStatus(config.ModelTag, s, info, nil) } if err := setStatus(status.Available, ""); err != nil { return errors.Trace(err) } config.GateUnlocker.Unlock() return nil }), nil }
go
func NewWorker(config Config) (worker.Worker, error) { if err := config.Validate(); err != nil { return nil, errors.Trace(err) } // There are no upgrade steps for a CAAS model. // We just set the status to available and unlock the gate. return jujuworker.NewSimpleWorker(func(<-chan struct{}) error { setStatus := func(s status.Status, info string) error { return config.Facade.SetModelStatus(config.ModelTag, s, info, nil) } if err := setStatus(status.Available, ""); err != nil { return errors.Trace(err) } config.GateUnlocker.Unlock() return nil }), nil }
[ "func", "NewWorker", "(", "config", "Config", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "if", "err", ":=", "config", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "// There are no upgrade steps for a CAAS model.", "// We just set the status to available and unlock the gate.", "return", "jujuworker", ".", "NewSimpleWorker", "(", "func", "(", "<-", "chan", "struct", "{", "}", ")", "error", "{", "setStatus", ":=", "func", "(", "s", "status", ".", "Status", ",", "info", "string", ")", "error", "{", "return", "config", ".", "Facade", ".", "SetModelStatus", "(", "config", ".", "ModelTag", ",", "s", ",", "info", ",", "nil", ")", "\n", "}", "\n", "if", "err", ":=", "setStatus", "(", "status", ".", "Available", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "config", ".", "GateUnlocker", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}", ")", ",", "nil", "\n", "}" ]
// NewWorker returns a worker that unlocks the model upgrade gate.
[ "NewWorker", "returns", "a", "worker", "that", "unlocks", "the", "model", "upgrade", "gate", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/caasenvironupgrader/worker.go#L55-L71
4,107
juju/juju
apiserver/facades/client/annotations/client.go
NewAPI
func NewAPI( st *state.State, resources facade.Resources, authorizer facade.Authorizer, ) (*API, error) { if !authorizer.AuthClient() { return nil, common.ErrPerm } m, err := st.Model() if err != nil { return nil, errors.Trace(err) } return &API{ access: getState(st, m), authorizer: authorizer, }, nil }
go
func NewAPI( st *state.State, resources facade.Resources, authorizer facade.Authorizer, ) (*API, error) { if !authorizer.AuthClient() { return nil, common.ErrPerm } m, err := st.Model() if err != nil { return nil, errors.Trace(err) } return &API{ access: getState(st, m), authorizer: authorizer, }, nil }
[ "func", "NewAPI", "(", "st", "*", "state", ".", "State", ",", "resources", "facade", ".", "Resources", ",", "authorizer", "facade", ".", "Authorizer", ",", ")", "(", "*", "API", ",", "error", ")", "{", "if", "!", "authorizer", ".", "AuthClient", "(", ")", "{", "return", "nil", ",", "common", ".", "ErrPerm", "\n", "}", "\n", "m", ",", "err", ":=", "st", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "API", "{", "access", ":", "getState", "(", "st", ",", "m", ")", ",", "authorizer", ":", "authorizer", ",", "}", ",", "nil", "\n", "}" ]
// NewAPI returns a new charm annotator API facade.
[ "NewAPI", "returns", "a", "new", "charm", "annotator", "API", "facade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/annotations/client.go#L35-L52
4,108
juju/juju
apiserver/facades/client/annotations/client.go
Get
func (api *API) Get(args params.Entities) params.AnnotationsGetResults { if err := api.checkCanRead(); err != nil { result := make([]params.AnnotationsGetResult, len(args.Entities)) for i := range result { result[i].Error = params.ErrorResult{Error: common.ServerError(err)} } return params.AnnotationsGetResults{Results: result} } entityResults := []params.AnnotationsGetResult{} for _, entity := range args.Entities { anEntityResult := params.AnnotationsGetResult{EntityTag: entity.Tag} if annts, err := api.getEntityAnnotations(entity.Tag); err != nil { anEntityResult.Error = params.ErrorResult{annotateError(err, entity.Tag, "getting")} } else { anEntityResult.Annotations = annts } entityResults = append(entityResults, anEntityResult) } return params.AnnotationsGetResults{Results: entityResults} }
go
func (api *API) Get(args params.Entities) params.AnnotationsGetResults { if err := api.checkCanRead(); err != nil { result := make([]params.AnnotationsGetResult, len(args.Entities)) for i := range result { result[i].Error = params.ErrorResult{Error: common.ServerError(err)} } return params.AnnotationsGetResults{Results: result} } entityResults := []params.AnnotationsGetResult{} for _, entity := range args.Entities { anEntityResult := params.AnnotationsGetResult{EntityTag: entity.Tag} if annts, err := api.getEntityAnnotations(entity.Tag); err != nil { anEntityResult.Error = params.ErrorResult{annotateError(err, entity.Tag, "getting")} } else { anEntityResult.Annotations = annts } entityResults = append(entityResults, anEntityResult) } return params.AnnotationsGetResults{Results: entityResults} }
[ "func", "(", "api", "*", "API", ")", "Get", "(", "args", "params", ".", "Entities", ")", "params", ".", "AnnotationsGetResults", "{", "if", "err", ":=", "api", ".", "checkCanRead", "(", ")", ";", "err", "!=", "nil", "{", "result", ":=", "make", "(", "[", "]", "params", ".", "AnnotationsGetResult", ",", "len", "(", "args", ".", "Entities", ")", ")", "\n", "for", "i", ":=", "range", "result", "{", "result", "[", "i", "]", ".", "Error", "=", "params", ".", "ErrorResult", "{", "Error", ":", "common", ".", "ServerError", "(", "err", ")", "}", "\n", "}", "\n", "return", "params", ".", "AnnotationsGetResults", "{", "Results", ":", "result", "}", "\n", "}", "\n\n", "entityResults", ":=", "[", "]", "params", ".", "AnnotationsGetResult", "{", "}", "\n", "for", "_", ",", "entity", ":=", "range", "args", ".", "Entities", "{", "anEntityResult", ":=", "params", ".", "AnnotationsGetResult", "{", "EntityTag", ":", "entity", ".", "Tag", "}", "\n", "if", "annts", ",", "err", ":=", "api", ".", "getEntityAnnotations", "(", "entity", ".", "Tag", ")", ";", "err", "!=", "nil", "{", "anEntityResult", ".", "Error", "=", "params", ".", "ErrorResult", "{", "annotateError", "(", "err", ",", "entity", ".", "Tag", ",", "\"", "\"", ")", "}", "\n", "}", "else", "{", "anEntityResult", ".", "Annotations", "=", "annts", "\n", "}", "\n", "entityResults", "=", "append", "(", "entityResults", ",", "anEntityResult", ")", "\n", "}", "\n", "return", "params", ".", "AnnotationsGetResults", "{", "Results", ":", "entityResults", "}", "\n", "}" ]
// Get returns annotations for given entities. // If annotations cannot be retrieved for a given entity, an error is returned. // Each entity is treated independently and, hence, will fail or succeed independently.
[ "Get", "returns", "annotations", "for", "given", "entities", ".", "If", "annotations", "cannot", "be", "retrieved", "for", "a", "given", "entity", "an", "error", "is", "returned", ".", "Each", "entity", "is", "treated", "independently", "and", "hence", "will", "fail", "or", "succeed", "independently", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/annotations/client.go#L79-L99
4,109
juju/juju
apiserver/facades/client/annotations/client.go
Set
func (api *API) Set(args params.AnnotationsSet) params.ErrorResults { if err := api.checkCanWrite(); err != nil { errorResults := make([]params.ErrorResult, len(args.Annotations)) for i := range errorResults { errorResults[i].Error = common.ServerError(err) } return params.ErrorResults{Results: errorResults} } setErrors := []params.ErrorResult{} for _, entityAnnotation := range args.Annotations { err := api.setEntityAnnotations(entityAnnotation.EntityTag, entityAnnotation.Annotations) if err != nil { setErrors = append(setErrors, params.ErrorResult{Error: annotateError(err, entityAnnotation.EntityTag, "setting")}) } } return params.ErrorResults{Results: setErrors} }
go
func (api *API) Set(args params.AnnotationsSet) params.ErrorResults { if err := api.checkCanWrite(); err != nil { errorResults := make([]params.ErrorResult, len(args.Annotations)) for i := range errorResults { errorResults[i].Error = common.ServerError(err) } return params.ErrorResults{Results: errorResults} } setErrors := []params.ErrorResult{} for _, entityAnnotation := range args.Annotations { err := api.setEntityAnnotations(entityAnnotation.EntityTag, entityAnnotation.Annotations) if err != nil { setErrors = append(setErrors, params.ErrorResult{Error: annotateError(err, entityAnnotation.EntityTag, "setting")}) } } return params.ErrorResults{Results: setErrors} }
[ "func", "(", "api", "*", "API", ")", "Set", "(", "args", "params", ".", "AnnotationsSet", ")", "params", ".", "ErrorResults", "{", "if", "err", ":=", "api", ".", "checkCanWrite", "(", ")", ";", "err", "!=", "nil", "{", "errorResults", ":=", "make", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "args", ".", "Annotations", ")", ")", "\n", "for", "i", ":=", "range", "errorResults", "{", "errorResults", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "return", "params", ".", "ErrorResults", "{", "Results", ":", "errorResults", "}", "\n", "}", "\n", "setErrors", ":=", "[", "]", "params", ".", "ErrorResult", "{", "}", "\n", "for", "_", ",", "entityAnnotation", ":=", "range", "args", ".", "Annotations", "{", "err", ":=", "api", ".", "setEntityAnnotations", "(", "entityAnnotation", ".", "EntityTag", ",", "entityAnnotation", ".", "Annotations", ")", "\n", "if", "err", "!=", "nil", "{", "setErrors", "=", "append", "(", "setErrors", ",", "params", ".", "ErrorResult", "{", "Error", ":", "annotateError", "(", "err", ",", "entityAnnotation", ".", "EntityTag", ",", "\"", "\"", ")", "}", ")", "\n", "}", "\n", "}", "\n", "return", "params", ".", "ErrorResults", "{", "Results", ":", "setErrors", "}", "\n", "}" ]
// Set stores annotations for given entities
[ "Set", "stores", "annotations", "for", "given", "entities" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/annotations/client.go#L102-L119
4,110
juju/juju
cmd/juju/machine/upgradeseries.go
UpgradeSeriesPrepare
func (c *upgradeSeriesCommand) UpgradeSeriesPrepare(ctx *cmd.Context) (err error) { apiRoot, err := c.ensureAPIClient() if err != nil { return errors.Trace(err) } if apiRoot != nil { defer apiRoot.Close() } units, err := c.upgradeMachineSeriesClient.UpgradeSeriesValidate(c.machineNumber, c.series) if err != nil { return errors.Trace(err) } if err := c.promptConfirmation(ctx, units); err != nil { return errors.Trace(err) } if err = c.upgradeMachineSeriesClient.UpgradeSeriesPrepare(c.machineNumber, c.series, c.force); err != nil { return errors.Trace(err) } if err = c.handleNotifications(ctx); err != nil { return errors.Trace(err) } m := UpgradeSeriesPrepareFinishedMessage + "\n" ctx.Infof(m, c.machineNumber) return nil }
go
func (c *upgradeSeriesCommand) UpgradeSeriesPrepare(ctx *cmd.Context) (err error) { apiRoot, err := c.ensureAPIClient() if err != nil { return errors.Trace(err) } if apiRoot != nil { defer apiRoot.Close() } units, err := c.upgradeMachineSeriesClient.UpgradeSeriesValidate(c.machineNumber, c.series) if err != nil { return errors.Trace(err) } if err := c.promptConfirmation(ctx, units); err != nil { return errors.Trace(err) } if err = c.upgradeMachineSeriesClient.UpgradeSeriesPrepare(c.machineNumber, c.series, c.force); err != nil { return errors.Trace(err) } if err = c.handleNotifications(ctx); err != nil { return errors.Trace(err) } m := UpgradeSeriesPrepareFinishedMessage + "\n" ctx.Infof(m, c.machineNumber) return nil }
[ "func", "(", "c", "*", "upgradeSeriesCommand", ")", "UpgradeSeriesPrepare", "(", "ctx", "*", "cmd", ".", "Context", ")", "(", "err", "error", ")", "{", "apiRoot", ",", "err", ":=", "c", ".", "ensureAPIClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "apiRoot", "!=", "nil", "{", "defer", "apiRoot", ".", "Close", "(", ")", "\n", "}", "\n\n", "units", ",", "err", ":=", "c", ".", "upgradeMachineSeriesClient", ".", "UpgradeSeriesValidate", "(", "c", ".", "machineNumber", ",", "c", ".", "series", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "c", ".", "promptConfirmation", "(", "ctx", ",", "units", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "err", "=", "c", ".", "upgradeMachineSeriesClient", ".", "UpgradeSeriesPrepare", "(", "c", ".", "machineNumber", ",", "c", ".", "series", ",", "c", ".", "force", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "err", "=", "c", ".", "handleNotifications", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "m", ":=", "UpgradeSeriesPrepareFinishedMessage", "+", "\"", "\\n", "\"", "\n", "ctx", ".", "Infof", "(", "m", ",", "c", ".", "machineNumber", ")", "\n\n", "return", "nil", "\n", "}" ]
// UpgradeSeriesPrepare is the interface to the API server endpoint of the same // name. Since this function's interface will be mocked as an external test // dependency this function should contain minimal logic other than gathering an // API handle and making the API call.
[ "UpgradeSeriesPrepare", "is", "the", "interface", "to", "the", "API", "server", "endpoint", "of", "the", "same", "name", ".", "Since", "this", "function", "s", "interface", "will", "be", "mocked", "as", "an", "external", "test", "dependency", "this", "function", "should", "contain", "minimal", "logic", "other", "than", "gathering", "an", "API", "handle", "and", "making", "the", "API", "call", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/machine/upgradeseries.go#L214-L243
4,111
juju/juju
cmd/juju/machine/upgradeseries.go
displayNotifications
func (c *upgradeSeriesCommand) displayNotifications(ctx *cmd.Context) func() error { // We return and anonymous function here to satisfy the catacomb plan's // need for a work function and to close over the commands context. return func() error { uw, wid, err := c.upgradeMachineSeriesClient.WatchUpgradeSeriesNotifications(c.machineNumber) if err != nil { return errors.Trace(err) } err = c.catacomb.Add(uw) if err != nil { return errors.Trace(err) } for { select { case <-c.catacomb.Dying(): return c.catacomb.ErrDying() case <-uw.Changes(): err = c.handleUpgradeSeriesChange(ctx, wid) if err != nil { return errors.Trace(err) } } } } }
go
func (c *upgradeSeriesCommand) displayNotifications(ctx *cmd.Context) func() error { // We return and anonymous function here to satisfy the catacomb plan's // need for a work function and to close over the commands context. return func() error { uw, wid, err := c.upgradeMachineSeriesClient.WatchUpgradeSeriesNotifications(c.machineNumber) if err != nil { return errors.Trace(err) } err = c.catacomb.Add(uw) if err != nil { return errors.Trace(err) } for { select { case <-c.catacomb.Dying(): return c.catacomb.ErrDying() case <-uw.Changes(): err = c.handleUpgradeSeriesChange(ctx, wid) if err != nil { return errors.Trace(err) } } } } }
[ "func", "(", "c", "*", "upgradeSeriesCommand", ")", "displayNotifications", "(", "ctx", "*", "cmd", ".", "Context", ")", "func", "(", ")", "error", "{", "// We return and anonymous function here to satisfy the catacomb plan's", "// need for a work function and to close over the commands context.", "return", "func", "(", ")", "error", "{", "uw", ",", "wid", ",", "err", ":=", "c", ".", "upgradeMachineSeriesClient", ".", "WatchUpgradeSeriesNotifications", "(", "c", ".", "machineNumber", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "err", "=", "c", ".", "catacomb", ".", "Add", "(", "uw", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "for", "{", "select", "{", "case", "<-", "c", ".", "catacomb", ".", "Dying", "(", ")", ":", "return", "c", ".", "catacomb", ".", "ErrDying", "(", ")", "\n", "case", "<-", "uw", ".", "Changes", "(", ")", ":", "err", "=", "c", ".", "handleUpgradeSeriesChange", "(", "ctx", ",", "wid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// displayNotifications handles the writing of upgrade series notifications to // standard out.
[ "displayNotifications", "handles", "the", "writing", "of", "upgrade", "series", "notifications", "to", "standard", "out", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/machine/upgradeseries.go#L296-L320
4,112
juju/juju
cmd/juju/machine/upgradeseries.go
UpgradeSeriesComplete
func (c *upgradeSeriesCommand) UpgradeSeriesComplete(ctx *cmd.Context) error { apiRoot, err := c.ensureAPIClient() if err != nil { return errors.Trace(err) } if apiRoot != nil { defer apiRoot.Close() } if err := c.upgradeMachineSeriesClient.UpgradeSeriesComplete(c.machineNumber); err != nil { return errors.Trace(err) } if err := c.handleNotifications(ctx); err != nil { return errors.Trace(err) } m := UpgradeSeriesCompleteFinishedMessage + "\n" ctx.Infof(m, c.machineNumber) return nil }
go
func (c *upgradeSeriesCommand) UpgradeSeriesComplete(ctx *cmd.Context) error { apiRoot, err := c.ensureAPIClient() if err != nil { return errors.Trace(err) } if apiRoot != nil { defer apiRoot.Close() } if err := c.upgradeMachineSeriesClient.UpgradeSeriesComplete(c.machineNumber); err != nil { return errors.Trace(err) } if err := c.handleNotifications(ctx); err != nil { return errors.Trace(err) } m := UpgradeSeriesCompleteFinishedMessage + "\n" ctx.Infof(m, c.machineNumber) return nil }
[ "func", "(", "c", "*", "upgradeSeriesCommand", ")", "UpgradeSeriesComplete", "(", "ctx", "*", "cmd", ".", "Context", ")", "error", "{", "apiRoot", ",", "err", ":=", "c", ".", "ensureAPIClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "apiRoot", "!=", "nil", "{", "defer", "apiRoot", ".", "Close", "(", ")", "\n", "}", "\n\n", "if", "err", ":=", "c", ".", "upgradeMachineSeriesClient", ".", "UpgradeSeriesComplete", "(", "c", ".", "machineNumber", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "c", ".", "handleNotifications", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "m", ":=", "UpgradeSeriesCompleteFinishedMessage", "+", "\"", "\\n", "\"", "\n", "ctx", ".", "Infof", "(", "m", ",", "c", ".", "machineNumber", ")", "\n\n", "return", "nil", "\n", "}" ]
// UpgradeSeriesComplete completes a series upgrade for a given machine, // that is if a machine is marked as upgrading using UpgradeSeriesPrepare, // then this command will complete that process and the machine will no longer // be marked as upgrading.
[ "UpgradeSeriesComplete", "completes", "a", "series", "upgrade", "for", "a", "given", "machine", "that", "is", "if", "a", "machine", "is", "marked", "as", "upgrading", "using", "UpgradeSeriesPrepare", "then", "this", "command", "will", "complete", "that", "process", "and", "the", "machine", "will", "no", "longer", "be", "marked", "as", "upgrading", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/machine/upgradeseries.go#L338-L359
4,113
juju/juju
state/unitagent.go
Status
func (u *UnitAgent) Status() (status.StatusInfo, error) { info, err := getStatus(u.st.db(), u.globalKey(), "agent") if err != nil { return status.StatusInfo{}, errors.Trace(err) } // The current health spec says when a hook error occurs, the workload should // be in error state, but the state model more correctly records the agent // itself as being in error. So we'll do that model translation here. // TODO(fwereade): this should absolutely not be happpening in the model. // TODO: when fixed, also fix code in status.go for UnitAgent. if info.Status == status.Error { return status.StatusInfo{ Status: status.Idle, Message: "", Data: map[string]interface{}{}, Since: info.Since, }, nil } return info, nil }
go
func (u *UnitAgent) Status() (status.StatusInfo, error) { info, err := getStatus(u.st.db(), u.globalKey(), "agent") if err != nil { return status.StatusInfo{}, errors.Trace(err) } // The current health spec says when a hook error occurs, the workload should // be in error state, but the state model more correctly records the agent // itself as being in error. So we'll do that model translation here. // TODO(fwereade): this should absolutely not be happpening in the model. // TODO: when fixed, also fix code in status.go for UnitAgent. if info.Status == status.Error { return status.StatusInfo{ Status: status.Idle, Message: "", Data: map[string]interface{}{}, Since: info.Since, }, nil } return info, nil }
[ "func", "(", "u", "*", "UnitAgent", ")", "Status", "(", ")", "(", "status", ".", "StatusInfo", ",", "error", ")", "{", "info", ",", "err", ":=", "getStatus", "(", "u", ".", "st", ".", "db", "(", ")", ",", "u", ".", "globalKey", "(", ")", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "status", ".", "StatusInfo", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "// The current health spec says when a hook error occurs, the workload should", "// be in error state, but the state model more correctly records the agent", "// itself as being in error. So we'll do that model translation here.", "// TODO(fwereade): this should absolutely not be happpening in the model.", "// TODO: when fixed, also fix code in status.go for UnitAgent.", "if", "info", ".", "Status", "==", "status", ".", "Error", "{", "return", "status", ".", "StatusInfo", "{", "Status", ":", "status", ".", "Idle", ",", "Message", ":", "\"", "\"", ",", "Data", ":", "map", "[", "string", "]", "interface", "{", "}", "{", "}", ",", "Since", ":", "info", ".", "Since", ",", "}", ",", "nil", "\n", "}", "\n", "return", "info", ",", "nil", "\n", "}" ]
// Status returns the status of the unit agent.
[ "Status", "returns", "the", "status", "of", "the", "unit", "agent", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unitagent.go#L37-L56
4,114
juju/juju
state/unitagent.go
SetStatus
func (u *UnitAgent) SetStatus(unitAgentStatus status.StatusInfo) (err error) { unit, err := u.st.Unit(u.name) if errors.IsNotFound(err) { return errors.Annotate(errors.NotFoundf("agent"), "cannot set status") } if err != nil { return errors.Trace(err) } isAssigned := unit.doc.MachineId != "" shouldBeAssigned := unit.ShouldBeAssigned() isPrincipal := unit.doc.Principal == "" switch unitAgentStatus.Status { case status.Idle, status.Executing, status.Rebooting, status.Failed: if !isAssigned && isPrincipal && shouldBeAssigned { return errors.Errorf("cannot set status %q until unit is assigned", unitAgentStatus.Status) } case status.Error: if unitAgentStatus.Message == "" { return errors.Errorf("cannot set status %q without info", unitAgentStatus.Status) } case status.Allocating: if isAssigned { return errors.Errorf("cannot set status %q as unit is already assigned", unitAgentStatus.Status) } case status.Running: // Only CAAS units (those that require assignment) can have a status of running. if shouldBeAssigned { return errors.Errorf("cannot set invalid status %q", unitAgentStatus.Status) } case status.Lost: return errors.Errorf("cannot set status %q", unitAgentStatus.Status) default: return errors.Errorf("cannot set invalid status %q", unitAgentStatus.Status) } return setStatus(u.st.db(), setStatusParams{ badge: "agent", globalKey: u.globalKey(), status: unitAgentStatus.Status, message: unitAgentStatus.Message, rawData: unitAgentStatus.Data, updated: timeOrNow(unitAgentStatus.Since, u.st.clock()), }) }
go
func (u *UnitAgent) SetStatus(unitAgentStatus status.StatusInfo) (err error) { unit, err := u.st.Unit(u.name) if errors.IsNotFound(err) { return errors.Annotate(errors.NotFoundf("agent"), "cannot set status") } if err != nil { return errors.Trace(err) } isAssigned := unit.doc.MachineId != "" shouldBeAssigned := unit.ShouldBeAssigned() isPrincipal := unit.doc.Principal == "" switch unitAgentStatus.Status { case status.Idle, status.Executing, status.Rebooting, status.Failed: if !isAssigned && isPrincipal && shouldBeAssigned { return errors.Errorf("cannot set status %q until unit is assigned", unitAgentStatus.Status) } case status.Error: if unitAgentStatus.Message == "" { return errors.Errorf("cannot set status %q without info", unitAgentStatus.Status) } case status.Allocating: if isAssigned { return errors.Errorf("cannot set status %q as unit is already assigned", unitAgentStatus.Status) } case status.Running: // Only CAAS units (those that require assignment) can have a status of running. if shouldBeAssigned { return errors.Errorf("cannot set invalid status %q", unitAgentStatus.Status) } case status.Lost: return errors.Errorf("cannot set status %q", unitAgentStatus.Status) default: return errors.Errorf("cannot set invalid status %q", unitAgentStatus.Status) } return setStatus(u.st.db(), setStatusParams{ badge: "agent", globalKey: u.globalKey(), status: unitAgentStatus.Status, message: unitAgentStatus.Message, rawData: unitAgentStatus.Data, updated: timeOrNow(unitAgentStatus.Since, u.st.clock()), }) }
[ "func", "(", "u", "*", "UnitAgent", ")", "SetStatus", "(", "unitAgentStatus", "status", ".", "StatusInfo", ")", "(", "err", "error", ")", "{", "unit", ",", "err", ":=", "u", ".", "st", ".", "Unit", "(", "u", ".", "name", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "errors", ".", "Annotate", "(", "errors", ".", "NotFoundf", "(", "\"", "\"", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "isAssigned", ":=", "unit", ".", "doc", ".", "MachineId", "!=", "\"", "\"", "\n", "shouldBeAssigned", ":=", "unit", ".", "ShouldBeAssigned", "(", ")", "\n", "isPrincipal", ":=", "unit", ".", "doc", ".", "Principal", "==", "\"", "\"", "\n\n", "switch", "unitAgentStatus", ".", "Status", "{", "case", "status", ".", "Idle", ",", "status", ".", "Executing", ",", "status", ".", "Rebooting", ",", "status", ".", "Failed", ":", "if", "!", "isAssigned", "&&", "isPrincipal", "&&", "shouldBeAssigned", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "unitAgentStatus", ".", "Status", ")", "\n", "}", "\n", "case", "status", ".", "Error", ":", "if", "unitAgentStatus", ".", "Message", "==", "\"", "\"", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "unitAgentStatus", ".", "Status", ")", "\n", "}", "\n", "case", "status", ".", "Allocating", ":", "if", "isAssigned", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "unitAgentStatus", ".", "Status", ")", "\n", "}", "\n", "case", "status", ".", "Running", ":", "// Only CAAS units (those that require assignment) can have a status of running.", "if", "shouldBeAssigned", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "unitAgentStatus", ".", "Status", ")", "\n", "}", "\n", "case", "status", ".", "Lost", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "unitAgentStatus", ".", "Status", ")", "\n", "default", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "unitAgentStatus", ".", "Status", ")", "\n", "}", "\n", "return", "setStatus", "(", "u", ".", "st", ".", "db", "(", ")", ",", "setStatusParams", "{", "badge", ":", "\"", "\"", ",", "globalKey", ":", "u", ".", "globalKey", "(", ")", ",", "status", ":", "unitAgentStatus", ".", "Status", ",", "message", ":", "unitAgentStatus", ".", "Message", ",", "rawData", ":", "unitAgentStatus", ".", "Data", ",", "updated", ":", "timeOrNow", "(", "unitAgentStatus", ".", "Since", ",", "u", ".", "st", ".", "clock", "(", ")", ")", ",", "}", ")", "\n", "}" ]
// SetStatus sets the status of the unit agent. The optional values // allow to pass additional helpful status data.
[ "SetStatus", "sets", "the", "status", "of", "the", "unit", "agent", ".", "The", "optional", "values", "allow", "to", "pass", "additional", "helpful", "status", "data", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/unitagent.go#L60-L103
4,115
juju/juju
provider/gce/google/network.go
Path
func (ns *NetworkSpec) Path() string { name := ns.Name if name == "" { name = networkDefaultName } return networkPathRoot + name }
go
func (ns *NetworkSpec) Path() string { name := ns.Name if name == "" { name = networkDefaultName } return networkPathRoot + name }
[ "func", "(", "ns", "*", "NetworkSpec", ")", "Path", "(", ")", "string", "{", "name", ":=", "ns", ".", "Name", "\n", "if", "name", "==", "\"", "\"", "{", "name", "=", "networkDefaultName", "\n", "}", "\n", "return", "networkPathRoot", "+", "name", "\n", "}" ]
// Path returns the qualified name of the network.
[ "Path", "returns", "the", "qualified", "name", "of", "the", "network", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/network.go#L33-L39
4,116
juju/juju
provider/gce/google/network.go
newInterface
func (ns *NetworkSpec) newInterface(name string) *compute.NetworkInterface { var access []*compute.AccessConfig if name != "" { // This interface has an internet connection. access = append(access, &compute.AccessConfig{ Name: name, Type: NetworkAccessOneToOneNAT, // NatIP (only set if using a reserved public IP) }) // TODO(ericsnow) Will we need to support more access configs? } return &compute.NetworkInterface{ Network: ns.Path(), AccessConfigs: access, } }
go
func (ns *NetworkSpec) newInterface(name string) *compute.NetworkInterface { var access []*compute.AccessConfig if name != "" { // This interface has an internet connection. access = append(access, &compute.AccessConfig{ Name: name, Type: NetworkAccessOneToOneNAT, // NatIP (only set if using a reserved public IP) }) // TODO(ericsnow) Will we need to support more access configs? } return &compute.NetworkInterface{ Network: ns.Path(), AccessConfigs: access, } }
[ "func", "(", "ns", "*", "NetworkSpec", ")", "newInterface", "(", "name", "string", ")", "*", "compute", ".", "NetworkInterface", "{", "var", "access", "[", "]", "*", "compute", ".", "AccessConfig", "\n", "if", "name", "!=", "\"", "\"", "{", "// This interface has an internet connection.", "access", "=", "append", "(", "access", ",", "&", "compute", ".", "AccessConfig", "{", "Name", ":", "name", ",", "Type", ":", "NetworkAccessOneToOneNAT", ",", "// NatIP (only set if using a reserved public IP)", "}", ")", "\n", "// TODO(ericsnow) Will we need to support more access configs?", "}", "\n", "return", "&", "compute", ".", "NetworkInterface", "{", "Network", ":", "ns", ".", "Path", "(", ")", ",", "AccessConfigs", ":", "access", ",", "}", "\n", "}" ]
// newInterface builds up all the data needed by the GCE API to create // a new interface connected to the network.
[ "newInterface", "builds", "up", "all", "the", "data", "needed", "by", "the", "GCE", "API", "to", "create", "a", "new", "interface", "connected", "to", "the", "network", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/network.go#L43-L58
4,117
juju/juju
provider/gce/google/network.go
firewallSpec
func firewallSpec(name, target string, sourceCIDRs []string, ports protocolPorts) *compute.Firewall { if len(sourceCIDRs) == 0 { sourceCIDRs = []string{"0.0.0.0/0"} } firewall := compute.Firewall{ // Allowed is set below. // Description is not set. Name: name, // Network: (defaults to global) // SourceTags is not set. TargetTags: []string{target}, SourceRanges: sourceCIDRs, } var sortedProtocols []string for protocol := range ports { sortedProtocols = append(sortedProtocols, protocol) } sort.Strings(sortedProtocols) for _, protocol := range sortedProtocols { allowed := compute.FirewallAllowed{ IPProtocol: protocol, Ports: ports.portStrings(protocol), } firewall.Allowed = append(firewall.Allowed, &allowed) } return &firewall }
go
func firewallSpec(name, target string, sourceCIDRs []string, ports protocolPorts) *compute.Firewall { if len(sourceCIDRs) == 0 { sourceCIDRs = []string{"0.0.0.0/0"} } firewall := compute.Firewall{ // Allowed is set below. // Description is not set. Name: name, // Network: (defaults to global) // SourceTags is not set. TargetTags: []string{target}, SourceRanges: sourceCIDRs, } var sortedProtocols []string for protocol := range ports { sortedProtocols = append(sortedProtocols, protocol) } sort.Strings(sortedProtocols) for _, protocol := range sortedProtocols { allowed := compute.FirewallAllowed{ IPProtocol: protocol, Ports: ports.portStrings(protocol), } firewall.Allowed = append(firewall.Allowed, &allowed) } return &firewall }
[ "func", "firewallSpec", "(", "name", ",", "target", "string", ",", "sourceCIDRs", "[", "]", "string", ",", "ports", "protocolPorts", ")", "*", "compute", ".", "Firewall", "{", "if", "len", "(", "sourceCIDRs", ")", "==", "0", "{", "sourceCIDRs", "=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "}", "\n", "firewall", ":=", "compute", ".", "Firewall", "{", "// Allowed is set below.", "// Description is not set.", "Name", ":", "name", ",", "// Network: (defaults to global)", "// SourceTags is not set.", "TargetTags", ":", "[", "]", "string", "{", "target", "}", ",", "SourceRanges", ":", "sourceCIDRs", ",", "}", "\n\n", "var", "sortedProtocols", "[", "]", "string", "\n", "for", "protocol", ":=", "range", "ports", "{", "sortedProtocols", "=", "append", "(", "sortedProtocols", ",", "protocol", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "sortedProtocols", ")", "\n\n", "for", "_", ",", "protocol", ":=", "range", "sortedProtocols", "{", "allowed", ":=", "compute", ".", "FirewallAllowed", "{", "IPProtocol", ":", "protocol", ",", "Ports", ":", "ports", ".", "portStrings", "(", "protocol", ")", ",", "}", "\n", "firewall", ".", "Allowed", "=", "append", "(", "firewall", ".", "Allowed", ",", "&", "allowed", ")", "\n", "}", "\n", "return", "&", "firewall", "\n", "}" ]
// firewallSpec expands a port range set in to compute.FirewallAllowed // and returns a compute.Firewall for the provided name.
[ "firewallSpec", "expands", "a", "port", "range", "set", "in", "to", "compute", ".", "FirewallAllowed", "and", "returns", "a", "compute", ".", "Firewall", "for", "the", "provided", "name", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/network.go#L62-L90
4,118
juju/juju
apiserver/common/modelstatus.go
ModelStatus
func (c *ModelStatusAPI) ModelStatus(req params.Entities) (params.ModelStatusResults, error) { models := req.Entities status := make([]params.ModelStatus, len(models)) for i, model := range models { modelStatus, err := c.modelStatus(model.Tag) if err != nil { status[i].Error = ServerError(err) continue } status[i] = modelStatus } return params.ModelStatusResults{Results: status}, nil }
go
func (c *ModelStatusAPI) ModelStatus(req params.Entities) (params.ModelStatusResults, error) { models := req.Entities status := make([]params.ModelStatus, len(models)) for i, model := range models { modelStatus, err := c.modelStatus(model.Tag) if err != nil { status[i].Error = ServerError(err) continue } status[i] = modelStatus } return params.ModelStatusResults{Results: status}, nil }
[ "func", "(", "c", "*", "ModelStatusAPI", ")", "ModelStatus", "(", "req", "params", ".", "Entities", ")", "(", "params", ".", "ModelStatusResults", ",", "error", ")", "{", "models", ":=", "req", ".", "Entities", "\n", "status", ":=", "make", "(", "[", "]", "params", ".", "ModelStatus", ",", "len", "(", "models", ")", ")", "\n", "for", "i", ",", "model", ":=", "range", "models", "{", "modelStatus", ",", "err", ":=", "c", ".", "modelStatus", "(", "model", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "status", "[", "i", "]", ".", "Error", "=", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "status", "[", "i", "]", "=", "modelStatus", "\n", "}", "\n", "return", "params", ".", "ModelStatusResults", "{", "Results", ":", "status", "}", ",", "nil", "\n", "}" ]
// ModelStatus returns a summary of the model.
[ "ModelStatus", "returns", "a", "summary", "of", "the", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/modelstatus.go#L32-L44
4,119
juju/juju
apiserver/common/modelstatus.go
ModelFilesystemInfo
func ModelFilesystemInfo(in []state.Filesystem) []params.ModelFilesystemInfo { out := make([]params.ModelFilesystemInfo, len(in)) for i, in := range in { var statusString string status, err := in.Status() if err != nil { statusString = err.Error() } else { statusString = string(status.Status) } var providerId string if info, err := in.Info(); err == nil { providerId = info.FilesystemId } out[i] = params.ModelFilesystemInfo{ Id: in.Tag().Id(), ProviderId: providerId, Status: statusString, Message: status.Message, Detachable: in.Detachable(), } } return out }
go
func ModelFilesystemInfo(in []state.Filesystem) []params.ModelFilesystemInfo { out := make([]params.ModelFilesystemInfo, len(in)) for i, in := range in { var statusString string status, err := in.Status() if err != nil { statusString = err.Error() } else { statusString = string(status.Status) } var providerId string if info, err := in.Info(); err == nil { providerId = info.FilesystemId } out[i] = params.ModelFilesystemInfo{ Id: in.Tag().Id(), ProviderId: providerId, Status: statusString, Message: status.Message, Detachable: in.Detachable(), } } return out }
[ "func", "ModelFilesystemInfo", "(", "in", "[", "]", "state", ".", "Filesystem", ")", "[", "]", "params", ".", "ModelFilesystemInfo", "{", "out", ":=", "make", "(", "[", "]", "params", ".", "ModelFilesystemInfo", ",", "len", "(", "in", ")", ")", "\n", "for", "i", ",", "in", ":=", "range", "in", "{", "var", "statusString", "string", "\n", "status", ",", "err", ":=", "in", ".", "Status", "(", ")", "\n", "if", "err", "!=", "nil", "{", "statusString", "=", "err", ".", "Error", "(", ")", "\n", "}", "else", "{", "statusString", "=", "string", "(", "status", ".", "Status", ")", "\n", "}", "\n", "var", "providerId", "string", "\n", "if", "info", ",", "err", ":=", "in", ".", "Info", "(", ")", ";", "err", "==", "nil", "{", "providerId", "=", "info", ".", "FilesystemId", "\n", "}", "\n", "out", "[", "i", "]", "=", "params", ".", "ModelFilesystemInfo", "{", "Id", ":", "in", ".", "Tag", "(", ")", ".", "Id", "(", ")", ",", "ProviderId", ":", "providerId", ",", "Status", ":", "statusString", ",", "Message", ":", "status", ".", "Message", ",", "Detachable", ":", "in", ".", "Detachable", "(", ")", ",", "}", "\n", "}", "\n", "return", "out", "\n", "}" ]
// ModelFilesystemInfo returns information about filesystems in the model.
[ "ModelFilesystemInfo", "returns", "information", "about", "filesystems", "in", "the", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/modelstatus.go#L126-L149
4,120
juju/juju
apiserver/common/modelstatus.go
ModelVolumeInfo
func ModelVolumeInfo(in []state.Volume) []params.ModelVolumeInfo { out := make([]params.ModelVolumeInfo, len(in)) for i, in := range in { var statusString string status, err := in.Status() if err != nil { statusString = err.Error() } else { statusString = string(status.Status) } var providerId string if info, err := in.Info(); err == nil { providerId = info.VolumeId } out[i] = params.ModelVolumeInfo{ Id: in.Tag().Id(), ProviderId: providerId, Status: statusString, Message: status.Message, Detachable: in.Detachable(), } } return out }
go
func ModelVolumeInfo(in []state.Volume) []params.ModelVolumeInfo { out := make([]params.ModelVolumeInfo, len(in)) for i, in := range in { var statusString string status, err := in.Status() if err != nil { statusString = err.Error() } else { statusString = string(status.Status) } var providerId string if info, err := in.Info(); err == nil { providerId = info.VolumeId } out[i] = params.ModelVolumeInfo{ Id: in.Tag().Id(), ProviderId: providerId, Status: statusString, Message: status.Message, Detachable: in.Detachable(), } } return out }
[ "func", "ModelVolumeInfo", "(", "in", "[", "]", "state", ".", "Volume", ")", "[", "]", "params", ".", "ModelVolumeInfo", "{", "out", ":=", "make", "(", "[", "]", "params", ".", "ModelVolumeInfo", ",", "len", "(", "in", ")", ")", "\n", "for", "i", ",", "in", ":=", "range", "in", "{", "var", "statusString", "string", "\n", "status", ",", "err", ":=", "in", ".", "Status", "(", ")", "\n", "if", "err", "!=", "nil", "{", "statusString", "=", "err", ".", "Error", "(", ")", "\n", "}", "else", "{", "statusString", "=", "string", "(", "status", ".", "Status", ")", "\n", "}", "\n", "var", "providerId", "string", "\n", "if", "info", ",", "err", ":=", "in", ".", "Info", "(", ")", ";", "err", "==", "nil", "{", "providerId", "=", "info", ".", "VolumeId", "\n", "}", "\n", "out", "[", "i", "]", "=", "params", ".", "ModelVolumeInfo", "{", "Id", ":", "in", ".", "Tag", "(", ")", ".", "Id", "(", ")", ",", "ProviderId", ":", "providerId", ",", "Status", ":", "statusString", ",", "Message", ":", "status", ".", "Message", ",", "Detachable", ":", "in", ".", "Detachable", "(", ")", ",", "}", "\n", "}", "\n", "return", "out", "\n", "}" ]
// ModelVolumeInfo returns information about volumes in the model.
[ "ModelVolumeInfo", "returns", "information", "about", "volumes", "in", "the", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/modelstatus.go#L152-L175
4,121
juju/juju
worker/uniter/runner/jujuc/context.go
NewRelationIdValue
func NewRelationIdValue(ctx Context, result *int) (*relationIdValue, error) { v := &relationIdValue{result: result, ctx: ctx} id := -1 if r, err := ctx.HookRelation(); err == nil { id = r.Id() v.value = r.FakeId() } else if !errors.IsNotFound(err) { return nil, errors.Trace(err) } *result = id return v, nil }
go
func NewRelationIdValue(ctx Context, result *int) (*relationIdValue, error) { v := &relationIdValue{result: result, ctx: ctx} id := -1 if r, err := ctx.HookRelation(); err == nil { id = r.Id() v.value = r.FakeId() } else if !errors.IsNotFound(err) { return nil, errors.Trace(err) } *result = id return v, nil }
[ "func", "NewRelationIdValue", "(", "ctx", "Context", ",", "result", "*", "int", ")", "(", "*", "relationIdValue", ",", "error", ")", "{", "v", ":=", "&", "relationIdValue", "{", "result", ":", "result", ",", "ctx", ":", "ctx", "}", "\n", "id", ":=", "-", "1", "\n", "if", "r", ",", "err", ":=", "ctx", ".", "HookRelation", "(", ")", ";", "err", "==", "nil", "{", "id", "=", "r", ".", "Id", "(", ")", "\n", "v", ".", "value", "=", "r", ".", "FakeId", "(", ")", "\n", "}", "else", "if", "!", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "*", "result", "=", "id", "\n", "return", "v", ",", "nil", "\n", "}" ]
// NewRelationIdValue returns a gnuflag.Value for convenient parsing of relation // ids in ctx.
[ "NewRelationIdValue", "returns", "a", "gnuflag", ".", "Value", "for", "convenient", "parsing", "of", "relation", "ids", "in", "ctx", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/jujuc/context.go#L315-L326
4,122
juju/juju
worker/uniter/runner/jujuc/context.go
Set
func (v *relationIdValue) Set(value string) error { trim := value if idx := strings.LastIndex(trim, ":"); idx != -1 { trim = trim[idx+1:] } id, err := strconv.Atoi(trim) if err != nil { return fmt.Errorf("invalid relation id") } if _, err := v.ctx.Relation(id); err != nil { return errors.Trace(err) } *v.result = id v.value = value return nil }
go
func (v *relationIdValue) Set(value string) error { trim := value if idx := strings.LastIndex(trim, ":"); idx != -1 { trim = trim[idx+1:] } id, err := strconv.Atoi(trim) if err != nil { return fmt.Errorf("invalid relation id") } if _, err := v.ctx.Relation(id); err != nil { return errors.Trace(err) } *v.result = id v.value = value return nil }
[ "func", "(", "v", "*", "relationIdValue", ")", "Set", "(", "value", "string", ")", "error", "{", "trim", ":=", "value", "\n", "if", "idx", ":=", "strings", ".", "LastIndex", "(", "trim", ",", "\"", "\"", ")", ";", "idx", "!=", "-", "1", "{", "trim", "=", "trim", "[", "idx", "+", "1", ":", "]", "\n", "}", "\n", "id", ",", "err", ":=", "strconv", ".", "Atoi", "(", "trim", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "v", ".", "ctx", ".", "Relation", "(", "id", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "*", "v", ".", "result", "=", "id", "\n", "v", ".", "value", "=", "value", "\n", "return", "nil", "\n", "}" ]
// Set interprets value as a relation id, if possible, and returns an error // if it is not known to the system. The parsed relation id will be written // to v.result.
[ "Set", "interprets", "value", "as", "a", "relation", "id", "if", "possible", "and", "returns", "an", "error", "if", "it", "is", "not", "known", "to", "the", "system", ".", "The", "parsed", "relation", "id", "will", "be", "written", "to", "v", ".", "result", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/jujuc/context.go#L343-L358
4,123
juju/juju
cmd/juju/common/model.go
FriendlyDuration
func FriendlyDuration(when *time.Time, now time.Time) string { if when == nil { return "" } return UserFriendlyDuration(*when, now) }
go
func FriendlyDuration(when *time.Time, now time.Time) string { if when == nil { return "" } return UserFriendlyDuration(*when, now) }
[ "func", "FriendlyDuration", "(", "when", "*", "time", ".", "Time", ",", "now", "time", ".", "Time", ")", "string", "{", "if", "when", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "UserFriendlyDuration", "(", "*", "when", ",", "now", ")", "\n", "}" ]
// FriendlyDuration renders a time pointer that we get from the API as // a friendly string.
[ "FriendlyDuration", "renders", "a", "time", "pointer", "that", "we", "get", "from", "the", "API", "as", "a", "friendly", "string", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/common/model.go#L72-L77
4,124
juju/juju
cmd/juju/common/model.go
ModelInfoFromParams
func ModelInfoFromParams(info params.ModelInfo, now time.Time) (ModelInfo, error) { ownerTag, err := names.ParseUserTag(info.OwnerTag) if err != nil { return ModelInfo{}, errors.Trace(err) } cloudTag, err := names.ParseCloudTag(info.CloudTag) if err != nil { return ModelInfo{}, errors.Trace(err) } modelInfo := ModelInfo{ ShortName: info.Name, Name: jujuclient.JoinOwnerModelName(ownerTag, info.Name), Type: model.ModelType(info.Type), UUID: info.UUID, ControllerUUID: info.ControllerUUID, IsController: info.IsController, Owner: ownerTag.Id(), Life: string(info.Life), Cloud: cloudTag.Id(), CloudRegion: info.CloudRegion, } if info.AgentVersion != nil { modelInfo.AgentVersion = info.AgentVersion.String() } // Although this may be more performance intensive, we have to use reflection // since structs containing map[string]interface {} cannot be compared, i.e // cannot use simple '==' here. if !reflect.DeepEqual(info.Status, params.EntityStatus{}) { modelInfo.Status = &ModelStatus{ Current: info.Status.Status, Message: info.Status.Info, Since: FriendlyDuration(info.Status.Since, now), } } if info.Migration != nil { status := modelInfo.Status if status == nil { status = &ModelStatus{} modelInfo.Status = status } status.Migration = info.Migration.Status status.MigrationStart = FriendlyDuration(info.Migration.Start, now) status.MigrationEnd = FriendlyDuration(info.Migration.End, now) } if info.ProviderType != "" { modelInfo.ProviderType = info.ProviderType } if len(info.Users) != 0 { modelInfo.Users = ModelUserInfoFromParams(info.Users, now) } if len(info.Machines) != 0 { modelInfo.Machines = ModelMachineInfoFromParams(info.Machines) } if info.SLA != nil { modelInfo.SLA = ModelSLAFromParams(info.SLA) modelInfo.SLAOwner = ModelSLAOwnerFromParams(info.SLA) } if info.CloudCredentialTag != "" { credTag, err := names.ParseCloudCredentialTag(info.CloudCredentialTag) if err != nil { return ModelInfo{}, errors.Trace(err) } modelInfo.Credential = &ModelCredential{ Name: credTag.Name(), Owner: credTag.Owner().Id(), Cloud: credTag.Cloud().Id(), } } return modelInfo, nil }
go
func ModelInfoFromParams(info params.ModelInfo, now time.Time) (ModelInfo, error) { ownerTag, err := names.ParseUserTag(info.OwnerTag) if err != nil { return ModelInfo{}, errors.Trace(err) } cloudTag, err := names.ParseCloudTag(info.CloudTag) if err != nil { return ModelInfo{}, errors.Trace(err) } modelInfo := ModelInfo{ ShortName: info.Name, Name: jujuclient.JoinOwnerModelName(ownerTag, info.Name), Type: model.ModelType(info.Type), UUID: info.UUID, ControllerUUID: info.ControllerUUID, IsController: info.IsController, Owner: ownerTag.Id(), Life: string(info.Life), Cloud: cloudTag.Id(), CloudRegion: info.CloudRegion, } if info.AgentVersion != nil { modelInfo.AgentVersion = info.AgentVersion.String() } // Although this may be more performance intensive, we have to use reflection // since structs containing map[string]interface {} cannot be compared, i.e // cannot use simple '==' here. if !reflect.DeepEqual(info.Status, params.EntityStatus{}) { modelInfo.Status = &ModelStatus{ Current: info.Status.Status, Message: info.Status.Info, Since: FriendlyDuration(info.Status.Since, now), } } if info.Migration != nil { status := modelInfo.Status if status == nil { status = &ModelStatus{} modelInfo.Status = status } status.Migration = info.Migration.Status status.MigrationStart = FriendlyDuration(info.Migration.Start, now) status.MigrationEnd = FriendlyDuration(info.Migration.End, now) } if info.ProviderType != "" { modelInfo.ProviderType = info.ProviderType } if len(info.Users) != 0 { modelInfo.Users = ModelUserInfoFromParams(info.Users, now) } if len(info.Machines) != 0 { modelInfo.Machines = ModelMachineInfoFromParams(info.Machines) } if info.SLA != nil { modelInfo.SLA = ModelSLAFromParams(info.SLA) modelInfo.SLAOwner = ModelSLAOwnerFromParams(info.SLA) } if info.CloudCredentialTag != "" { credTag, err := names.ParseCloudCredentialTag(info.CloudCredentialTag) if err != nil { return ModelInfo{}, errors.Trace(err) } modelInfo.Credential = &ModelCredential{ Name: credTag.Name(), Owner: credTag.Owner().Id(), Cloud: credTag.Cloud().Id(), } } return modelInfo, nil }
[ "func", "ModelInfoFromParams", "(", "info", "params", ".", "ModelInfo", ",", "now", "time", ".", "Time", ")", "(", "ModelInfo", ",", "error", ")", "{", "ownerTag", ",", "err", ":=", "names", ".", "ParseUserTag", "(", "info", ".", "OwnerTag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ModelInfo", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "cloudTag", ",", "err", ":=", "names", ".", "ParseCloudTag", "(", "info", ".", "CloudTag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ModelInfo", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "modelInfo", ":=", "ModelInfo", "{", "ShortName", ":", "info", ".", "Name", ",", "Name", ":", "jujuclient", ".", "JoinOwnerModelName", "(", "ownerTag", ",", "info", ".", "Name", ")", ",", "Type", ":", "model", ".", "ModelType", "(", "info", ".", "Type", ")", ",", "UUID", ":", "info", ".", "UUID", ",", "ControllerUUID", ":", "info", ".", "ControllerUUID", ",", "IsController", ":", "info", ".", "IsController", ",", "Owner", ":", "ownerTag", ".", "Id", "(", ")", ",", "Life", ":", "string", "(", "info", ".", "Life", ")", ",", "Cloud", ":", "cloudTag", ".", "Id", "(", ")", ",", "CloudRegion", ":", "info", ".", "CloudRegion", ",", "}", "\n", "if", "info", ".", "AgentVersion", "!=", "nil", "{", "modelInfo", ".", "AgentVersion", "=", "info", ".", "AgentVersion", ".", "String", "(", ")", "\n", "}", "\n", "// Although this may be more performance intensive, we have to use reflection", "// since structs containing map[string]interface {} cannot be compared, i.e", "// cannot use simple '==' here.", "if", "!", "reflect", ".", "DeepEqual", "(", "info", ".", "Status", ",", "params", ".", "EntityStatus", "{", "}", ")", "{", "modelInfo", ".", "Status", "=", "&", "ModelStatus", "{", "Current", ":", "info", ".", "Status", ".", "Status", ",", "Message", ":", "info", ".", "Status", ".", "Info", ",", "Since", ":", "FriendlyDuration", "(", "info", ".", "Status", ".", "Since", ",", "now", ")", ",", "}", "\n", "}", "\n", "if", "info", ".", "Migration", "!=", "nil", "{", "status", ":=", "modelInfo", ".", "Status", "\n", "if", "status", "==", "nil", "{", "status", "=", "&", "ModelStatus", "{", "}", "\n", "modelInfo", ".", "Status", "=", "status", "\n", "}", "\n", "status", ".", "Migration", "=", "info", ".", "Migration", ".", "Status", "\n", "status", ".", "MigrationStart", "=", "FriendlyDuration", "(", "info", ".", "Migration", ".", "Start", ",", "now", ")", "\n", "status", ".", "MigrationEnd", "=", "FriendlyDuration", "(", "info", ".", "Migration", ".", "End", ",", "now", ")", "\n", "}", "\n\n", "if", "info", ".", "ProviderType", "!=", "\"", "\"", "{", "modelInfo", ".", "ProviderType", "=", "info", ".", "ProviderType", "\n\n", "}", "\n", "if", "len", "(", "info", ".", "Users", ")", "!=", "0", "{", "modelInfo", ".", "Users", "=", "ModelUserInfoFromParams", "(", "info", ".", "Users", ",", "now", ")", "\n", "}", "\n", "if", "len", "(", "info", ".", "Machines", ")", "!=", "0", "{", "modelInfo", ".", "Machines", "=", "ModelMachineInfoFromParams", "(", "info", ".", "Machines", ")", "\n", "}", "\n", "if", "info", ".", "SLA", "!=", "nil", "{", "modelInfo", ".", "SLA", "=", "ModelSLAFromParams", "(", "info", ".", "SLA", ")", "\n", "modelInfo", ".", "SLAOwner", "=", "ModelSLAOwnerFromParams", "(", "info", ".", "SLA", ")", "\n", "}", "\n\n", "if", "info", ".", "CloudCredentialTag", "!=", "\"", "\"", "{", "credTag", ",", "err", ":=", "names", ".", "ParseCloudCredentialTag", "(", "info", ".", "CloudCredentialTag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ModelInfo", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "modelInfo", ".", "Credential", "=", "&", "ModelCredential", "{", "Name", ":", "credTag", ".", "Name", "(", ")", ",", "Owner", ":", "credTag", ".", "Owner", "(", ")", ".", "Id", "(", ")", ",", "Cloud", ":", "credTag", ".", "Cloud", "(", ")", ".", "Id", "(", ")", ",", "}", "\n", "}", "\n\n", "return", "modelInfo", ",", "nil", "\n", "}" ]
// ModelInfoFromParams translates a params.ModelInfo to ModelInfo.
[ "ModelInfoFromParams", "translates", "a", "params", ".", "ModelInfo", "to", "ModelInfo", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/common/model.go#L87-L160
4,125
juju/juju
cmd/juju/common/model.go
OwnerQualifiedModelName
func OwnerQualifiedModelName(modelName string, owner, user names.UserTag) string { if owner.Id() == user.Id() { return modelName } return jujuclient.JoinOwnerModelName(owner, modelName) }
go
func OwnerQualifiedModelName(modelName string, owner, user names.UserTag) string { if owner.Id() == user.Id() { return modelName } return jujuclient.JoinOwnerModelName(owner, modelName) }
[ "func", "OwnerQualifiedModelName", "(", "modelName", "string", ",", "owner", ",", "user", "names", ".", "UserTag", ")", "string", "{", "if", "owner", ".", "Id", "(", ")", "==", "user", ".", "Id", "(", ")", "{", "return", "modelName", "\n", "}", "\n", "return", "jujuclient", ".", "JoinOwnerModelName", "(", "owner", ",", "modelName", ")", "\n", "}" ]
// OwnerQualifiedModelName returns the model name qualified with the // model owner if the owner is not the same as the given canonical // user name. If the owner is a local user, we omit the domain.
[ "OwnerQualifiedModelName", "returns", "the", "model", "name", "qualified", "with", "the", "model", "owner", "if", "the", "owner", "is", "not", "the", "same", "as", "the", "given", "canonical", "user", "name", ".", "If", "the", "owner", "is", "a", "local", "user", "we", "omit", "the", "domain", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/common/model.go#L212-L217
4,126
juju/juju
cmd/juju/resource/charmresources.go
NewCharmResourcesCommand
func NewCharmResourcesCommand(resourceLister ResourceLister) modelcmd.ModelCommand { var c CharmResourcesCommand c.setResourceLister(resourceLister) return modelcmd.Wrap(&c) }
go
func NewCharmResourcesCommand(resourceLister ResourceLister) modelcmd.ModelCommand { var c CharmResourcesCommand c.setResourceLister(resourceLister) return modelcmd.Wrap(&c) }
[ "func", "NewCharmResourcesCommand", "(", "resourceLister", "ResourceLister", ")", "modelcmd", ".", "ModelCommand", "{", "var", "c", "CharmResourcesCommand", "\n", "c", ".", "setResourceLister", "(", "resourceLister", ")", "\n", "return", "modelcmd", ".", "Wrap", "(", "&", "c", ")", "\n", "}" ]
// NewCharmResourcesCommand returns a new command that lists resources defined // by a charm.
[ "NewCharmResourcesCommand", "returns", "a", "new", "command", "that", "lists", "resources", "defined", "by", "a", "charm", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/resource/charmresources.go#L28-L32
4,127
juju/juju
cmd/juju/resource/charmresources.go
ListResources
func (c *baseCharmResourcesCommand) ListResources(ids []charmstore.CharmID) ([][]charmresource.Resource, error) { bakeryClient, err := c.BakeryClient() if err != nil { return nil, errors.Trace(err) } conAPIRoot, err := c.NewControllerAPIRoot() if err != nil { return nil, errors.Trace(err) } csURL, err := getCharmStoreAPIURL(conAPIRoot) if err != nil { return nil, errors.Trace(err) } client, err := charmstore.NewCustomClient(bakeryClient, csURL) if err != nil { return nil, errors.Trace(err) } return client.ListResources(ids) }
go
func (c *baseCharmResourcesCommand) ListResources(ids []charmstore.CharmID) ([][]charmresource.Resource, error) { bakeryClient, err := c.BakeryClient() if err != nil { return nil, errors.Trace(err) } conAPIRoot, err := c.NewControllerAPIRoot() if err != nil { return nil, errors.Trace(err) } csURL, err := getCharmStoreAPIURL(conAPIRoot) if err != nil { return nil, errors.Trace(err) } client, err := charmstore.NewCustomClient(bakeryClient, csURL) if err != nil { return nil, errors.Trace(err) } return client.ListResources(ids) }
[ "func", "(", "c", "*", "baseCharmResourcesCommand", ")", "ListResources", "(", "ids", "[", "]", "charmstore", ".", "CharmID", ")", "(", "[", "]", "[", "]", "charmresource", ".", "Resource", ",", "error", ")", "{", "bakeryClient", ",", "err", ":=", "c", ".", "BakeryClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "conAPIRoot", ",", "err", ":=", "c", ".", "NewControllerAPIRoot", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "csURL", ",", "err", ":=", "getCharmStoreAPIURL", "(", "conAPIRoot", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "client", ",", "err", ":=", "charmstore", ".", "NewCustomClient", "(", "bakeryClient", ",", "csURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "client", ".", "ListResources", "(", "ids", ")", "\n", "}" ]
// ListCharmResources implements CharmResourceLister by getting the charmstore client // from the command's ModelCommandBase.
[ "ListCharmResources", "implements", "CharmResourceLister", "by", "getting", "the", "charmstore", "client", "from", "the", "command", "s", "ModelCommandBase", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/resource/charmresources.go#L161-L179
4,128
juju/juju
worker/pruner/worker.go
Work
func (w *PrunerWorker) Work(getPrunerConfig func(*config.Config) (time.Duration, uint)) error { modelConfigWatcher, err := w.config.Facade.WatchForModelConfigChanges() if err != nil { return errors.Trace(err) } err = w.catacomb.Add(modelConfigWatcher) if err != nil { return errors.Trace(err) } var ( maxAge time.Duration maxCollectionMB uint modelConfigChanges = modelConfigWatcher.Changes() // We will also get an initial event, but need to ensure that event is // received before doing any pruning. ) var timer clock.Timer var timerCh <-chan time.Time for { select { case <-w.catacomb.Dying(): return w.catacomb.ErrDying() case _, ok := <-modelConfigChanges: if !ok { return errors.New("model configuration watcher closed") } modelConfig, err := w.config.Facade.ModelConfig() if err != nil { return errors.Annotate(err, "cannot load model configuration") } newMaxAge, newMaxCollectionMB := getPrunerConfig(modelConfig) if newMaxAge != maxAge || newMaxCollectionMB != maxCollectionMB { logger.Infof("status history config: max age: %v, max collection size %dM for %s (%s)", newMaxAge, newMaxCollectionMB, modelConfig.Name(), modelConfig.UUID()) maxAge = newMaxAge maxCollectionMB = newMaxCollectionMB } if timer == nil { timer = w.config.Clock.NewTimer(w.config.PruneInterval) timerCh = timer.Chan() } case <-timerCh: err := w.config.Facade.Prune(maxAge, int(maxCollectionMB)) if err != nil { return errors.Trace(err) } timer.Reset(w.config.PruneInterval) } } }
go
func (w *PrunerWorker) Work(getPrunerConfig func(*config.Config) (time.Duration, uint)) error { modelConfigWatcher, err := w.config.Facade.WatchForModelConfigChanges() if err != nil { return errors.Trace(err) } err = w.catacomb.Add(modelConfigWatcher) if err != nil { return errors.Trace(err) } var ( maxAge time.Duration maxCollectionMB uint modelConfigChanges = modelConfigWatcher.Changes() // We will also get an initial event, but need to ensure that event is // received before doing any pruning. ) var timer clock.Timer var timerCh <-chan time.Time for { select { case <-w.catacomb.Dying(): return w.catacomb.ErrDying() case _, ok := <-modelConfigChanges: if !ok { return errors.New("model configuration watcher closed") } modelConfig, err := w.config.Facade.ModelConfig() if err != nil { return errors.Annotate(err, "cannot load model configuration") } newMaxAge, newMaxCollectionMB := getPrunerConfig(modelConfig) if newMaxAge != maxAge || newMaxCollectionMB != maxCollectionMB { logger.Infof("status history config: max age: %v, max collection size %dM for %s (%s)", newMaxAge, newMaxCollectionMB, modelConfig.Name(), modelConfig.UUID()) maxAge = newMaxAge maxCollectionMB = newMaxCollectionMB } if timer == nil { timer = w.config.Clock.NewTimer(w.config.PruneInterval) timerCh = timer.Chan() } case <-timerCh: err := w.config.Facade.Prune(maxAge, int(maxCollectionMB)) if err != nil { return errors.Trace(err) } timer.Reset(w.config.PruneInterval) } } }
[ "func", "(", "w", "*", "PrunerWorker", ")", "Work", "(", "getPrunerConfig", "func", "(", "*", "config", ".", "Config", ")", "(", "time", ".", "Duration", ",", "uint", ")", ")", "error", "{", "modelConfigWatcher", ",", "err", ":=", "w", ".", "config", ".", "Facade", ".", "WatchForModelConfigChanges", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "err", "=", "w", ".", "catacomb", ".", "Add", "(", "modelConfigWatcher", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "var", "(", "maxAge", "time", ".", "Duration", "\n", "maxCollectionMB", "uint", "\n", "modelConfigChanges", "=", "modelConfigWatcher", ".", "Changes", "(", ")", "\n", "// We will also get an initial event, but need to ensure that event is", "// received before doing any pruning.", ")", "\n\n", "var", "timer", "clock", ".", "Timer", "\n", "var", "timerCh", "<-", "chan", "time", ".", "Time", "\n", "for", "{", "select", "{", "case", "<-", "w", ".", "catacomb", ".", "Dying", "(", ")", ":", "return", "w", ".", "catacomb", ".", "ErrDying", "(", ")", "\n\n", "case", "_", ",", "ok", ":=", "<-", "modelConfigChanges", ":", "if", "!", "ok", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "modelConfig", ",", "err", ":=", "w", ".", "config", ".", "Facade", ".", "ModelConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "newMaxAge", ",", "newMaxCollectionMB", ":=", "getPrunerConfig", "(", "modelConfig", ")", "\n\n", "if", "newMaxAge", "!=", "maxAge", "||", "newMaxCollectionMB", "!=", "maxCollectionMB", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "newMaxAge", ",", "newMaxCollectionMB", ",", "modelConfig", ".", "Name", "(", ")", ",", "modelConfig", ".", "UUID", "(", ")", ")", "\n", "maxAge", "=", "newMaxAge", "\n", "maxCollectionMB", "=", "newMaxCollectionMB", "\n", "}", "\n", "if", "timer", "==", "nil", "{", "timer", "=", "w", ".", "config", ".", "Clock", ".", "NewTimer", "(", "w", ".", "config", ".", "PruneInterval", ")", "\n", "timerCh", "=", "timer", ".", "Chan", "(", ")", "\n", "}", "\n\n", "case", "<-", "timerCh", ":", "err", ":=", "w", ".", "config", ".", "Facade", ".", "Prune", "(", "maxAge", ",", "int", "(", "maxCollectionMB", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "timer", ".", "Reset", "(", "w", ".", "config", ".", "PruneInterval", ")", "\n", "}", "\n", "}", "\n", "}" ]
// body of generic pruner loop
[ "body", "of", "generic", "pruner", "loop" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/pruner/worker.go#L54-L109
4,129
juju/juju
controller/modelmanager/createmodel.go
finalizeConfig
func finalizeConfig( provider environs.EnvironProvider, cloud environs.CloudSpec, attrs map[string]interface{}, ) (*config.Config, error) { cfg, err := config.New(config.UseDefaults, attrs) if err != nil { return nil, errors.Annotate(err, "creating config from values failed") } cfg, err = provider.PrepareConfig(environs.PrepareConfigParams{ Cloud: cloud, Config: cfg, }) if err != nil { return nil, errors.Annotate(err, "provider config preparation failed") } cfg, err = provider.Validate(cfg, nil) if err != nil { return nil, errors.Annotate(err, "provider config validation failed") } return cfg, nil }
go
func finalizeConfig( provider environs.EnvironProvider, cloud environs.CloudSpec, attrs map[string]interface{}, ) (*config.Config, error) { cfg, err := config.New(config.UseDefaults, attrs) if err != nil { return nil, errors.Annotate(err, "creating config from values failed") } cfg, err = provider.PrepareConfig(environs.PrepareConfigParams{ Cloud: cloud, Config: cfg, }) if err != nil { return nil, errors.Annotate(err, "provider config preparation failed") } cfg, err = provider.Validate(cfg, nil) if err != nil { return nil, errors.Annotate(err, "provider config validation failed") } return cfg, nil }
[ "func", "finalizeConfig", "(", "provider", "environs", ".", "EnvironProvider", ",", "cloud", "environs", ".", "CloudSpec", ",", "attrs", "map", "[", "string", "]", "interface", "{", "}", ",", ")", "(", "*", "config", ".", "Config", ",", "error", ")", "{", "cfg", ",", "err", ":=", "config", ".", "New", "(", "config", ".", "UseDefaults", ",", "attrs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "cfg", ",", "err", "=", "provider", ".", "PrepareConfig", "(", "environs", ".", "PrepareConfigParams", "{", "Cloud", ":", "cloud", ",", "Config", ":", "cfg", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "cfg", ",", "err", "=", "provider", ".", "Validate", "(", "cfg", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "cfg", ",", "nil", "\n", "}" ]
// finalizeConfig creates the config object from attributes, // and calls EnvironProvider.PrepareConfig.
[ "finalizeConfig", "creates", "the", "config", "object", "from", "attributes", "and", "calls", "EnvironProvider", ".", "PrepareConfig", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/controller/modelmanager/createmodel.go#L136-L157
4,130
juju/juju
environs/manual/sshprovisioner/provisioner.go
ProvisionMachine
func ProvisionMachine(args manual.ProvisionMachineArgs) (machineId string, err error) { defer func() { if machineId != "" && err != nil { logger.Errorf("provisioning failed, removing machine %v: %v", machineId, err) if cleanupErr := args.Client.ForceDestroyMachines(machineId); cleanupErr != nil { logger.Errorf("error cleaning up machine: %s", cleanupErr) } machineId = "" } }() // Create the "ubuntu" user and initialise passwordless sudo. We populate // the ubuntu user's authorized_keys file with the public keys in the current // user's ~/.ssh directory. The authenticationworker will later update the // ubuntu user's authorized_keys. if err = InitUbuntuUser(args.Host, args.User, args.AuthorizedKeys, args.Stdin, args.Stdout); err != nil { return "", err } machineParams, err := gatherMachineParams(args.Host) if err != nil { return "", err } // Inform Juju that the machine exists. machineId, err = manual.RecordMachineInState(args.Client, *machineParams) if err != nil { return "", err } provisioningScript, err := args.Client.ProvisioningScript(params.ProvisioningScriptParams{ MachineId: machineId, Nonce: machineParams.Nonce, DisablePackageCommands: !args.EnableOSRefreshUpdate && !args.EnableOSUpgrade, }) if err != nil { logger.Errorf("cannot obtain provisioning script") return "", err } // Finally, provision the machine agent. err = runProvisionScript(provisioningScript, args.Host, args.Stderr) if err != nil { return machineId, err } logger.Infof("Provisioned machine %v", machineId) return machineId, nil }
go
func ProvisionMachine(args manual.ProvisionMachineArgs) (machineId string, err error) { defer func() { if machineId != "" && err != nil { logger.Errorf("provisioning failed, removing machine %v: %v", machineId, err) if cleanupErr := args.Client.ForceDestroyMachines(machineId); cleanupErr != nil { logger.Errorf("error cleaning up machine: %s", cleanupErr) } machineId = "" } }() // Create the "ubuntu" user and initialise passwordless sudo. We populate // the ubuntu user's authorized_keys file with the public keys in the current // user's ~/.ssh directory. The authenticationworker will later update the // ubuntu user's authorized_keys. if err = InitUbuntuUser(args.Host, args.User, args.AuthorizedKeys, args.Stdin, args.Stdout); err != nil { return "", err } machineParams, err := gatherMachineParams(args.Host) if err != nil { return "", err } // Inform Juju that the machine exists. machineId, err = manual.RecordMachineInState(args.Client, *machineParams) if err != nil { return "", err } provisioningScript, err := args.Client.ProvisioningScript(params.ProvisioningScriptParams{ MachineId: machineId, Nonce: machineParams.Nonce, DisablePackageCommands: !args.EnableOSRefreshUpdate && !args.EnableOSUpgrade, }) if err != nil { logger.Errorf("cannot obtain provisioning script") return "", err } // Finally, provision the machine agent. err = runProvisionScript(provisioningScript, args.Host, args.Stderr) if err != nil { return machineId, err } logger.Infof("Provisioned machine %v", machineId) return machineId, nil }
[ "func", "ProvisionMachine", "(", "args", "manual", ".", "ProvisionMachineArgs", ")", "(", "machineId", "string", ",", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "machineId", "!=", "\"", "\"", "&&", "err", "!=", "nil", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "machineId", ",", "err", ")", "\n", "if", "cleanupErr", ":=", "args", ".", "Client", ".", "ForceDestroyMachines", "(", "machineId", ")", ";", "cleanupErr", "!=", "nil", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "cleanupErr", ")", "\n", "}", "\n", "machineId", "=", "\"", "\"", "\n", "}", "\n", "}", "(", ")", "\n\n", "// Create the \"ubuntu\" user and initialise passwordless sudo. We populate", "// the ubuntu user's authorized_keys file with the public keys in the current", "// user's ~/.ssh directory. The authenticationworker will later update the", "// ubuntu user's authorized_keys.", "if", "err", "=", "InitUbuntuUser", "(", "args", ".", "Host", ",", "args", ".", "User", ",", "args", ".", "AuthorizedKeys", ",", "args", ".", "Stdin", ",", "args", ".", "Stdout", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "machineParams", ",", "err", ":=", "gatherMachineParams", "(", "args", ".", "Host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// Inform Juju that the machine exists.", "machineId", ",", "err", "=", "manual", ".", "RecordMachineInState", "(", "args", ".", "Client", ",", "*", "machineParams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "provisioningScript", ",", "err", ":=", "args", ".", "Client", ".", "ProvisioningScript", "(", "params", ".", "ProvisioningScriptParams", "{", "MachineId", ":", "machineId", ",", "Nonce", ":", "machineParams", ".", "Nonce", ",", "DisablePackageCommands", ":", "!", "args", ".", "EnableOSRefreshUpdate", "&&", "!", "args", ".", "EnableOSUpgrade", ",", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "logger", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// Finally, provision the machine agent.", "err", "=", "runProvisionScript", "(", "provisioningScript", ",", "args", ".", "Host", ",", "args", ".", "Stderr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "machineId", ",", "err", "\n", "}", "\n\n", "logger", ".", "Infof", "(", "\"", "\"", ",", "machineId", ")", "\n", "return", "machineId", ",", "nil", "\n", "}" ]
// Provision returns a new machineId and nil if the provision process is done successfully // The func will manual provision a linux machine using as it's default protocol SSH
[ "Provision", "returns", "a", "new", "machineId", "and", "nil", "if", "the", "provision", "process", "is", "done", "successfully", "The", "func", "will", "manual", "provision", "a", "linux", "machine", "using", "as", "it", "s", "default", "protocol", "SSH" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/manual/sshprovisioner/provisioner.go#L20-L70
4,131
juju/juju
worker/common/credentialinvalidator.go
NewCredentialInvalidatorFacade
func NewCredentialInvalidatorFacade(apiCaller base.APICaller) (CredentialAPI, error) { return credentialvalidator.NewFacade(apiCaller), nil }
go
func NewCredentialInvalidatorFacade(apiCaller base.APICaller) (CredentialAPI, error) { return credentialvalidator.NewFacade(apiCaller), nil }
[ "func", "NewCredentialInvalidatorFacade", "(", "apiCaller", "base", ".", "APICaller", ")", "(", "CredentialAPI", ",", "error", ")", "{", "return", "credentialvalidator", ".", "NewFacade", "(", "apiCaller", ")", ",", "nil", "\n", "}" ]
// NewCredentialInvalidatorFacade creates an API facade capable of invalidating credential.
[ "NewCredentialInvalidatorFacade", "creates", "an", "API", "facade", "capable", "of", "invalidating", "credential", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/common/credentialinvalidator.go#L18-L20
4,132
juju/juju
worker/common/credentialinvalidator.go
NewCloudCallContext
func NewCloudCallContext(c CredentialAPI, dying context.Dying) context.ProviderCallContext { return &context.CloudCallContext{ DyingFunc: dying, InvalidateCredentialFunc: c.InvalidateModelCredential, } }
go
func NewCloudCallContext(c CredentialAPI, dying context.Dying) context.ProviderCallContext { return &context.CloudCallContext{ DyingFunc: dying, InvalidateCredentialFunc: c.InvalidateModelCredential, } }
[ "func", "NewCloudCallContext", "(", "c", "CredentialAPI", ",", "dying", "context", ".", "Dying", ")", "context", ".", "ProviderCallContext", "{", "return", "&", "context", ".", "CloudCallContext", "{", "DyingFunc", ":", "dying", ",", "InvalidateCredentialFunc", ":", "c", ".", "InvalidateModelCredential", ",", "}", "\n", "}" ]
// NewCloudCallContext creates a cloud call context to be used by workers.
[ "NewCloudCallContext", "creates", "a", "cloud", "call", "context", "to", "be", "used", "by", "workers", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/common/credentialinvalidator.go#L23-L28
4,133
juju/juju
cmd/juju/block/disablecommand.go
NewDisableCommand
func NewDisableCommand() cmd.Command { return modelcmd.Wrap(&disableCommand{ apiFunc: func(c newAPIRoot) (blockClientAPI, error) { return getBlockAPI(c) }, }) }
go
func NewDisableCommand() cmd.Command { return modelcmd.Wrap(&disableCommand{ apiFunc: func(c newAPIRoot) (blockClientAPI, error) { return getBlockAPI(c) }, }) }
[ "func", "NewDisableCommand", "(", ")", "cmd", ".", "Command", "{", "return", "modelcmd", ".", "Wrap", "(", "&", "disableCommand", "{", "apiFunc", ":", "func", "(", "c", "newAPIRoot", ")", "(", "blockClientAPI", ",", "error", ")", "{", "return", "getBlockAPI", "(", "c", ")", "\n", "}", ",", "}", ")", "\n", "}" ]
// NewDisableCommand returns a disable-command command instance // that will use the default API.
[ "NewDisableCommand", "returns", "a", "disable", "-", "command", "command", "instance", "that", "will", "use", "the", "default", "API", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/block/disablecommand.go#L18-L24
4,134
juju/juju
apiserver/facades/agent/deployer/deployer.go
NewDeployerAPI
func NewDeployerAPI( st *state.State, resources facade.Resources, authorizer facade.Authorizer, ) (*DeployerAPI, error) { if !authorizer.AuthMachineAgent() { return nil, common.ErrPerm } getAuthFunc := func() (common.AuthFunc, error) { // Get all units of the machine and cache them. thisMachineTag := authorizer.GetAuthTag() units, err := getAllUnits(st, thisMachineTag) if err != nil { return nil, err } // Then we just check if the unit is already known. return func(tag names.Tag) bool { for _, unit := range units { // TODO (thumper): remove the names.Tag conversion when gccgo // implements concrete-type-to-interface comparison correctly. if names.Tag(names.NewUnitTag(unit)) == tag { return true } } return false }, nil } getCanWatch := func() (common.AuthFunc, error) { return authorizer.AuthOwner, nil } return &DeployerAPI{ Remover: common.NewRemover(st, true, getAuthFunc), PasswordChanger: common.NewPasswordChanger(st, getAuthFunc), LifeGetter: common.NewLifeGetter(st, getAuthFunc), APIAddresser: common.NewAPIAddresser(st, resources), UnitsWatcher: common.NewUnitsWatcher(st, resources, getCanWatch), StatusSetter: common.NewStatusSetter(st, getAuthFunc), st: st, resources: resources, authorizer: authorizer, }, nil }
go
func NewDeployerAPI( st *state.State, resources facade.Resources, authorizer facade.Authorizer, ) (*DeployerAPI, error) { if !authorizer.AuthMachineAgent() { return nil, common.ErrPerm } getAuthFunc := func() (common.AuthFunc, error) { // Get all units of the machine and cache them. thisMachineTag := authorizer.GetAuthTag() units, err := getAllUnits(st, thisMachineTag) if err != nil { return nil, err } // Then we just check if the unit is already known. return func(tag names.Tag) bool { for _, unit := range units { // TODO (thumper): remove the names.Tag conversion when gccgo // implements concrete-type-to-interface comparison correctly. if names.Tag(names.NewUnitTag(unit)) == tag { return true } } return false }, nil } getCanWatch := func() (common.AuthFunc, error) { return authorizer.AuthOwner, nil } return &DeployerAPI{ Remover: common.NewRemover(st, true, getAuthFunc), PasswordChanger: common.NewPasswordChanger(st, getAuthFunc), LifeGetter: common.NewLifeGetter(st, getAuthFunc), APIAddresser: common.NewAPIAddresser(st, resources), UnitsWatcher: common.NewUnitsWatcher(st, resources, getCanWatch), StatusSetter: common.NewStatusSetter(st, getAuthFunc), st: st, resources: resources, authorizer: authorizer, }, nil }
[ "func", "NewDeployerAPI", "(", "st", "*", "state", ".", "State", ",", "resources", "facade", ".", "Resources", ",", "authorizer", "facade", ".", "Authorizer", ",", ")", "(", "*", "DeployerAPI", ",", "error", ")", "{", "if", "!", "authorizer", ".", "AuthMachineAgent", "(", ")", "{", "return", "nil", ",", "common", ".", "ErrPerm", "\n", "}", "\n", "getAuthFunc", ":=", "func", "(", ")", "(", "common", ".", "AuthFunc", ",", "error", ")", "{", "// Get all units of the machine and cache them.", "thisMachineTag", ":=", "authorizer", ".", "GetAuthTag", "(", ")", "\n", "units", ",", "err", ":=", "getAllUnits", "(", "st", ",", "thisMachineTag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// Then we just check if the unit is already known.", "return", "func", "(", "tag", "names", ".", "Tag", ")", "bool", "{", "for", "_", ",", "unit", ":=", "range", "units", "{", "// TODO (thumper): remove the names.Tag conversion when gccgo", "// implements concrete-type-to-interface comparison correctly.", "if", "names", ".", "Tag", "(", "names", ".", "NewUnitTag", "(", "unit", ")", ")", "==", "tag", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}", ",", "nil", "\n", "}", "\n", "getCanWatch", ":=", "func", "(", ")", "(", "common", ".", "AuthFunc", ",", "error", ")", "{", "return", "authorizer", ".", "AuthOwner", ",", "nil", "\n", "}", "\n", "return", "&", "DeployerAPI", "{", "Remover", ":", "common", ".", "NewRemover", "(", "st", ",", "true", ",", "getAuthFunc", ")", ",", "PasswordChanger", ":", "common", ".", "NewPasswordChanger", "(", "st", ",", "getAuthFunc", ")", ",", "LifeGetter", ":", "common", ".", "NewLifeGetter", "(", "st", ",", "getAuthFunc", ")", ",", "APIAddresser", ":", "common", ".", "NewAPIAddresser", "(", "st", ",", "resources", ")", ",", "UnitsWatcher", ":", "common", ".", "NewUnitsWatcher", "(", "st", ",", "resources", ",", "getCanWatch", ")", ",", "StatusSetter", ":", "common", ".", "NewStatusSetter", "(", "st", ",", "getAuthFunc", ")", ",", "st", ":", "st", ",", "resources", ":", "resources", ",", "authorizer", ":", "authorizer", ",", "}", ",", "nil", "\n", "}" ]
// NewDeployerAPI creates a new server-side DeployerAPI facade.
[ "NewDeployerAPI", "creates", "a", "new", "server", "-", "side", "DeployerAPI", "facade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/deployer/deployer.go#L32-L73
4,135
juju/juju
apiserver/facades/agent/deployer/deployer.go
SetStatus
func (d *DeployerAPI) SetStatus(args params.SetStatus) (params.ErrorResults, error) { return d.StatusSetter.SetStatus(args) }
go
func (d *DeployerAPI) SetStatus(args params.SetStatus) (params.ErrorResults, error) { return d.StatusSetter.SetStatus(args) }
[ "func", "(", "d", "*", "DeployerAPI", ")", "SetStatus", "(", "args", "params", ".", "SetStatus", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "return", "d", ".", "StatusSetter", ".", "SetStatus", "(", "args", ")", "\n", "}" ]
// SetStatus sets the status of the specified entities.
[ "SetStatus", "sets", "the", "status", "of", "the", "specified", "entities", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/deployer/deployer.go#L89-L91
4,136
juju/juju
apiserver/facades/agent/deployer/deployer.go
getAllUnits
func getAllUnits(st *state.State, tag names.Tag) ([]string, error) { machine, err := st.Machine(tag.Id()) if err != nil { return nil, err } // Start a watcher on machine's units, read the initial event and stop it. watch := machine.WatchUnits() defer watch.Stop() if units, ok := <-watch.Changes(); ok { return units, nil } return nil, fmt.Errorf("cannot obtain units of machine %q: %v", tag, watch.Err()) }
go
func getAllUnits(st *state.State, tag names.Tag) ([]string, error) { machine, err := st.Machine(tag.Id()) if err != nil { return nil, err } // Start a watcher on machine's units, read the initial event and stop it. watch := machine.WatchUnits() defer watch.Stop() if units, ok := <-watch.Changes(); ok { return units, nil } return nil, fmt.Errorf("cannot obtain units of machine %q: %v", tag, watch.Err()) }
[ "func", "getAllUnits", "(", "st", "*", "state", ".", "State", ",", "tag", "names", ".", "Tag", ")", "(", "[", "]", "string", ",", "error", ")", "{", "machine", ",", "err", ":=", "st", ".", "Machine", "(", "tag", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// Start a watcher on machine's units, read the initial event and stop it.", "watch", ":=", "machine", ".", "WatchUnits", "(", ")", "\n", "defer", "watch", ".", "Stop", "(", ")", "\n", "if", "units", ",", "ok", ":=", "<-", "watch", ".", "Changes", "(", ")", ";", "ok", "{", "return", "units", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "tag", ",", "watch", ".", "Err", "(", ")", ")", "\n", "}" ]
// getAllUnits returns a list of all principal and subordinate units // assigned to the given machine.
[ "getAllUnits", "returns", "a", "list", "of", "all", "principal", "and", "subordinate", "units", "assigned", "to", "the", "given", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/deployer/deployer.go#L95-L107
4,137
juju/juju
cmd/juju/backups/restore.go
NewRestoreCommand
func NewRestoreCommand() cmd.Command { c := &restoreCommand{} c.getModelStatusAPI = func() (ModelStatusAPI, error) { return c.NewModelManagerAPIClient() } return modelcmd.Wrap(c) }
go
func NewRestoreCommand() cmd.Command { c := &restoreCommand{} c.getModelStatusAPI = func() (ModelStatusAPI, error) { return c.NewModelManagerAPIClient() } return modelcmd.Wrap(c) }
[ "func", "NewRestoreCommand", "(", ")", "cmd", ".", "Command", "{", "c", ":=", "&", "restoreCommand", "{", "}", "\n", "c", ".", "getModelStatusAPI", "=", "func", "(", ")", "(", "ModelStatusAPI", ",", "error", ")", "{", "return", "c", ".", "NewModelManagerAPIClient", "(", ")", "}", "\n", "return", "modelcmd", ".", "Wrap", "(", "c", ")", "\n", "}" ]
// NewRestoreCommand returns a command used to restore a backup.
[ "NewRestoreCommand", "returns", "a", "command", "used", "to", "restore", "a", "backup", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/backups/restore.go#L29-L33
4,138
juju/juju
cmd/juju/backups/restore.go
SetFlags
func (c *restoreCommand) SetFlags(f *gnuflag.FlagSet) { c.CommandBase.SetFlags(f) f.StringVar(&c.Filename, "file", "", "Provide a file to be used as the backup") f.StringVar(&c.BackupId, "id", "", "Provide the name of the backup to be restored") }
go
func (c *restoreCommand) SetFlags(f *gnuflag.FlagSet) { c.CommandBase.SetFlags(f) f.StringVar(&c.Filename, "file", "", "Provide a file to be used as the backup") f.StringVar(&c.BackupId, "id", "", "Provide the name of the backup to be restored") }
[ "func", "(", "c", "*", "restoreCommand", ")", "SetFlags", "(", "f", "*", "gnuflag", ".", "FlagSet", ")", "{", "c", ".", "CommandBase", ".", "SetFlags", "(", "f", ")", "\n", "f", ".", "StringVar", "(", "&", "c", ".", "Filename", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "f", ".", "StringVar", "(", "&", "c", ".", "BackupId", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}" ]
// SetFlags handles known option flags.
[ "SetFlags", "handles", "known", "option", "flags", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/backups/restore.go#L92-L96
4,139
juju/juju
cmd/juju/backups/restore.go
Init
func (c *restoreCommand) Init(args []string) error { if c.Filename == "" && c.BackupId == "" { return errors.Errorf("you must specify either a file or a backup id.") } if c.Filename != "" && c.BackupId != "" { return errors.Errorf("you must specify either a file or a backup id but not both.") } if c.Filename != "" { var err error c.Filename, err = filepath.Abs(c.Filename) if err != nil { return errors.Trace(err) } } return nil }
go
func (c *restoreCommand) Init(args []string) error { if c.Filename == "" && c.BackupId == "" { return errors.Errorf("you must specify either a file or a backup id.") } if c.Filename != "" && c.BackupId != "" { return errors.Errorf("you must specify either a file or a backup id but not both.") } if c.Filename != "" { var err error c.Filename, err = filepath.Abs(c.Filename) if err != nil { return errors.Trace(err) } } return nil }
[ "func", "(", "c", "*", "restoreCommand", ")", "Init", "(", "args", "[", "]", "string", ")", "error", "{", "if", "c", ".", "Filename", "==", "\"", "\"", "&&", "c", ".", "BackupId", "==", "\"", "\"", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "Filename", "!=", "\"", "\"", "&&", "c", ".", "BackupId", "!=", "\"", "\"", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "c", ".", "Filename", "!=", "\"", "\"", "{", "var", "err", "error", "\n", "c", ".", "Filename", ",", "err", "=", "filepath", ".", "Abs", "(", "c", ".", "Filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Init is where the preconditions for this command can be checked.
[ "Init", "is", "where", "the", "preconditions", "for", "this", "command", "can", "be", "checked", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/backups/restore.go#L99-L116
4,140
juju/juju
cmd/juju/backups/restore.go
Run
func (c *restoreCommand) Run(ctx *cmd.Context) error { if err := c.validateIaasController(c.Info().Name); err != nil { return errors.Trace(err) } if c.Log != nil { if err := c.Log.Start(ctx); err != nil { return err } } // Don't allow restore in an HA environment controllerModelUUID, modelStatus, err := c.modelStatus() if err != nil { return errors.Trace(err) } activeCount, _ := controller.ControllerMachineCounts(controllerModelUUID, modelStatus) if activeCount > 1 { return errors.Errorf("unable to restore backup in HA configuration. For help see https://docs.jujucharms.com/stable/controllers-backup") } var archive ArchiveReader var meta *params.BackupsMetadataResult target := c.BackupId if c.Filename != "" { // Read archive specified by the Filename target = c.Filename var err error archive, meta, err = getArchive(c.Filename) if err != nil { return errors.Trace(err) } defer archive.Close() } client, err := c.NewAPIClient() if err != nil { return errors.Trace(err) } defer client.Close() // We have a backup client, now use the relevant method // to restore the backup. if c.Filename != "" { err = client.RestoreReader(archive, meta, c.newClient) } else { err = client.Restore(c.BackupId, c.newClient) } if err != nil { return errors.Trace(err) } fmt.Fprintf(ctx.Stdout, "restore from %q completed\n", target) return nil }
go
func (c *restoreCommand) Run(ctx *cmd.Context) error { if err := c.validateIaasController(c.Info().Name); err != nil { return errors.Trace(err) } if c.Log != nil { if err := c.Log.Start(ctx); err != nil { return err } } // Don't allow restore in an HA environment controllerModelUUID, modelStatus, err := c.modelStatus() if err != nil { return errors.Trace(err) } activeCount, _ := controller.ControllerMachineCounts(controllerModelUUID, modelStatus) if activeCount > 1 { return errors.Errorf("unable to restore backup in HA configuration. For help see https://docs.jujucharms.com/stable/controllers-backup") } var archive ArchiveReader var meta *params.BackupsMetadataResult target := c.BackupId if c.Filename != "" { // Read archive specified by the Filename target = c.Filename var err error archive, meta, err = getArchive(c.Filename) if err != nil { return errors.Trace(err) } defer archive.Close() } client, err := c.NewAPIClient() if err != nil { return errors.Trace(err) } defer client.Close() // We have a backup client, now use the relevant method // to restore the backup. if c.Filename != "" { err = client.RestoreReader(archive, meta, c.newClient) } else { err = client.Restore(c.BackupId, c.newClient) } if err != nil { return errors.Trace(err) } fmt.Fprintf(ctx.Stdout, "restore from %q completed\n", target) return nil }
[ "func", "(", "c", "*", "restoreCommand", ")", "Run", "(", "ctx", "*", "cmd", ".", "Context", ")", "error", "{", "if", "err", ":=", "c", ".", "validateIaasController", "(", "c", ".", "Info", "(", ")", ".", "Name", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "c", ".", "Log", "!=", "nil", "{", "if", "err", ":=", "c", ".", "Log", ".", "Start", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// Don't allow restore in an HA environment", "controllerModelUUID", ",", "modelStatus", ",", "err", ":=", "c", ".", "modelStatus", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "activeCount", ",", "_", ":=", "controller", ".", "ControllerMachineCounts", "(", "controllerModelUUID", ",", "modelStatus", ")", "\n", "if", "activeCount", ">", "1", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "archive", "ArchiveReader", "\n", "var", "meta", "*", "params", ".", "BackupsMetadataResult", "\n", "target", ":=", "c", ".", "BackupId", "\n", "if", "c", ".", "Filename", "!=", "\"", "\"", "{", "// Read archive specified by the Filename", "target", "=", "c", ".", "Filename", "\n", "var", "err", "error", "\n", "archive", ",", "meta", ",", "err", "=", "getArchive", "(", "c", ".", "Filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "defer", "archive", ".", "Close", "(", ")", "\n", "}", "\n\n", "client", ",", "err", ":=", "c", ".", "NewAPIClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "defer", "client", ".", "Close", "(", ")", "\n\n", "// We have a backup client, now use the relevant method", "// to restore the backup.", "if", "c", ".", "Filename", "!=", "\"", "\"", "{", "err", "=", "client", ".", "RestoreReader", "(", "archive", ",", "meta", ",", "c", ".", "newClient", ")", "\n", "}", "else", "{", "err", "=", "client", ".", "Restore", "(", "c", ".", "BackupId", ",", "c", ".", "newClient", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "ctx", ".", "Stdout", ",", "\"", "\\n", "\"", ",", "target", ")", "\n", "return", "nil", "\n", "}" ]
// Run is the entry point for this command.
[ "Run", "is", "the", "entry", "point", "for", "this", "command", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/backups/restore.go#L160-L212
4,141
juju/juju
worker/agentconfigupdater/worker.go
NewWorker
func NewWorker(config WorkerConfig) (worker.Worker, error) { if err := config.Validate(); err != nil { return nil, errors.Trace(err) } started := make(chan struct{}) w := &agentConfigUpdater{ config: config, mongoProfile: config.MongoProfile, } w.tomb.Go(func() error { return w.loop(started) }) select { case <-started: case <-time.After(10 * time.Second): return nil, errors.New("worker failed to start properly") } return w, nil }
go
func NewWorker(config WorkerConfig) (worker.Worker, error) { if err := config.Validate(); err != nil { return nil, errors.Trace(err) } started := make(chan struct{}) w := &agentConfigUpdater{ config: config, mongoProfile: config.MongoProfile, } w.tomb.Go(func() error { return w.loop(started) }) select { case <-started: case <-time.After(10 * time.Second): return nil, errors.New("worker failed to start properly") } return w, nil }
[ "func", "NewWorker", "(", "config", "WorkerConfig", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "if", "err", ":=", "config", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "started", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "w", ":=", "&", "agentConfigUpdater", "{", "config", ":", "config", ",", "mongoProfile", ":", "config", ".", "MongoProfile", ",", "}", "\n", "w", ".", "tomb", ".", "Go", "(", "func", "(", ")", "error", "{", "return", "w", ".", "loop", "(", "started", ")", "\n", "}", ")", "\n", "select", "{", "case", "<-", "started", ":", "case", "<-", "time", ".", "After", "(", "10", "*", "time", ".", "Second", ")", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "w", ",", "nil", "\n", "}" ]
// NewWorker creates a new agent config updater worker.
[ "NewWorker", "creates", "a", "new", "agent", "config", "updater", "worker", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/agentconfigupdater/worker.go#L51-L70
4,142
juju/juju
state/singular.go
SingularClaimer
func (st *State) SingularClaimer() lease.Claimer { return lazyLeaseClaimer{func() (lease.Claimer, error) { manager := st.workers.singularManager() return manager.Claimer(singularControllerNamespace, st.modelUUID()) }} }
go
func (st *State) SingularClaimer() lease.Claimer { return lazyLeaseClaimer{func() (lease.Claimer, error) { manager := st.workers.singularManager() return manager.Claimer(singularControllerNamespace, st.modelUUID()) }} }
[ "func", "(", "st", "*", "State", ")", "SingularClaimer", "(", ")", "lease", ".", "Claimer", "{", "return", "lazyLeaseClaimer", "{", "func", "(", ")", "(", "lease", ".", "Claimer", ",", "error", ")", "{", "manager", ":=", "st", ".", "workers", ".", "singularManager", "(", ")", "\n", "return", "manager", ".", "Claimer", "(", "singularControllerNamespace", ",", "st", ".", "modelUUID", "(", ")", ")", "\n", "}", "}", "\n", "}" ]
// SingularClaimer returns a lease.Claimer representing the exclusive right to // manage the model.
[ "SingularClaimer", "returns", "a", "lease", ".", "Claimer", "representing", "the", "exclusive", "right", "to", "manage", "the", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/singular.go#L12-L17
4,143
juju/juju
state/endpoint.go
counterpartRole
func counterpartRole(r charm.RelationRole) charm.RelationRole { switch r { case charm.RoleProvider: return charm.RoleRequirer case charm.RoleRequirer: return charm.RoleProvider case charm.RolePeer: return charm.RolePeer } panic(fmt.Errorf("unknown relation role %q", r)) }
go
func counterpartRole(r charm.RelationRole) charm.RelationRole { switch r { case charm.RoleProvider: return charm.RoleRequirer case charm.RoleRequirer: return charm.RoleProvider case charm.RolePeer: return charm.RolePeer } panic(fmt.Errorf("unknown relation role %q", r)) }
[ "func", "counterpartRole", "(", "r", "charm", ".", "RelationRole", ")", "charm", ".", "RelationRole", "{", "switch", "r", "{", "case", "charm", ".", "RoleProvider", ":", "return", "charm", ".", "RoleRequirer", "\n", "case", "charm", ".", "RoleRequirer", ":", "return", "charm", ".", "RoleProvider", "\n", "case", "charm", ".", "RolePeer", ":", "return", "charm", ".", "RolePeer", "\n", "}", "\n", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "r", ")", ")", "\n", "}" ]
// counterpartRole returns the RelationRole that this RelationRole // can relate to. // This should remain an internal method because the relation // model does not guarantee that for every role there will // necessarily exist a single counterpart role that is sensible // for basing algorithms upon.
[ "counterpartRole", "returns", "the", "RelationRole", "that", "this", "RelationRole", "can", "relate", "to", ".", "This", "should", "remain", "an", "internal", "method", "because", "the", "relation", "model", "does", "not", "guarantee", "that", "for", "every", "role", "there", "will", "necessarily", "exist", "a", "single", "counterpart", "role", "that", "is", "sensible", "for", "basing", "algorithms", "upon", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/endpoint.go#L18-L28
4,144
juju/juju
state/endpoint.go
CanRelateTo
func (ep Endpoint) CanRelateTo(other Endpoint) bool { return ep.ApplicationName != other.ApplicationName && ep.Interface == other.Interface && ep.Role != charm.RolePeer && counterpartRole(ep.Role) == other.Role }
go
func (ep Endpoint) CanRelateTo(other Endpoint) bool { return ep.ApplicationName != other.ApplicationName && ep.Interface == other.Interface && ep.Role != charm.RolePeer && counterpartRole(ep.Role) == other.Role }
[ "func", "(", "ep", "Endpoint", ")", "CanRelateTo", "(", "other", "Endpoint", ")", "bool", "{", "return", "ep", ".", "ApplicationName", "!=", "other", ".", "ApplicationName", "&&", "ep", ".", "Interface", "==", "other", ".", "Interface", "&&", "ep", ".", "Role", "!=", "charm", ".", "RolePeer", "&&", "counterpartRole", "(", "ep", ".", "Role", ")", "==", "other", ".", "Role", "\n", "}" ]
// CanRelateTo returns whether a relation may be established between e and other.
[ "CanRelateTo", "returns", "whether", "a", "relation", "may", "be", "established", "between", "e", "and", "other", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/endpoint.go#L45-L50
4,145
juju/juju
apiserver/facades/controller/firewaller/firewaller.go
NewStateFirewallerAPIV3
func NewStateFirewallerAPIV3(context facade.Context) (*FirewallerAPIV3, error) { st := context.State() m, err := st.Model() if err != nil { return nil, errors.Trace(err) } cloudSpecAPI := cloudspec.NewCloudSpec( context.Resources(), cloudspec.MakeCloudSpecGetterForModel(st), cloudspec.MakeCloudSpecWatcherForModel(st), common.AuthFuncForTag(m.ModelTag()), ) return NewFirewallerAPI(stateShim{st: st, State: firewall.StateShim(st, m)}, context.Resources(), context.Auth(), cloudSpecAPI) }
go
func NewStateFirewallerAPIV3(context facade.Context) (*FirewallerAPIV3, error) { st := context.State() m, err := st.Model() if err != nil { return nil, errors.Trace(err) } cloudSpecAPI := cloudspec.NewCloudSpec( context.Resources(), cloudspec.MakeCloudSpecGetterForModel(st), cloudspec.MakeCloudSpecWatcherForModel(st), common.AuthFuncForTag(m.ModelTag()), ) return NewFirewallerAPI(stateShim{st: st, State: firewall.StateShim(st, m)}, context.Resources(), context.Auth(), cloudSpecAPI) }
[ "func", "NewStateFirewallerAPIV3", "(", "context", "facade", ".", "Context", ")", "(", "*", "FirewallerAPIV3", ",", "error", ")", "{", "st", ":=", "context", ".", "State", "(", ")", "\n\n", "m", ",", "err", ":=", "st", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "cloudSpecAPI", ":=", "cloudspec", ".", "NewCloudSpec", "(", "context", ".", "Resources", "(", ")", ",", "cloudspec", ".", "MakeCloudSpecGetterForModel", "(", "st", ")", ",", "cloudspec", ".", "MakeCloudSpecWatcherForModel", "(", "st", ")", ",", "common", ".", "AuthFuncForTag", "(", "m", ".", "ModelTag", "(", ")", ")", ",", ")", "\n", "return", "NewFirewallerAPI", "(", "stateShim", "{", "st", ":", "st", ",", "State", ":", "firewall", ".", "StateShim", "(", "st", ",", "m", ")", "}", ",", "context", ".", "Resources", "(", ")", ",", "context", ".", "Auth", "(", ")", ",", "cloudSpecAPI", ")", "\n", "}" ]
// NewStateFirewallerAPIV3 creates a new server-side FirewallerAPIV3 facade.
[ "NewStateFirewallerAPIV3", "creates", "a", "new", "server", "-", "side", "FirewallerAPIV3", "facade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/firewaller/firewaller.go#L55-L70
4,146
juju/juju
apiserver/facades/controller/firewaller/firewaller.go
NewStateFirewallerAPIV4
func NewStateFirewallerAPIV4(context facade.Context) (*FirewallerAPIV4, error) { facadev3, err := NewStateFirewallerAPIV3(context) if err != nil { return nil, err } return &FirewallerAPIV4{ ControllerConfigAPI: common.NewStateControllerConfig(context.State()), FirewallerAPIV3: facadev3, }, nil }
go
func NewStateFirewallerAPIV4(context facade.Context) (*FirewallerAPIV4, error) { facadev3, err := NewStateFirewallerAPIV3(context) if err != nil { return nil, err } return &FirewallerAPIV4{ ControllerConfigAPI: common.NewStateControllerConfig(context.State()), FirewallerAPIV3: facadev3, }, nil }
[ "func", "NewStateFirewallerAPIV4", "(", "context", "facade", ".", "Context", ")", "(", "*", "FirewallerAPIV4", ",", "error", ")", "{", "facadev3", ",", "err", ":=", "NewStateFirewallerAPIV3", "(", "context", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "FirewallerAPIV4", "{", "ControllerConfigAPI", ":", "common", ".", "NewStateControllerConfig", "(", "context", ".", "State", "(", ")", ")", ",", "FirewallerAPIV3", ":", "facadev3", ",", "}", ",", "nil", "\n", "}" ]
// NewStateFirewallerAPIV4 creates a new server-side FirewallerAPIV4 facade.
[ "NewStateFirewallerAPIV4", "creates", "a", "new", "server", "-", "side", "FirewallerAPIV4", "facade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/firewaller/firewaller.go#L73-L82
4,147
juju/juju
apiserver/facades/controller/firewaller/firewaller.go
NewStateFirewallerAPIV5
func NewStateFirewallerAPIV5(context facade.Context) (*FirewallerAPIV5, error) { facadev4, err := NewStateFirewallerAPIV4(context) if err != nil { return nil, err } return &FirewallerAPIV5{ FirewallerAPIV4: facadev4, }, nil }
go
func NewStateFirewallerAPIV5(context facade.Context) (*FirewallerAPIV5, error) { facadev4, err := NewStateFirewallerAPIV4(context) if err != nil { return nil, err } return &FirewallerAPIV5{ FirewallerAPIV4: facadev4, }, nil }
[ "func", "NewStateFirewallerAPIV5", "(", "context", "facade", ".", "Context", ")", "(", "*", "FirewallerAPIV5", ",", "error", ")", "{", "facadev4", ",", "err", ":=", "NewStateFirewallerAPIV4", "(", "context", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "FirewallerAPIV5", "{", "FirewallerAPIV4", ":", "facadev4", ",", "}", ",", "nil", "\n", "}" ]
// NewStateFirewallerAPIV5 creates a new server-side FirewallerAPIV5 facade.
[ "NewStateFirewallerAPIV5", "creates", "a", "new", "server", "-", "side", "FirewallerAPIV5", "facade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/firewaller/firewaller.go#L85-L93
4,148
juju/juju
apiserver/facades/controller/firewaller/firewaller.go
NewFirewallerAPI
func NewFirewallerAPI( st State, resources facade.Resources, authorizer facade.Authorizer, cloudSpecAPI cloudspec.CloudSpecAPI, ) (*FirewallerAPIV3, error) { if !authorizer.AuthController() { // Firewaller must run as a controller. return nil, common.ErrPerm } // Set up the various authorization checkers. accessModel := common.AuthFuncForTagKind(names.ModelTagKind) accessUnit := common.AuthFuncForTagKind(names.UnitTagKind) accessApplication := common.AuthFuncForTagKind(names.ApplicationTagKind) accessMachine := common.AuthFuncForTagKind(names.MachineTagKind) accessRelation := common.AuthFuncForTagKind(names.RelationTagKind) accessUnitApplicationOrMachineOrRelation := common.AuthAny(accessUnit, accessApplication, accessMachine, accessRelation) // Life() is supported for units, applications or machines. lifeGetter := common.NewLifeGetter( st, accessUnitApplicationOrMachineOrRelation, ) // ModelConfig() and WatchForModelConfigChanges() are allowed // with unrestricted access. modelWatcher := common.NewModelWatcher( st, resources, authorizer, ) // Watch() is supported for applications only. entityWatcher := common.NewAgentEntityWatcher( st, resources, accessApplication, ) // WatchUnits() is supported for machines. unitsWatcher := common.NewUnitsWatcher(st, resources, accessMachine, ) // WatchModelMachines() is allowed with unrestricted access. machinesWatcher := common.NewModelMachinesWatcher( st, resources, authorizer, ) // InstanceId() is supported for machines. instanceIdGetter := common.NewInstanceIdGetter( st, accessMachine, ) return &FirewallerAPIV3{ LifeGetter: lifeGetter, ModelWatcher: modelWatcher, AgentEntityWatcher: entityWatcher, UnitsWatcher: unitsWatcher, ModelMachinesWatcher: machinesWatcher, InstanceIdGetter: instanceIdGetter, CloudSpecAPI: cloudSpecAPI, st: st, resources: resources, authorizer: authorizer, accessUnit: accessUnit, accessApplication: accessApplication, accessMachine: accessMachine, accessModel: accessModel, }, nil }
go
func NewFirewallerAPI( st State, resources facade.Resources, authorizer facade.Authorizer, cloudSpecAPI cloudspec.CloudSpecAPI, ) (*FirewallerAPIV3, error) { if !authorizer.AuthController() { // Firewaller must run as a controller. return nil, common.ErrPerm } // Set up the various authorization checkers. accessModel := common.AuthFuncForTagKind(names.ModelTagKind) accessUnit := common.AuthFuncForTagKind(names.UnitTagKind) accessApplication := common.AuthFuncForTagKind(names.ApplicationTagKind) accessMachine := common.AuthFuncForTagKind(names.MachineTagKind) accessRelation := common.AuthFuncForTagKind(names.RelationTagKind) accessUnitApplicationOrMachineOrRelation := common.AuthAny(accessUnit, accessApplication, accessMachine, accessRelation) // Life() is supported for units, applications or machines. lifeGetter := common.NewLifeGetter( st, accessUnitApplicationOrMachineOrRelation, ) // ModelConfig() and WatchForModelConfigChanges() are allowed // with unrestricted access. modelWatcher := common.NewModelWatcher( st, resources, authorizer, ) // Watch() is supported for applications only. entityWatcher := common.NewAgentEntityWatcher( st, resources, accessApplication, ) // WatchUnits() is supported for machines. unitsWatcher := common.NewUnitsWatcher(st, resources, accessMachine, ) // WatchModelMachines() is allowed with unrestricted access. machinesWatcher := common.NewModelMachinesWatcher( st, resources, authorizer, ) // InstanceId() is supported for machines. instanceIdGetter := common.NewInstanceIdGetter( st, accessMachine, ) return &FirewallerAPIV3{ LifeGetter: lifeGetter, ModelWatcher: modelWatcher, AgentEntityWatcher: entityWatcher, UnitsWatcher: unitsWatcher, ModelMachinesWatcher: machinesWatcher, InstanceIdGetter: instanceIdGetter, CloudSpecAPI: cloudSpecAPI, st: st, resources: resources, authorizer: authorizer, accessUnit: accessUnit, accessApplication: accessApplication, accessMachine: accessMachine, accessModel: accessModel, }, nil }
[ "func", "NewFirewallerAPI", "(", "st", "State", ",", "resources", "facade", ".", "Resources", ",", "authorizer", "facade", ".", "Authorizer", ",", "cloudSpecAPI", "cloudspec", ".", "CloudSpecAPI", ",", ")", "(", "*", "FirewallerAPIV3", ",", "error", ")", "{", "if", "!", "authorizer", ".", "AuthController", "(", ")", "{", "// Firewaller must run as a controller.", "return", "nil", ",", "common", ".", "ErrPerm", "\n", "}", "\n", "// Set up the various authorization checkers.", "accessModel", ":=", "common", ".", "AuthFuncForTagKind", "(", "names", ".", "ModelTagKind", ")", "\n", "accessUnit", ":=", "common", ".", "AuthFuncForTagKind", "(", "names", ".", "UnitTagKind", ")", "\n", "accessApplication", ":=", "common", ".", "AuthFuncForTagKind", "(", "names", ".", "ApplicationTagKind", ")", "\n", "accessMachine", ":=", "common", ".", "AuthFuncForTagKind", "(", "names", ".", "MachineTagKind", ")", "\n", "accessRelation", ":=", "common", ".", "AuthFuncForTagKind", "(", "names", ".", "RelationTagKind", ")", "\n", "accessUnitApplicationOrMachineOrRelation", ":=", "common", ".", "AuthAny", "(", "accessUnit", ",", "accessApplication", ",", "accessMachine", ",", "accessRelation", ")", "\n\n", "// Life() is supported for units, applications or machines.", "lifeGetter", ":=", "common", ".", "NewLifeGetter", "(", "st", ",", "accessUnitApplicationOrMachineOrRelation", ",", ")", "\n", "// ModelConfig() and WatchForModelConfigChanges() are allowed", "// with unrestricted access.", "modelWatcher", ":=", "common", ".", "NewModelWatcher", "(", "st", ",", "resources", ",", "authorizer", ",", ")", "\n", "// Watch() is supported for applications only.", "entityWatcher", ":=", "common", ".", "NewAgentEntityWatcher", "(", "st", ",", "resources", ",", "accessApplication", ",", ")", "\n", "// WatchUnits() is supported for machines.", "unitsWatcher", ":=", "common", ".", "NewUnitsWatcher", "(", "st", ",", "resources", ",", "accessMachine", ",", ")", "\n", "// WatchModelMachines() is allowed with unrestricted access.", "machinesWatcher", ":=", "common", ".", "NewModelMachinesWatcher", "(", "st", ",", "resources", ",", "authorizer", ",", ")", "\n", "// InstanceId() is supported for machines.", "instanceIdGetter", ":=", "common", ".", "NewInstanceIdGetter", "(", "st", ",", "accessMachine", ",", ")", "\n\n", "return", "&", "FirewallerAPIV3", "{", "LifeGetter", ":", "lifeGetter", ",", "ModelWatcher", ":", "modelWatcher", ",", "AgentEntityWatcher", ":", "entityWatcher", ",", "UnitsWatcher", ":", "unitsWatcher", ",", "ModelMachinesWatcher", ":", "machinesWatcher", ",", "InstanceIdGetter", ":", "instanceIdGetter", ",", "CloudSpecAPI", ":", "cloudSpecAPI", ",", "st", ":", "st", ",", "resources", ":", "resources", ",", "authorizer", ":", "authorizer", ",", "accessUnit", ":", "accessUnit", ",", "accessApplication", ":", "accessApplication", ",", "accessMachine", ":", "accessMachine", ",", "accessModel", ":", "accessModel", ",", "}", ",", "nil", "\n", "}" ]
// NewFirewallerAPI creates a new server-side FirewallerAPIV3 facade.
[ "NewFirewallerAPI", "creates", "a", "new", "server", "-", "side", "FirewallerAPIV3", "facade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/firewaller/firewaller.go#L96-L165
4,149
juju/juju
apiserver/facades/controller/firewaller/firewaller.go
WatchOpenedPorts
func (f *FirewallerAPIV3) WatchOpenedPorts(args params.Entities) (params.StringsWatchResults, error) { result := params.StringsWatchResults{ Results: make([]params.StringsWatchResult, len(args.Entities)), } if len(args.Entities) == 0 { return result, nil } canWatch, err := f.accessModel() if err != nil { return params.StringsWatchResults{}, errors.Trace(err) } for i, entity := range args.Entities { tag, err := names.ParseTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } if !canWatch(tag) { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } watcherId, initial, err := f.watchOneModelOpenedPorts(tag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } result.Results[i].StringsWatcherId = watcherId result.Results[i].Changes = initial } return result, nil }
go
func (f *FirewallerAPIV3) WatchOpenedPorts(args params.Entities) (params.StringsWatchResults, error) { result := params.StringsWatchResults{ Results: make([]params.StringsWatchResult, len(args.Entities)), } if len(args.Entities) == 0 { return result, nil } canWatch, err := f.accessModel() if err != nil { return params.StringsWatchResults{}, errors.Trace(err) } for i, entity := range args.Entities { tag, err := names.ParseTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } if !canWatch(tag) { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } watcherId, initial, err := f.watchOneModelOpenedPorts(tag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } result.Results[i].StringsWatcherId = watcherId result.Results[i].Changes = initial } return result, nil }
[ "func", "(", "f", "*", "FirewallerAPIV3", ")", "WatchOpenedPorts", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "StringsWatchResults", ",", "error", ")", "{", "result", ":=", "params", ".", "StringsWatchResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "StringsWatchResult", ",", "len", "(", "args", ".", "Entities", ")", ")", ",", "}", "\n", "if", "len", "(", "args", ".", "Entities", ")", "==", "0", "{", "return", "result", ",", "nil", "\n", "}", "\n", "canWatch", ",", "err", ":=", "f", ".", "accessModel", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "StringsWatchResults", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "for", "i", ",", "entity", ":=", "range", "args", ".", "Entities", "{", "tag", ",", "err", ":=", "names", ".", "ParseTag", "(", "entity", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "common", ".", "ErrPerm", ")", "\n", "continue", "\n", "}", "\n", "if", "!", "canWatch", "(", "tag", ")", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "common", ".", "ErrPerm", ")", "\n", "continue", "\n", "}", "\n", "watcherId", ",", "initial", ",", "err", ":=", "f", ".", "watchOneModelOpenedPorts", "(", "tag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "result", ".", "Results", "[", "i", "]", ".", "StringsWatcherId", "=", "watcherId", "\n", "result", ".", "Results", "[", "i", "]", ".", "Changes", "=", "initial", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// WatchOpenedPorts returns a new StringsWatcher for each given // model tag.
[ "WatchOpenedPorts", "returns", "a", "new", "StringsWatcher", "for", "each", "given", "model", "tag", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/firewaller/firewaller.go#L169-L199
4,150
juju/juju
apiserver/facades/controller/firewaller/firewaller.go
GetMachinePorts
func (f *FirewallerAPIV3) GetMachinePorts(args params.MachinePortsParams) (params.MachinePortsResults, error) { result := params.MachinePortsResults{ Results: make([]params.MachinePortsResult, len(args.Params)), } canAccess, err := f.accessMachine() if err != nil { return params.MachinePortsResults{}, err } for i, param := range args.Params { machineTag, err := names.ParseMachineTag(param.MachineTag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } var subnetTag names.SubnetTag if param.SubnetTag != "" { subnetTag, err = names.ParseSubnetTag(param.SubnetTag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } } machine, err := f.getMachine(canAccess, machineTag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } ports, err := machine.OpenedPorts(subnetTag.Id()) if err != nil { result.Results[i].Error = common.ServerError(err) continue } if ports != nil { portRangeMap := ports.AllPortRanges() var portRanges []network.PortRange for portRange := range portRangeMap { portRanges = append(portRanges, portRange) } network.SortPortRanges(portRanges) for _, portRange := range portRanges { unitTag := names.NewUnitTag(portRangeMap[portRange]).String() result.Results[i].Ports = append(result.Results[i].Ports, params.MachinePortRange{ UnitTag: unitTag, PortRange: params.FromNetworkPortRange(portRange), }) } } } return result, nil }
go
func (f *FirewallerAPIV3) GetMachinePorts(args params.MachinePortsParams) (params.MachinePortsResults, error) { result := params.MachinePortsResults{ Results: make([]params.MachinePortsResult, len(args.Params)), } canAccess, err := f.accessMachine() if err != nil { return params.MachinePortsResults{}, err } for i, param := range args.Params { machineTag, err := names.ParseMachineTag(param.MachineTag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } var subnetTag names.SubnetTag if param.SubnetTag != "" { subnetTag, err = names.ParseSubnetTag(param.SubnetTag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } } machine, err := f.getMachine(canAccess, machineTag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } ports, err := machine.OpenedPorts(subnetTag.Id()) if err != nil { result.Results[i].Error = common.ServerError(err) continue } if ports != nil { portRangeMap := ports.AllPortRanges() var portRanges []network.PortRange for portRange := range portRangeMap { portRanges = append(portRanges, portRange) } network.SortPortRanges(portRanges) for _, portRange := range portRanges { unitTag := names.NewUnitTag(portRangeMap[portRange]).String() result.Results[i].Ports = append(result.Results[i].Ports, params.MachinePortRange{ UnitTag: unitTag, PortRange: params.FromNetworkPortRange(portRange), }) } } } return result, nil }
[ "func", "(", "f", "*", "FirewallerAPIV3", ")", "GetMachinePorts", "(", "args", "params", ".", "MachinePortsParams", ")", "(", "params", ".", "MachinePortsResults", ",", "error", ")", "{", "result", ":=", "params", ".", "MachinePortsResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "MachinePortsResult", ",", "len", "(", "args", ".", "Params", ")", ")", ",", "}", "\n", "canAccess", ",", "err", ":=", "f", ".", "accessMachine", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "MachinePortsResults", "{", "}", ",", "err", "\n", "}", "\n", "for", "i", ",", "param", ":=", "range", "args", ".", "Params", "{", "machineTag", ",", "err", ":=", "names", ".", "ParseMachineTag", "(", "param", ".", "MachineTag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "var", "subnetTag", "names", ".", "SubnetTag", "\n", "if", "param", ".", "SubnetTag", "!=", "\"", "\"", "{", "subnetTag", ",", "err", "=", "names", ".", "ParseSubnetTag", "(", "param", ".", "SubnetTag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "}", "\n", "machine", ",", "err", ":=", "f", ".", "getMachine", "(", "canAccess", ",", "machineTag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "ports", ",", "err", ":=", "machine", ".", "OpenedPorts", "(", "subnetTag", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "ports", "!=", "nil", "{", "portRangeMap", ":=", "ports", ".", "AllPortRanges", "(", ")", "\n", "var", "portRanges", "[", "]", "network", ".", "PortRange", "\n", "for", "portRange", ":=", "range", "portRangeMap", "{", "portRanges", "=", "append", "(", "portRanges", ",", "portRange", ")", "\n", "}", "\n", "network", ".", "SortPortRanges", "(", "portRanges", ")", "\n\n", "for", "_", ",", "portRange", ":=", "range", "portRanges", "{", "unitTag", ":=", "names", ".", "NewUnitTag", "(", "portRangeMap", "[", "portRange", "]", ")", ".", "String", "(", ")", "\n", "result", ".", "Results", "[", "i", "]", ".", "Ports", "=", "append", "(", "result", ".", "Results", "[", "i", "]", ".", "Ports", ",", "params", ".", "MachinePortRange", "{", "UnitTag", ":", "unitTag", ",", "PortRange", ":", "params", ".", "FromNetworkPortRange", "(", "portRange", ")", ",", "}", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// GetMachinePorts returns the port ranges opened on a machine for the specified // subnet as a map mapping port ranges to the tags of the units that opened // them.
[ "GetMachinePorts", "returns", "the", "port", "ranges", "opened", "on", "a", "machine", "for", "the", "specified", "subnet", "as", "a", "map", "mapping", "port", "ranges", "to", "the", "tags", "of", "the", "units", "that", "opened", "them", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/firewaller/firewaller.go#L215-L266
4,151
juju/juju
apiserver/facades/controller/firewaller/firewaller.go
GetExposed
func (f *FirewallerAPIV3) GetExposed(args params.Entities) (params.BoolResults, error) { result := params.BoolResults{ Results: make([]params.BoolResult, len(args.Entities)), } canAccess, err := f.accessApplication() if err != nil { return params.BoolResults{}, err } for i, entity := range args.Entities { tag, err := names.ParseApplicationTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } application, err := f.getApplication(canAccess, tag) if err == nil { result.Results[i].Result = application.IsExposed() } result.Results[i].Error = common.ServerError(err) } return result, nil }
go
func (f *FirewallerAPIV3) GetExposed(args params.Entities) (params.BoolResults, error) { result := params.BoolResults{ Results: make([]params.BoolResult, len(args.Entities)), } canAccess, err := f.accessApplication() if err != nil { return params.BoolResults{}, err } for i, entity := range args.Entities { tag, err := names.ParseApplicationTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } application, err := f.getApplication(canAccess, tag) if err == nil { result.Results[i].Result = application.IsExposed() } result.Results[i].Error = common.ServerError(err) } return result, nil }
[ "func", "(", "f", "*", "FirewallerAPIV3", ")", "GetExposed", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "BoolResults", ",", "error", ")", "{", "result", ":=", "params", ".", "BoolResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "BoolResult", ",", "len", "(", "args", ".", "Entities", ")", ")", ",", "}", "\n", "canAccess", ",", "err", ":=", "f", ".", "accessApplication", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "BoolResults", "{", "}", ",", "err", "\n", "}", "\n", "for", "i", ",", "entity", ":=", "range", "args", ".", "Entities", "{", "tag", ",", "err", ":=", "names", ".", "ParseApplicationTag", "(", "entity", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "common", ".", "ErrPerm", ")", "\n", "continue", "\n", "}", "\n", "application", ",", "err", ":=", "f", ".", "getApplication", "(", "canAccess", ",", "tag", ")", "\n", "if", "err", "==", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Result", "=", "application", ".", "IsExposed", "(", ")", "\n", "}", "\n", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// GetExposed returns the exposed flag value for each given application.
[ "GetExposed", "returns", "the", "exposed", "flag", "value", "for", "each", "given", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/firewaller/firewaller.go#L316-L337
4,152
juju/juju
apiserver/facades/controller/firewaller/firewaller.go
WatchIngressAddressesForRelations
func (f *FirewallerAPIV4) WatchIngressAddressesForRelations(relations params.Entities) (params.StringsWatchResults, error) { results := params.StringsWatchResults{ make([]params.StringsWatchResult, len(relations.Entities)), } one := func(tag string) (id string, changes []string, _ error) { logger.Debugf("Watching ingress addresses for %+v from model %v", tag, f.st.ModelUUID()) relationTag, err := names.ParseRelationTag(tag) if err != nil { return "", nil, errors.Trace(err) } rel, err := f.st.KeyRelation(relationTag.Id()) if err != nil { return "", nil, errors.Trace(err) } w := rel.WatchRelationIngressNetworks() changes, ok := <-w.Changes() if !ok { return "", nil, common.ServerError(watcher.EnsureErr(w)) } return f.resources.Register(w), changes, nil } for i, e := range relations.Entities { watcherId, changes, err := one(e.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } results.Results[i].StringsWatcherId = watcherId results.Results[i].Changes = changes } return results, nil }
go
func (f *FirewallerAPIV4) WatchIngressAddressesForRelations(relations params.Entities) (params.StringsWatchResults, error) { results := params.StringsWatchResults{ make([]params.StringsWatchResult, len(relations.Entities)), } one := func(tag string) (id string, changes []string, _ error) { logger.Debugf("Watching ingress addresses for %+v from model %v", tag, f.st.ModelUUID()) relationTag, err := names.ParseRelationTag(tag) if err != nil { return "", nil, errors.Trace(err) } rel, err := f.st.KeyRelation(relationTag.Id()) if err != nil { return "", nil, errors.Trace(err) } w := rel.WatchRelationIngressNetworks() changes, ok := <-w.Changes() if !ok { return "", nil, common.ServerError(watcher.EnsureErr(w)) } return f.resources.Register(w), changes, nil } for i, e := range relations.Entities { watcherId, changes, err := one(e.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } results.Results[i].StringsWatcherId = watcherId results.Results[i].Changes = changes } return results, nil }
[ "func", "(", "f", "*", "FirewallerAPIV4", ")", "WatchIngressAddressesForRelations", "(", "relations", "params", ".", "Entities", ")", "(", "params", ".", "StringsWatchResults", ",", "error", ")", "{", "results", ":=", "params", ".", "StringsWatchResults", "{", "make", "(", "[", "]", "params", ".", "StringsWatchResult", ",", "len", "(", "relations", ".", "Entities", ")", ")", ",", "}", "\n\n", "one", ":=", "func", "(", "tag", "string", ")", "(", "id", "string", ",", "changes", "[", "]", "string", ",", "_", "error", ")", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "tag", ",", "f", ".", "st", ".", "ModelUUID", "(", ")", ")", "\n\n", "relationTag", ",", "err", ":=", "names", ".", "ParseRelationTag", "(", "tag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "rel", ",", "err", ":=", "f", ".", "st", ".", "KeyRelation", "(", "relationTag", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "w", ":=", "rel", ".", "WatchRelationIngressNetworks", "(", ")", "\n", "changes", ",", "ok", ":=", "<-", "w", ".", "Changes", "(", ")", "\n", "if", "!", "ok", "{", "return", "\"", "\"", ",", "nil", ",", "common", ".", "ServerError", "(", "watcher", ".", "EnsureErr", "(", "w", ")", ")", "\n", "}", "\n", "return", "f", ".", "resources", ".", "Register", "(", "w", ")", ",", "changes", ",", "nil", "\n", "}", "\n\n", "for", "i", ",", "e", ":=", "range", "relations", ".", "Entities", "{", "watcherId", ",", "changes", ",", "err", ":=", "one", "(", "e", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "results", ".", "Results", "[", "i", "]", ".", "StringsWatcherId", "=", "watcherId", "\n", "results", ".", "Results", "[", "i", "]", ".", "Changes", "=", "changes", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// WatchIngressAddressesForRelations creates a watcher that returns the ingress networks // that have been recorded against the specified relations.
[ "WatchIngressAddressesForRelations", "creates", "a", "watcher", "that", "returns", "the", "ingress", "networks", "that", "have", "been", "recorded", "against", "the", "specified", "relations", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/firewaller/firewaller.go#L414-L448
4,153
juju/juju
apiserver/facades/controller/firewaller/firewaller.go
MacaroonForRelations
func (f *FirewallerAPIV4) MacaroonForRelations(args params.Entities) (params.MacaroonResults, error) { var result params.MacaroonResults result.Results = make([]params.MacaroonResult, len(args.Entities)) for i, entity := range args.Entities { relationTag, err := names.ParseRelationTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } mac, err := f.st.GetMacaroon(relationTag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } result.Results[i].Result = mac } return result, nil }
go
func (f *FirewallerAPIV4) MacaroonForRelations(args params.Entities) (params.MacaroonResults, error) { var result params.MacaroonResults result.Results = make([]params.MacaroonResult, len(args.Entities)) for i, entity := range args.Entities { relationTag, err := names.ParseRelationTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } mac, err := f.st.GetMacaroon(relationTag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } result.Results[i].Result = mac } return result, nil }
[ "func", "(", "f", "*", "FirewallerAPIV4", ")", "MacaroonForRelations", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "MacaroonResults", ",", "error", ")", "{", "var", "result", "params", ".", "MacaroonResults", "\n", "result", ".", "Results", "=", "make", "(", "[", "]", "params", ".", "MacaroonResult", ",", "len", "(", "args", ".", "Entities", ")", ")", "\n", "for", "i", ",", "entity", ":=", "range", "args", ".", "Entities", "{", "relationTag", ",", "err", ":=", "names", ".", "ParseRelationTag", "(", "entity", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "mac", ",", "err", ":=", "f", ".", "st", ".", "GetMacaroon", "(", "relationTag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "result", ".", "Results", "[", "i", "]", ".", "Result", "=", "mac", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// MacaroonForRelations returns the macaroon for the specified relations.
[ "MacaroonForRelations", "returns", "the", "macaroon", "for", "the", "specified", "relations", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/firewaller/firewaller.go#L451-L468
4,154
juju/juju
apiserver/facades/controller/firewaller/firewaller.go
SetRelationsStatus
func (f *FirewallerAPIV4) SetRelationsStatus(args params.SetStatus) (params.ErrorResults, error) { var result params.ErrorResults result.Results = make([]params.ErrorResult, len(args.Entities)) for i, entity := range args.Entities { relationTag, err := names.ParseRelationTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } rel, err := f.st.KeyRelation(relationTag.Id()) if err != nil { result.Results[i].Error = common.ServerError(err) continue } err = rel.SetStatus(status.StatusInfo{ Status: status.Status(entity.Status), Message: entity.Info, }) result.Results[i].Error = common.ServerError(err) } return result, nil }
go
func (f *FirewallerAPIV4) SetRelationsStatus(args params.SetStatus) (params.ErrorResults, error) { var result params.ErrorResults result.Results = make([]params.ErrorResult, len(args.Entities)) for i, entity := range args.Entities { relationTag, err := names.ParseRelationTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } rel, err := f.st.KeyRelation(relationTag.Id()) if err != nil { result.Results[i].Error = common.ServerError(err) continue } err = rel.SetStatus(status.StatusInfo{ Status: status.Status(entity.Status), Message: entity.Info, }) result.Results[i].Error = common.ServerError(err) } return result, nil }
[ "func", "(", "f", "*", "FirewallerAPIV4", ")", "SetRelationsStatus", "(", "args", "params", ".", "SetStatus", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "var", "result", "params", ".", "ErrorResults", "\n", "result", ".", "Results", "=", "make", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "args", ".", "Entities", ")", ")", "\n", "for", "i", ",", "entity", ":=", "range", "args", ".", "Entities", "{", "relationTag", ",", "err", ":=", "names", ".", "ParseRelationTag", "(", "entity", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "rel", ",", "err", ":=", "f", ".", "st", ".", "KeyRelation", "(", "relationTag", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "err", "=", "rel", ".", "SetStatus", "(", "status", ".", "StatusInfo", "{", "Status", ":", "status", ".", "Status", "(", "entity", ".", "Status", ")", ",", "Message", ":", "entity", ".", "Info", ",", "}", ")", "\n", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// SetRelationsStatus sets the status for the specified relations.
[ "SetRelationsStatus", "sets", "the", "status", "for", "the", "specified", "relations", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/firewaller/firewaller.go#L471-L492
4,155
juju/juju
apiserver/facades/controller/firewaller/firewaller.go
FirewallRules
func (f *FirewallerAPIV4) FirewallRules(args params.KnownServiceArgs) (params.ListFirewallRulesResults, error) { var result params.ListFirewallRulesResults for _, knownService := range args.KnownServices { rule, err := f.st.FirewallRule(state.WellKnownServiceType(knownService)) if err != nil && !errors.IsNotFound(err) { return result, common.ServerError(err) } if err != nil { continue } result.Rules = append(result.Rules, params.FirewallRule{ KnownService: knownService, WhitelistCIDRS: rule.WhitelistCIDRs, }) } return result, nil }
go
func (f *FirewallerAPIV4) FirewallRules(args params.KnownServiceArgs) (params.ListFirewallRulesResults, error) { var result params.ListFirewallRulesResults for _, knownService := range args.KnownServices { rule, err := f.st.FirewallRule(state.WellKnownServiceType(knownService)) if err != nil && !errors.IsNotFound(err) { return result, common.ServerError(err) } if err != nil { continue } result.Rules = append(result.Rules, params.FirewallRule{ KnownService: knownService, WhitelistCIDRS: rule.WhitelistCIDRs, }) } return result, nil }
[ "func", "(", "f", "*", "FirewallerAPIV4", ")", "FirewallRules", "(", "args", "params", ".", "KnownServiceArgs", ")", "(", "params", ".", "ListFirewallRulesResults", ",", "error", ")", "{", "var", "result", "params", ".", "ListFirewallRulesResults", "\n", "for", "_", ",", "knownService", ":=", "range", "args", ".", "KnownServices", "{", "rule", ",", "err", ":=", "f", ".", "st", ".", "FirewallRule", "(", "state", ".", "WellKnownServiceType", "(", "knownService", ")", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "result", ",", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "result", ".", "Rules", "=", "append", "(", "result", ".", "Rules", ",", "params", ".", "FirewallRule", "{", "KnownService", ":", "knownService", ",", "WhitelistCIDRS", ":", "rule", ".", "WhitelistCIDRs", ",", "}", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// FirewallRules returns the firewall rules for the specified well known service types.
[ "FirewallRules", "returns", "the", "firewall", "rules", "for", "the", "specified", "well", "known", "service", "types", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/firewaller/firewaller.go#L495-L511
4,156
juju/juju
state/backups/db.go
NewDBInfo
func NewDBInfo(mgoInfo *mongo.MongoInfo, session DBSession, version mongo.Version) (*DBInfo, error) { targets, err := getBackupTargetDatabases(session) if err != nil { return nil, errors.Trace(err) } info := DBInfo{ Address: mgoInfo.Addrs[0], Password: mgoInfo.Password, Targets: targets, MongoVersion: version, } // TODO(dfc) Backup should take a Tag. if mgoInfo.Tag != nil { info.Username = mgoInfo.Tag.String() } return &info, nil }
go
func NewDBInfo(mgoInfo *mongo.MongoInfo, session DBSession, version mongo.Version) (*DBInfo, error) { targets, err := getBackupTargetDatabases(session) if err != nil { return nil, errors.Trace(err) } info := DBInfo{ Address: mgoInfo.Addrs[0], Password: mgoInfo.Password, Targets: targets, MongoVersion: version, } // TODO(dfc) Backup should take a Tag. if mgoInfo.Tag != nil { info.Username = mgoInfo.Tag.String() } return &info, nil }
[ "func", "NewDBInfo", "(", "mgoInfo", "*", "mongo", ".", "MongoInfo", ",", "session", "DBSession", ",", "version", "mongo", ".", "Version", ")", "(", "*", "DBInfo", ",", "error", ")", "{", "targets", ",", "err", ":=", "getBackupTargetDatabases", "(", "session", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "info", ":=", "DBInfo", "{", "Address", ":", "mgoInfo", ".", "Addrs", "[", "0", "]", ",", "Password", ":", "mgoInfo", ".", "Password", ",", "Targets", ":", "targets", ",", "MongoVersion", ":", "version", ",", "}", "\n\n", "// TODO(dfc) Backup should take a Tag.", "if", "mgoInfo", ".", "Tag", "!=", "nil", "{", "info", ".", "Username", "=", "mgoInfo", ".", "Tag", ".", "String", "(", ")", "\n", "}", "\n\n", "return", "&", "info", ",", "nil", "\n", "}" ]
// NewDBInfo returns the information needed by backups to dump // the database.
[ "NewDBInfo", "returns", "the", "information", "needed", "by", "backups", "to", "dump", "the", "database", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/db.go#L65-L84
4,157
juju/juju
state/backups/db.go
NewDBDumper
func NewDBDumper(info *DBInfo) (DBDumper, error) { mongodumpPath, err := getMongodumpPath() if err != nil { return nil, errors.Annotate(err, "mongodump not available") } dumper := mongoDumper{ DBInfo: info, binPath: mongodumpPath, } return &dumper, nil }
go
func NewDBDumper(info *DBInfo) (DBDumper, error) { mongodumpPath, err := getMongodumpPath() if err != nil { return nil, errors.Annotate(err, "mongodump not available") } dumper := mongoDumper{ DBInfo: info, binPath: mongodumpPath, } return &dumper, nil }
[ "func", "NewDBDumper", "(", "info", "*", "DBInfo", ")", "(", "DBDumper", ",", "error", ")", "{", "mongodumpPath", ",", "err", ":=", "getMongodumpPath", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "dumper", ":=", "mongoDumper", "{", "DBInfo", ":", "info", ",", "binPath", ":", "mongodumpPath", ",", "}", "\n", "return", "&", "dumper", ",", "nil", "\n", "}" ]
// NewDBDumper returns a new value with a Dump method for dumping the // juju state database.
[ "NewDBDumper", "returns", "a", "new", "value", "with", "a", "Dump", "method", "for", "dumping", "the", "juju", "state", "database", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/db.go#L144-L155
4,158
juju/juju
state/backups/db.go
Dump
func (md *mongoDumper) Dump(baseDumpDir string) error { if err := md.dump(baseDumpDir); err != nil { return errors.Trace(err) } found, err := listDatabases(baseDumpDir) if err != nil { return errors.Trace(err) } // Strip the ignored database from the dump dir. ignored := found.Difference(md.Targets) // Admin must be removed only if the mongo version is 3.x or // above, since 2.x will not restore properly without admin. if md.DBInfo.MongoVersion.NewerThan(mongo.Mongo26) == -1 { ignored.Remove("admin") } err = stripIgnored(ignored, baseDumpDir) return errors.Trace(err) }
go
func (md *mongoDumper) Dump(baseDumpDir string) error { if err := md.dump(baseDumpDir); err != nil { return errors.Trace(err) } found, err := listDatabases(baseDumpDir) if err != nil { return errors.Trace(err) } // Strip the ignored database from the dump dir. ignored := found.Difference(md.Targets) // Admin must be removed only if the mongo version is 3.x or // above, since 2.x will not restore properly without admin. if md.DBInfo.MongoVersion.NewerThan(mongo.Mongo26) == -1 { ignored.Remove("admin") } err = stripIgnored(ignored, baseDumpDir) return errors.Trace(err) }
[ "func", "(", "md", "*", "mongoDumper", ")", "Dump", "(", "baseDumpDir", "string", ")", "error", "{", "if", "err", ":=", "md", ".", "dump", "(", "baseDumpDir", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "found", ",", "err", ":=", "listDatabases", "(", "baseDumpDir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// Strip the ignored database from the dump dir.", "ignored", ":=", "found", ".", "Difference", "(", "md", ".", "Targets", ")", "\n", "// Admin must be removed only if the mongo version is 3.x or", "// above, since 2.x will not restore properly without admin.", "if", "md", ".", "DBInfo", ".", "MongoVersion", ".", "NewerThan", "(", "mongo", ".", "Mongo26", ")", "==", "-", "1", "{", "ignored", ".", "Remove", "(", "\"", "\"", ")", "\n", "}", "\n", "err", "=", "stripIgnored", "(", "ignored", ",", "baseDumpDir", ")", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// Dump dumps the juju state-related databases. To do this we dump all // databases and then remove any ignored databases from the dump results.
[ "Dump", "dumps", "the", "juju", "state", "-", "related", "databases", ".", "To", "do", "this", "we", "dump", "all", "databases", "and", "then", "remove", "any", "ignored", "databases", "from", "the", "dump", "results", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/db.go#L181-L200
4,159
juju/juju
state/backups/db.go
listDatabases
func listDatabases(dumpDir string) (set.Strings, error) { list, err := ioutil.ReadDir(dumpDir) if err != nil { return set.Strings{}, errors.Trace(err) } databases := make(set.Strings) for _, info := range list { if !info.IsDir() { // Notably, oplog.bson is thus excluded here. continue } databases.Add(info.Name()) } return databases, nil }
go
func listDatabases(dumpDir string) (set.Strings, error) { list, err := ioutil.ReadDir(dumpDir) if err != nil { return set.Strings{}, errors.Trace(err) } databases := make(set.Strings) for _, info := range list { if !info.IsDir() { // Notably, oplog.bson is thus excluded here. continue } databases.Add(info.Name()) } return databases, nil }
[ "func", "listDatabases", "(", "dumpDir", "string", ")", "(", "set", ".", "Strings", ",", "error", ")", "{", "list", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "dumpDir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "set", ".", "Strings", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "databases", ":=", "make", "(", "set", ".", "Strings", ")", "\n", "for", "_", ",", "info", ":=", "range", "list", "{", "if", "!", "info", ".", "IsDir", "(", ")", "{", "// Notably, oplog.bson is thus excluded here.", "continue", "\n", "}", "\n", "databases", ".", "Add", "(", "info", ".", "Name", "(", ")", ")", "\n", "}", "\n", "return", "databases", ",", "nil", "\n", "}" ]
// listDatabases returns the name of each sub-directory of the dump // directory. Each corresponds to a database dump generated by // mongodump. Note that, while mongodump is unlikely to change behavior // in this regard, this is not a documented guaranteed behavior.
[ "listDatabases", "returns", "the", "name", "of", "each", "sub", "-", "directory", "of", "the", "dump", "directory", ".", "Each", "corresponds", "to", "a", "database", "dump", "generated", "by", "mongodump", ".", "Note", "that", "while", "mongodump", "is", "unlikely", "to", "change", "behavior", "in", "this", "regard", "this", "is", "not", "a", "documented", "guaranteed", "behavior", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/db.go#L231-L246
4,160
juju/juju
state/backups/db.go
NewDBRestorer
func NewDBRestorer(args RestorerArgs) (DBRestorer, error) { mongorestorePath, err := getMongorestorePath() if err != nil { return nil, errors.Annotate(err, "mongorestore not available") } installedMongo := mongoInstalledVersion() logger.Debugf("args: is %#v", args) logger.Infof("installed mongo is %s", installedMongo) // NewerThan will check Major and Minor so migration between micro versions // will work, before changing this beware, Mongo has been known to break // compatibility between minors. if args.Version.NewerThan(installedMongo) != 0 { return nil, errors.NotSupportedf("restore mongo version %s into version %s", args.Version.String(), installedMongo.String()) } var restorer DBRestorer mgoRestorer := mongoRestorer{ DialInfo: args.DialInfo, binPath: mongorestorePath, tagUser: args.TagUser, tagUserPassword: args.TagUserPassword, runCommandFn: args.RunCommandFn, } switch args.Version.Major { case 2: restorer = &mongoRestorer24{ mongoRestorer: mgoRestorer, startMongo: args.StartMongo, stopMongo: args.StopMongo, } case 3: restorer = &mongoRestorer32{ mongoRestorer: mgoRestorer, getDB: args.GetDB, newMongoSession: args.NewMongoSession, } default: return nil, errors.Errorf("cannot restore from mongo version %q", args.Version.String()) } return restorer, nil }
go
func NewDBRestorer(args RestorerArgs) (DBRestorer, error) { mongorestorePath, err := getMongorestorePath() if err != nil { return nil, errors.Annotate(err, "mongorestore not available") } installedMongo := mongoInstalledVersion() logger.Debugf("args: is %#v", args) logger.Infof("installed mongo is %s", installedMongo) // NewerThan will check Major and Minor so migration between micro versions // will work, before changing this beware, Mongo has been known to break // compatibility between minors. if args.Version.NewerThan(installedMongo) != 0 { return nil, errors.NotSupportedf("restore mongo version %s into version %s", args.Version.String(), installedMongo.String()) } var restorer DBRestorer mgoRestorer := mongoRestorer{ DialInfo: args.DialInfo, binPath: mongorestorePath, tagUser: args.TagUser, tagUserPassword: args.TagUserPassword, runCommandFn: args.RunCommandFn, } switch args.Version.Major { case 2: restorer = &mongoRestorer24{ mongoRestorer: mgoRestorer, startMongo: args.StartMongo, stopMongo: args.StopMongo, } case 3: restorer = &mongoRestorer32{ mongoRestorer: mgoRestorer, getDB: args.GetDB, newMongoSession: args.NewMongoSession, } default: return nil, errors.Errorf("cannot restore from mongo version %q", args.Version.String()) } return restorer, nil }
[ "func", "NewDBRestorer", "(", "args", "RestorerArgs", ")", "(", "DBRestorer", ",", "error", ")", "{", "mongorestorePath", ",", "err", ":=", "getMongorestorePath", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "installedMongo", ":=", "mongoInstalledVersion", "(", ")", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "args", ")", "\n", "logger", ".", "Infof", "(", "\"", "\"", ",", "installedMongo", ")", "\n", "// NewerThan will check Major and Minor so migration between micro versions", "// will work, before changing this beware, Mongo has been known to break", "// compatibility between minors.", "if", "args", ".", "Version", ".", "NewerThan", "(", "installedMongo", ")", "!=", "0", "{", "return", "nil", ",", "errors", ".", "NotSupportedf", "(", "\"", "\"", ",", "args", ".", "Version", ".", "String", "(", ")", ",", "installedMongo", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "var", "restorer", "DBRestorer", "\n", "mgoRestorer", ":=", "mongoRestorer", "{", "DialInfo", ":", "args", ".", "DialInfo", ",", "binPath", ":", "mongorestorePath", ",", "tagUser", ":", "args", ".", "TagUser", ",", "tagUserPassword", ":", "args", ".", "TagUserPassword", ",", "runCommandFn", ":", "args", ".", "RunCommandFn", ",", "}", "\n", "switch", "args", ".", "Version", ".", "Major", "{", "case", "2", ":", "restorer", "=", "&", "mongoRestorer24", "{", "mongoRestorer", ":", "mgoRestorer", ",", "startMongo", ":", "args", ".", "StartMongo", ",", "stopMongo", ":", "args", ".", "StopMongo", ",", "}", "\n", "case", "3", ":", "restorer", "=", "&", "mongoRestorer32", "{", "mongoRestorer", ":", "mgoRestorer", ",", "getDB", ":", "args", ".", "GetDB", ",", "newMongoSession", ":", "args", ".", "NewMongoSession", ",", "}", "\n", "default", ":", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "args", ".", "Version", ".", "String", "(", ")", ")", "\n", "}", "\n", "return", "restorer", ",", "nil", "\n", "}" ]
// NewDBRestorer returns a new structure that can perform a restore // on the db pointed in dialInfo.
[ "NewDBRestorer", "returns", "a", "new", "structure", "that", "can", "perform", "a", "restore", "on", "the", "db", "pointed", "in", "dialInfo", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/db.go#L340-L381
4,161
juju/juju
state/backups/db.go
ensureOplogPermissions
func (md *mongoRestorer32) ensureOplogPermissions(dialInfo *mgo.DialInfo) error { s, err := md.newMongoSession(dialInfo) if err != nil { return errors.Trace(err) } defer s.Close() roles := bson.D{ {"createRole", "oploger"}, {"privileges", []bson.D{ { {"resource", bson.M{"anyResource": true}}, {"actions", []string{"anyAction"}}, }, }}, {"roles", []string{}}, } var mgoErr bson.M err = s.Run(roles, &mgoErr) if err != nil && !mgo.IsDup(err) { return errors.Trace(err) } result, ok := mgoErr["ok"] success, isFloat := result.(float64) if (!ok || !isFloat || success != 1) && mgoErr != nil && !mgo.IsDup(err) { return errors.Errorf("could not create special role to replay oplog, result was: %#v", mgoErr) } // This will replace old user with the new credentials admin := md.getDB("admin", s) grant := bson.D{ {"grantRolesToUser", md.DialInfo.Username}, {"roles", []string{"oploger"}}, } err = s.Run(grant, &mgoErr) if err != nil { return errors.Trace(err) } result, ok = mgoErr["ok"] success, isFloat = result.(float64) if (!ok || !isFloat || success != 1) && mgoErr != nil { return errors.Errorf("could not grant special role to %q, result was: %#v", md.DialInfo.Username, mgoErr) } grant = bson.D{ {"grantRolesToUser", "admin"}, {"roles", []string{"oploger"}}, } err = s.Run(grant, &mgoErr) if err != nil { return errors.Trace(err) } result, ok = mgoErr["ok"] success, isFloat = result.(float64) if (!ok || !isFloat || success != 1) && mgoErr != nil { return errors.Errorf("could not grant special role to \"admin\", result was: %#v", mgoErr) } if err := admin.UpsertUser(&mgo.User{ Username: md.DialInfo.Username, Password: md.DialInfo.Password, }); err != nil { return errors.Errorf("cannot set new admin credentials: %v", err) } return nil }
go
func (md *mongoRestorer32) ensureOplogPermissions(dialInfo *mgo.DialInfo) error { s, err := md.newMongoSession(dialInfo) if err != nil { return errors.Trace(err) } defer s.Close() roles := bson.D{ {"createRole", "oploger"}, {"privileges", []bson.D{ { {"resource", bson.M{"anyResource": true}}, {"actions", []string{"anyAction"}}, }, }}, {"roles", []string{}}, } var mgoErr bson.M err = s.Run(roles, &mgoErr) if err != nil && !mgo.IsDup(err) { return errors.Trace(err) } result, ok := mgoErr["ok"] success, isFloat := result.(float64) if (!ok || !isFloat || success != 1) && mgoErr != nil && !mgo.IsDup(err) { return errors.Errorf("could not create special role to replay oplog, result was: %#v", mgoErr) } // This will replace old user with the new credentials admin := md.getDB("admin", s) grant := bson.D{ {"grantRolesToUser", md.DialInfo.Username}, {"roles", []string{"oploger"}}, } err = s.Run(grant, &mgoErr) if err != nil { return errors.Trace(err) } result, ok = mgoErr["ok"] success, isFloat = result.(float64) if (!ok || !isFloat || success != 1) && mgoErr != nil { return errors.Errorf("could not grant special role to %q, result was: %#v", md.DialInfo.Username, mgoErr) } grant = bson.D{ {"grantRolesToUser", "admin"}, {"roles", []string{"oploger"}}, } err = s.Run(grant, &mgoErr) if err != nil { return errors.Trace(err) } result, ok = mgoErr["ok"] success, isFloat = result.(float64) if (!ok || !isFloat || success != 1) && mgoErr != nil { return errors.Errorf("could not grant special role to \"admin\", result was: %#v", mgoErr) } if err := admin.UpsertUser(&mgo.User{ Username: md.DialInfo.Username, Password: md.DialInfo.Password, }); err != nil { return errors.Errorf("cannot set new admin credentials: %v", err) } return nil }
[ "func", "(", "md", "*", "mongoRestorer32", ")", "ensureOplogPermissions", "(", "dialInfo", "*", "mgo", ".", "DialInfo", ")", "error", "{", "s", ",", "err", ":=", "md", ".", "newMongoSession", "(", "dialInfo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "defer", "s", ".", "Close", "(", ")", "\n\n", "roles", ":=", "bson", ".", "D", "{", "{", "\"", "\"", ",", "\"", "\"", "}", ",", "{", "\"", "\"", ",", "[", "]", "bson", ".", "D", "{", "{", "{", "\"", "\"", ",", "bson", ".", "M", "{", "\"", "\"", ":", "true", "}", "}", ",", "{", "\"", "\"", ",", "[", "]", "string", "{", "\"", "\"", "}", "}", ",", "}", ",", "}", "}", ",", "{", "\"", "\"", ",", "[", "]", "string", "{", "}", "}", ",", "}", "\n", "var", "mgoErr", "bson", ".", "M", "\n", "err", "=", "s", ".", "Run", "(", "roles", ",", "&", "mgoErr", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "mgo", ".", "IsDup", "(", "err", ")", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "result", ",", "ok", ":=", "mgoErr", "[", "\"", "\"", "]", "\n", "success", ",", "isFloat", ":=", "result", ".", "(", "float64", ")", "\n", "if", "(", "!", "ok", "||", "!", "isFloat", "||", "success", "!=", "1", ")", "&&", "mgoErr", "!=", "nil", "&&", "!", "mgo", ".", "IsDup", "(", "err", ")", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "mgoErr", ")", "\n", "}", "\n\n", "// This will replace old user with the new credentials", "admin", ":=", "md", ".", "getDB", "(", "\"", "\"", ",", "s", ")", "\n\n", "grant", ":=", "bson", ".", "D", "{", "{", "\"", "\"", ",", "md", ".", "DialInfo", ".", "Username", "}", ",", "{", "\"", "\"", ",", "[", "]", "string", "{", "\"", "\"", "}", "}", ",", "}", "\n\n", "err", "=", "s", ".", "Run", "(", "grant", ",", "&", "mgoErr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "result", ",", "ok", "=", "mgoErr", "[", "\"", "\"", "]", "\n", "success", ",", "isFloat", "=", "result", ".", "(", "float64", ")", "\n", "if", "(", "!", "ok", "||", "!", "isFloat", "||", "success", "!=", "1", ")", "&&", "mgoErr", "!=", "nil", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "md", ".", "DialInfo", ".", "Username", ",", "mgoErr", ")", "\n", "}", "\n\n", "grant", "=", "bson", ".", "D", "{", "{", "\"", "\"", ",", "\"", "\"", "}", ",", "{", "\"", "\"", ",", "[", "]", "string", "{", "\"", "\"", "}", "}", ",", "}", "\n\n", "err", "=", "s", ".", "Run", "(", "grant", ",", "&", "mgoErr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "result", ",", "ok", "=", "mgoErr", "[", "\"", "\"", "]", "\n", "success", ",", "isFloat", "=", "result", ".", "(", "float64", ")", "\n", "if", "(", "!", "ok", "||", "!", "isFloat", "||", "success", "!=", "1", ")", "&&", "mgoErr", "!=", "nil", "{", "return", "errors", ".", "Errorf", "(", "\"", "\\\"", "\\\"", "\"", ",", "mgoErr", ")", "\n", "}", "\n\n", "if", "err", ":=", "admin", ".", "UpsertUser", "(", "&", "mgo", ".", "User", "{", "Username", ":", "md", ".", "DialInfo", ".", "Username", ",", "Password", ":", "md", ".", "DialInfo", ".", "Password", ",", "}", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ensureOplogPermissions adds a special role to the admin user, this role // is required by mongorestore when doing oplogreplay.
[ "ensureOplogPermissions", "adds", "a", "special", "role", "to", "the", "admin", "user", "this", "role", "is", "required", "by", "mongorestore", "when", "doing", "oplogreplay", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/db.go#L420-L489
4,162
juju/juju
worker/uniter/uniter.go
NewUniter
func NewUniter(uniterParams *UniterParams) (*Uniter, error) { startFunc := newUniter(uniterParams) w, err := startFunc() return w.(*Uniter), err }
go
func NewUniter(uniterParams *UniterParams) (*Uniter, error) { startFunc := newUniter(uniterParams) w, err := startFunc() return w.(*Uniter), err }
[ "func", "NewUniter", "(", "uniterParams", "*", "UniterParams", ")", "(", "*", "Uniter", ",", "error", ")", "{", "startFunc", ":=", "newUniter", "(", "uniterParams", ")", "\n", "w", ",", "err", ":=", "startFunc", "(", ")", "\n", "return", "w", ".", "(", "*", "Uniter", ")", ",", "err", "\n", "}" ]
// NewUniter creates a new Uniter which will install, run, and upgrade // a charm on behalf of the unit with the given unitTag, by executing // hooks and operations provoked by changes in st.
[ "NewUniter", "creates", "a", "new", "Uniter", "which", "will", "install", "run", "and", "upgrade", "a", "charm", "on", "behalf", "of", "the", "unit", "with", "the", "given", "unitTag", "by", "executing", "hooks", "and", "operations", "provoked", "by", "changes", "in", "st", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/uniter.go#L148-L152
4,163
juju/juju
worker/uniter/uniter.go
StartUniter
func StartUniter(runner *worker.Runner, params *UniterParams) error { startFunc := newUniter(params) logger.Debugf("starting uniter for %q", params.UnitTag.Id()) err := runner.StartWorker(params.UnitTag.Id(), startFunc) return errors.Annotate(err, "error starting uniter worker") }
go
func StartUniter(runner *worker.Runner, params *UniterParams) error { startFunc := newUniter(params) logger.Debugf("starting uniter for %q", params.UnitTag.Id()) err := runner.StartWorker(params.UnitTag.Id(), startFunc) return errors.Annotate(err, "error starting uniter worker") }
[ "func", "StartUniter", "(", "runner", "*", "worker", ".", "Runner", ",", "params", "*", "UniterParams", ")", "error", "{", "startFunc", ":=", "newUniter", "(", "params", ")", "\n\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "params", ".", "UnitTag", ".", "Id", "(", ")", ")", "\n", "err", ":=", "runner", ".", "StartWorker", "(", "params", ".", "UnitTag", ".", "Id", "(", ")", ",", "startFunc", ")", "\n", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}" ]
// StartUniter creates a new Uniter and starts it using the specified runner.
[ "StartUniter", "creates", "a", "new", "Uniter", "and", "starts", "it", "using", "the", "specified", "runner", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/uniter.go#L155-L161
4,164
juju/juju
worker/uniter/uniter.go
stopUnitError
func (u *Uniter) stopUnitError() error { logger.Debugf("u.modelType: %s", u.modelType) if u.modelType == model.CAAS { return ErrCAASUnitDead } return jworker.ErrTerminateAgent }
go
func (u *Uniter) stopUnitError() error { logger.Debugf("u.modelType: %s", u.modelType) if u.modelType == model.CAAS { return ErrCAASUnitDead } return jworker.ErrTerminateAgent }
[ "func", "(", "u", "*", "Uniter", ")", "stopUnitError", "(", ")", "error", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "u", ".", "modelType", ")", "\n", "if", "u", ".", "modelType", "==", "model", ".", "CAAS", "{", "return", "ErrCAASUnitDead", "\n", "}", "\n", "return", "jworker", ".", "ErrTerminateAgent", "\n", "}" ]
// stopUnitError returns the error to use when exiting from stopping the unit. // For IAAS models, we want to terminate the agent, as each unit is run by // an individual agent for that unit.
[ "stopUnitError", "returns", "the", "error", "to", "use", "when", "exiting", "from", "stopping", "the", "unit", ".", "For", "IAAS", "models", "we", "want", "to", "terminate", "the", "agent", "as", "each", "unit", "is", "run", "by", "an", "individual", "agent", "for", "that", "unit", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/uniter.go#L461-L467
4,165
juju/juju
worker/uniter/uniter.go
acquireExecutionLock
func (u *Uniter) acquireExecutionLock(action string) (func(), error) { // We want to make sure we don't block forever when locking, but take the // Uniter's catacomb into account. spec := machinelock.Spec{ Cancel: u.catacomb.Dying(), Worker: "uniter", Comment: action, } releaser, err := u.hookLock.Acquire(spec) if err != nil { return nil, errors.Trace(err) } return releaser, nil }
go
func (u *Uniter) acquireExecutionLock(action string) (func(), error) { // We want to make sure we don't block forever when locking, but take the // Uniter's catacomb into account. spec := machinelock.Spec{ Cancel: u.catacomb.Dying(), Worker: "uniter", Comment: action, } releaser, err := u.hookLock.Acquire(spec) if err != nil { return nil, errors.Trace(err) } return releaser, nil }
[ "func", "(", "u", "*", "Uniter", ")", "acquireExecutionLock", "(", "action", "string", ")", "(", "func", "(", ")", ",", "error", ")", "{", "// We want to make sure we don't block forever when locking, but take the", "// Uniter's catacomb into account.", "spec", ":=", "machinelock", ".", "Spec", "{", "Cancel", ":", "u", ".", "catacomb", ".", "Dying", "(", ")", ",", "Worker", ":", "\"", "\"", ",", "Comment", ":", "action", ",", "}", "\n", "releaser", ",", "err", ":=", "u", ".", "hookLock", ".", "Acquire", "(", "spec", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "releaser", ",", "nil", "\n", "}" ]
// acquireExecutionLock acquires the machine-level execution lock, and // returns a func that must be called to unlock it. It's used by operation.Executor // when running operations that execute external code.
[ "acquireExecutionLock", "acquires", "the", "machine", "-", "level", "execution", "lock", "and", "returns", "a", "func", "that", "must", "be", "called", "to", "unlock", "it", ".", "It", "s", "used", "by", "operation", ".", "Executor", "when", "running", "operations", "that", "execute", "external", "code", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/uniter.go#L655-L668
4,166
juju/juju
provider/lxd/upgrades.go
ReadLegacyCloudCredentials
func ReadLegacyCloudCredentials(readFile func(string) ([]byte, error)) (cloud.Credential, error) { var ( jujuConfDir = jujupaths.MustSucceed(jujupaths.ConfDir(version.SupportedLTS())) clientCertPath = path.Join(jujuConfDir, "lxd-client.crt") clientKeyPath = path.Join(jujuConfDir, "lxd-client.key") serverCertPath = path.Join(jujuConfDir, "lxd-server.crt") ) readFileString := func(path string) (string, error) { data, err := readFile(path) if err != nil { if os.IsNotExist(err) { err = errors.NotFoundf("%s", path) } return "", errors.Trace(err) } return string(data), nil } clientCert, err := readFileString(clientCertPath) if err != nil { return cloud.Credential{}, errors.Annotate(err, "reading client certificate") } clientKey, err := readFileString(clientKeyPath) if err != nil { return cloud.Credential{}, errors.Annotate(err, "reading client key") } serverCert, err := readFileString(serverCertPath) if err != nil { return cloud.Credential{}, errors.Annotate(err, "reading server certificate") } return cloud.NewCredential(cloud.CertificateAuthType, map[string]string{ credAttrServerCert: serverCert, credAttrClientCert: clientCert, credAttrClientKey: clientKey, }), nil }
go
func ReadLegacyCloudCredentials(readFile func(string) ([]byte, error)) (cloud.Credential, error) { var ( jujuConfDir = jujupaths.MustSucceed(jujupaths.ConfDir(version.SupportedLTS())) clientCertPath = path.Join(jujuConfDir, "lxd-client.crt") clientKeyPath = path.Join(jujuConfDir, "lxd-client.key") serverCertPath = path.Join(jujuConfDir, "lxd-server.crt") ) readFileString := func(path string) (string, error) { data, err := readFile(path) if err != nil { if os.IsNotExist(err) { err = errors.NotFoundf("%s", path) } return "", errors.Trace(err) } return string(data), nil } clientCert, err := readFileString(clientCertPath) if err != nil { return cloud.Credential{}, errors.Annotate(err, "reading client certificate") } clientKey, err := readFileString(clientKeyPath) if err != nil { return cloud.Credential{}, errors.Annotate(err, "reading client key") } serverCert, err := readFileString(serverCertPath) if err != nil { return cloud.Credential{}, errors.Annotate(err, "reading server certificate") } return cloud.NewCredential(cloud.CertificateAuthType, map[string]string{ credAttrServerCert: serverCert, credAttrClientCert: clientCert, credAttrClientKey: clientKey, }), nil }
[ "func", "ReadLegacyCloudCredentials", "(", "readFile", "func", "(", "string", ")", "(", "[", "]", "byte", ",", "error", ")", ")", "(", "cloud", ".", "Credential", ",", "error", ")", "{", "var", "(", "jujuConfDir", "=", "jujupaths", ".", "MustSucceed", "(", "jujupaths", ".", "ConfDir", "(", "version", ".", "SupportedLTS", "(", ")", ")", ")", "\n", "clientCertPath", "=", "path", ".", "Join", "(", "jujuConfDir", ",", "\"", "\"", ")", "\n", "clientKeyPath", "=", "path", ".", "Join", "(", "jujuConfDir", ",", "\"", "\"", ")", "\n", "serverCertPath", "=", "path", ".", "Join", "(", "jujuConfDir", ",", "\"", "\"", ")", "\n", ")", "\n", "readFileString", ":=", "func", "(", "path", "string", ")", "(", "string", ",", "error", ")", "{", "data", ",", "err", ":=", "readFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "err", "=", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "path", ")", "\n", "}", "\n", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "string", "(", "data", ")", ",", "nil", "\n", "}", "\n", "clientCert", ",", "err", ":=", "readFileString", "(", "clientCertPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "cloud", ".", "Credential", "{", "}", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "clientKey", ",", "err", ":=", "readFileString", "(", "clientKeyPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "cloud", ".", "Credential", "{", "}", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "serverCert", ",", "err", ":=", "readFileString", "(", "serverCertPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "cloud", ".", "Credential", "{", "}", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "cloud", ".", "NewCredential", "(", "cloud", ".", "CertificateAuthType", ",", "map", "[", "string", "]", "string", "{", "credAttrServerCert", ":", "serverCert", ",", "credAttrClientCert", ":", "clientCert", ",", "credAttrClientKey", ":", "clientKey", ",", "}", ")", ",", "nil", "\n", "}" ]
// ReadLegacyCloudCredentials reads cloud credentials off disk for an old // LXD controller, and returns them as a cloud.Credential with the // certificate auth-type. // // If the credential files are missing from the filesystem, an error // satisfying errors.IsNotFound will be returned.
[ "ReadLegacyCloudCredentials", "reads", "cloud", "credentials", "off", "disk", "for", "an", "old", "LXD", "controller", "and", "returns", "them", "as", "a", "cloud", ".", "Credential", "with", "the", "certificate", "auth", "-", "type", ".", "If", "the", "credential", "files", "are", "missing", "from", "the", "filesystem", "an", "error", "satisfying", "errors", ".", "IsNotFound", "will", "be", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/lxd/upgrades.go#L23-L57
4,167
juju/juju
apiserver/common/credentialcommon/modelcredential.go
ValidateExistingModelCredential
func ValidateExistingModelCredential(backend PersistentBackend, callCtx context.ProviderCallContext) (params.ErrorResults, error) { model, err := backend.Model() if err != nil { return params.ErrorResults{}, errors.Trace(err) } credentialTag, isSet := model.CloudCredential() if !isSet { return params.ErrorResults{}, nil } storedCredential, err := backend.CloudCredential(credentialTag) if err != nil { return params.ErrorResults{}, errors.Trace(err) } if !storedCredential.IsValid() { return params.ErrorResults{}, errors.NotValidf("credential %q", storedCredential.Name) } credential := cloud.NewCredential(cloud.AuthType(storedCredential.AuthType), storedCredential.Attributes) return ValidateNewModelCredential(backend, callCtx, credentialTag, &credential) }
go
func ValidateExistingModelCredential(backend PersistentBackend, callCtx context.ProviderCallContext) (params.ErrorResults, error) { model, err := backend.Model() if err != nil { return params.ErrorResults{}, errors.Trace(err) } credentialTag, isSet := model.CloudCredential() if !isSet { return params.ErrorResults{}, nil } storedCredential, err := backend.CloudCredential(credentialTag) if err != nil { return params.ErrorResults{}, errors.Trace(err) } if !storedCredential.IsValid() { return params.ErrorResults{}, errors.NotValidf("credential %q", storedCredential.Name) } credential := cloud.NewCredential(cloud.AuthType(storedCredential.AuthType), storedCredential.Attributes) return ValidateNewModelCredential(backend, callCtx, credentialTag, &credential) }
[ "func", "ValidateExistingModelCredential", "(", "backend", "PersistentBackend", ",", "callCtx", "context", ".", "ProviderCallContext", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "model", ",", "err", ":=", "backend", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "credentialTag", ",", "isSet", ":=", "model", ".", "CloudCredential", "(", ")", "\n", "if", "!", "isSet", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "nil", "\n", "}", "\n\n", "storedCredential", ",", "err", ":=", "backend", ".", "CloudCredential", "(", "credentialTag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "!", "storedCredential", ".", "IsValid", "(", ")", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "storedCredential", ".", "Name", ")", "\n", "}", "\n", "credential", ":=", "cloud", ".", "NewCredential", "(", "cloud", ".", "AuthType", "(", "storedCredential", ".", "AuthType", ")", ",", "storedCredential", ".", "Attributes", ")", "\n", "return", "ValidateNewModelCredential", "(", "backend", ",", "callCtx", ",", "credentialTag", ",", "&", "credential", ")", "\n", "}" ]
// ValidateExistingModelCredential checks if the cloud credential that a given model uses is valid for it.
[ "ValidateExistingModelCredential", "checks", "if", "the", "cloud", "credential", "that", "a", "given", "model", "uses", "is", "valid", "for", "it", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/credentialcommon/modelcredential.go#L21-L42
4,168
juju/juju
apiserver/common/credentialcommon/modelcredential.go
ValidateNewModelCredential
func ValidateNewModelCredential(backend PersistentBackend, callCtx context.ProviderCallContext, credentialTag names.CloudCredentialTag, credential *cloud.Credential) (params.ErrorResults, error) { openParams, err := buildOpenParams(backend, credentialTag, credential) if err != nil { return params.ErrorResults{}, errors.Trace(err) } model, err := backend.Model() if err != nil { return params.ErrorResults{}, errors.Trace(err) } switch model.Type() { case state.ModelTypeCAAS: return checkCAASModelCredential(openParams) case state.ModelTypeIAAS: return checkIAASModelCredential(openParams, backend, callCtx) default: return params.ErrorResults{}, errors.NotSupportedf("model type %q", model.Type()) } }
go
func ValidateNewModelCredential(backend PersistentBackend, callCtx context.ProviderCallContext, credentialTag names.CloudCredentialTag, credential *cloud.Credential) (params.ErrorResults, error) { openParams, err := buildOpenParams(backend, credentialTag, credential) if err != nil { return params.ErrorResults{}, errors.Trace(err) } model, err := backend.Model() if err != nil { return params.ErrorResults{}, errors.Trace(err) } switch model.Type() { case state.ModelTypeCAAS: return checkCAASModelCredential(openParams) case state.ModelTypeIAAS: return checkIAASModelCredential(openParams, backend, callCtx) default: return params.ErrorResults{}, errors.NotSupportedf("model type %q", model.Type()) } }
[ "func", "ValidateNewModelCredential", "(", "backend", "PersistentBackend", ",", "callCtx", "context", ".", "ProviderCallContext", ",", "credentialTag", "names", ".", "CloudCredentialTag", ",", "credential", "*", "cloud", ".", "Credential", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "openParams", ",", "err", ":=", "buildOpenParams", "(", "backend", ",", "credentialTag", ",", "credential", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "model", ",", "err", ":=", "backend", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "switch", "model", ".", "Type", "(", ")", "{", "case", "state", ".", "ModelTypeCAAS", ":", "return", "checkCAASModelCredential", "(", "openParams", ")", "\n", "case", "state", ".", "ModelTypeIAAS", ":", "return", "checkIAASModelCredential", "(", "openParams", ",", "backend", ",", "callCtx", ")", "\n", "default", ":", "return", "params", ".", "ErrorResults", "{", "}", ",", "errors", ".", "NotSupportedf", "(", "\"", "\"", ",", "model", ".", "Type", "(", ")", ")", "\n", "}", "\n", "}" ]
// ValidateNewModelCredential checks if a new cloud credential could be valid for a given model.
[ "ValidateNewModelCredential", "checks", "if", "a", "new", "cloud", "credential", "could", "be", "valid", "for", "a", "given", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/credentialcommon/modelcredential.go#L45-L62
4,169
juju/juju
apiserver/common/credentialcommon/modelcredential.go
checkMachineInstances
func checkMachineInstances(backend PersistentBackend, provider CloudProvider, callCtx context.ProviderCallContext) (params.ErrorResults, error) { fail := func(original error) (params.ErrorResults, error) { return params.ErrorResults{}, original } // Get machines from state machines, err := backend.AllMachines() if err != nil { return fail(errors.Trace(err)) } var results []params.ErrorResult serverError := func(received error) params.ErrorResult { return params.ErrorResult{Error: common.ServerError(received)} } machinesByInstance := make(map[string]string) for _, machine := range machines { if machine.IsContainer() { // Containers don't correspond to instances at the // provider level. continue } if manual, err := machine.IsManual(); err != nil { return fail(errors.Trace(err)) } else if manual { continue } instanceId, err := machine.InstanceId() if errors.IsNotProvisioned(err) { // Skip over this machine; we wouldn't expect the cloud // to know about it. continue } else if err != nil { results = append(results, serverError(errors.Annotatef(err, "getting instance id for machine %s", machine.Id()))) continue } machinesByInstance[string(instanceId)] = machine.Id() } // Check can see all machines' instances instances, err := provider.AllInstances(callCtx) if err != nil { return fail(errors.Trace(err)) } instanceIds := set.NewStrings() for _, instance := range instances { id := string(instance.Id()) instanceIds.Add(id) if _, found := machinesByInstance[id]; !found { results = append(results, serverError(errors.Errorf("no machine with instance %q", id))) } } for instanceId, name := range machinesByInstance { if !instanceIds.Contains(instanceId) { results = append(results, serverError(errors.Errorf("couldn't find instance %q for machine %s", instanceId, name))) } } return params.ErrorResults{Results: results}, nil }
go
func checkMachineInstances(backend PersistentBackend, provider CloudProvider, callCtx context.ProviderCallContext) (params.ErrorResults, error) { fail := func(original error) (params.ErrorResults, error) { return params.ErrorResults{}, original } // Get machines from state machines, err := backend.AllMachines() if err != nil { return fail(errors.Trace(err)) } var results []params.ErrorResult serverError := func(received error) params.ErrorResult { return params.ErrorResult{Error: common.ServerError(received)} } machinesByInstance := make(map[string]string) for _, machine := range machines { if machine.IsContainer() { // Containers don't correspond to instances at the // provider level. continue } if manual, err := machine.IsManual(); err != nil { return fail(errors.Trace(err)) } else if manual { continue } instanceId, err := machine.InstanceId() if errors.IsNotProvisioned(err) { // Skip over this machine; we wouldn't expect the cloud // to know about it. continue } else if err != nil { results = append(results, serverError(errors.Annotatef(err, "getting instance id for machine %s", machine.Id()))) continue } machinesByInstance[string(instanceId)] = machine.Id() } // Check can see all machines' instances instances, err := provider.AllInstances(callCtx) if err != nil { return fail(errors.Trace(err)) } instanceIds := set.NewStrings() for _, instance := range instances { id := string(instance.Id()) instanceIds.Add(id) if _, found := machinesByInstance[id]; !found { results = append(results, serverError(errors.Errorf("no machine with instance %q", id))) } } for instanceId, name := range machinesByInstance { if !instanceIds.Contains(instanceId) { results = append(results, serverError(errors.Errorf("couldn't find instance %q for machine %s", instanceId, name))) } } return params.ErrorResults{Results: results}, nil }
[ "func", "checkMachineInstances", "(", "backend", "PersistentBackend", ",", "provider", "CloudProvider", ",", "callCtx", "context", ".", "ProviderCallContext", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "fail", ":=", "func", "(", "original", "error", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "return", "params", ".", "ErrorResults", "{", "}", ",", "original", "\n", "}", "\n\n", "// Get machines from state", "machines", ",", "err", ":=", "backend", ".", "AllMachines", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fail", "(", "errors", ".", "Trace", "(", "err", ")", ")", "\n", "}", "\n\n", "var", "results", "[", "]", "params", ".", "ErrorResult", "\n\n", "serverError", ":=", "func", "(", "received", "error", ")", "params", ".", "ErrorResult", "{", "return", "params", ".", "ErrorResult", "{", "Error", ":", "common", ".", "ServerError", "(", "received", ")", "}", "\n", "}", "\n\n", "machinesByInstance", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "for", "_", ",", "machine", ":=", "range", "machines", "{", "if", "machine", ".", "IsContainer", "(", ")", "{", "// Containers don't correspond to instances at the", "// provider level.", "continue", "\n", "}", "\n", "if", "manual", ",", "err", ":=", "machine", ".", "IsManual", "(", ")", ";", "err", "!=", "nil", "{", "return", "fail", "(", "errors", ".", "Trace", "(", "err", ")", ")", "\n", "}", "else", "if", "manual", "{", "continue", "\n", "}", "\n", "instanceId", ",", "err", ":=", "machine", ".", "InstanceId", "(", ")", "\n", "if", "errors", ".", "IsNotProvisioned", "(", "err", ")", "{", "// Skip over this machine; we wouldn't expect the cloud", "// to know about it.", "continue", "\n", "}", "else", "if", "err", "!=", "nil", "{", "results", "=", "append", "(", "results", ",", "serverError", "(", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "machine", ".", "Id", "(", ")", ")", ")", ")", "\n", "continue", "\n", "}", "\n", "machinesByInstance", "[", "string", "(", "instanceId", ")", "]", "=", "machine", ".", "Id", "(", ")", "\n", "}", "\n\n", "// Check can see all machines' instances", "instances", ",", "err", ":=", "provider", ".", "AllInstances", "(", "callCtx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fail", "(", "errors", ".", "Trace", "(", "err", ")", ")", "\n", "}", "\n\n", "instanceIds", ":=", "set", ".", "NewStrings", "(", ")", "\n", "for", "_", ",", "instance", ":=", "range", "instances", "{", "id", ":=", "string", "(", "instance", ".", "Id", "(", ")", ")", "\n", "instanceIds", ".", "Add", "(", "id", ")", "\n", "if", "_", ",", "found", ":=", "machinesByInstance", "[", "id", "]", ";", "!", "found", "{", "results", "=", "append", "(", "results", ",", "serverError", "(", "errors", ".", "Errorf", "(", "\"", "\"", ",", "id", ")", ")", ")", "\n", "}", "\n", "}", "\n\n", "for", "instanceId", ",", "name", ":=", "range", "machinesByInstance", "{", "if", "!", "instanceIds", ".", "Contains", "(", "instanceId", ")", "{", "results", "=", "append", "(", "results", ",", "serverError", "(", "errors", ".", "Errorf", "(", "\"", "\"", ",", "instanceId", ",", "name", ")", ")", ")", "\n", "}", "\n", "}", "\n\n", "return", "params", ".", "ErrorResults", "{", "Results", ":", "results", "}", ",", "nil", "\n", "}" ]
// checkMachineInstances compares model machines from state with // the ones reported by the provider using supplied credential. // This only makes sense for non-k8s providers.
[ "checkMachineInstances", "compares", "model", "machines", "from", "state", "with", "the", "ones", "reported", "by", "the", "provider", "using", "supplied", "credential", ".", "This", "only", "makes", "sense", "for", "non", "-", "k8s", "providers", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/credentialcommon/modelcredential.go#L92-L155
4,170
juju/juju
provider/common/provider.go
BootstrapEnv
func (dp DefaultProvider) BootstrapEnv(ctx environs.BootstrapContext, callCtx context.ProviderCallContext, args environs.BootstrapParams) (*environs.BootstrapResult, error) { result, err := Bootstrap(ctx, dp.Env, callCtx, args) if err != nil { return nil, errors.Trace(err) } return result, nil }
go
func (dp DefaultProvider) BootstrapEnv(ctx environs.BootstrapContext, callCtx context.ProviderCallContext, args environs.BootstrapParams) (*environs.BootstrapResult, error) { result, err := Bootstrap(ctx, dp.Env, callCtx, args) if err != nil { return nil, errors.Trace(err) } return result, nil }
[ "func", "(", "dp", "DefaultProvider", ")", "BootstrapEnv", "(", "ctx", "environs", ".", "BootstrapContext", ",", "callCtx", "context", ".", "ProviderCallContext", ",", "args", "environs", ".", "BootstrapParams", ")", "(", "*", "environs", ".", "BootstrapResult", ",", "error", ")", "{", "result", ",", "err", ":=", "Bootstrap", "(", "ctx", ",", "dp", ".", "Env", ",", "callCtx", ",", "args", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// BootstrapEnv bootstraps the Juju environment.
[ "BootstrapEnv", "bootstraps", "the", "Juju", "environment", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/common/provider.go#L22-L28
4,171
juju/juju
provider/common/provider.go
DestroyEnv
func (dp DefaultProvider) DestroyEnv(ctx context.ProviderCallContext) error { if err := Destroy(dp.Env, ctx); err != nil { return errors.Trace(err) } return nil }
go
func (dp DefaultProvider) DestroyEnv(ctx context.ProviderCallContext) error { if err := Destroy(dp.Env, ctx); err != nil { return errors.Trace(err) } return nil }
[ "func", "(", "dp", "DefaultProvider", ")", "DestroyEnv", "(", "ctx", "context", ".", "ProviderCallContext", ")", "error", "{", "if", "err", ":=", "Destroy", "(", "dp", ".", "Env", ",", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DestroyEnv destroys the Juju environment.
[ "DestroyEnv", "destroys", "the", "Juju", "environment", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/common/provider.go#L31-L36
4,172
juju/juju
cloudconfig/cloudinit/helpers.go
addPackageCommandsCommon
func addPackageCommandsCommon( cfg CloudConfig, packageProxySettings proxy.Settings, packageMirror string, addUpdateScripts bool, addUpgradeScripts bool, series string, ) { // Set the package mirror. cfg.SetPackageMirror(packageMirror) // For LTS series which need support for the cloud-tools archive, // we need to enable package-list update regardless of the environ // setting, otherwise bootstrap or provisioning will fail. if config.SeriesRequiresCloudArchiveTools(series) && !addUpdateScripts { addUpdateScripts = true } // Bring packages up-to-date. cfg.SetSystemUpdate(addUpdateScripts) cfg.SetSystemUpgrade(addUpgradeScripts) // Always run this step - this is where we install packages that juju // requires. cfg.addRequiredPackages() // TODO(bogdanteleaga): Deal with proxy settings on CentOS cfg.updateProxySettings(packageProxySettings) }
go
func addPackageCommandsCommon( cfg CloudConfig, packageProxySettings proxy.Settings, packageMirror string, addUpdateScripts bool, addUpgradeScripts bool, series string, ) { // Set the package mirror. cfg.SetPackageMirror(packageMirror) // For LTS series which need support for the cloud-tools archive, // we need to enable package-list update regardless of the environ // setting, otherwise bootstrap or provisioning will fail. if config.SeriesRequiresCloudArchiveTools(series) && !addUpdateScripts { addUpdateScripts = true } // Bring packages up-to-date. cfg.SetSystemUpdate(addUpdateScripts) cfg.SetSystemUpgrade(addUpgradeScripts) // Always run this step - this is where we install packages that juju // requires. cfg.addRequiredPackages() // TODO(bogdanteleaga): Deal with proxy settings on CentOS cfg.updateProxySettings(packageProxySettings) }
[ "func", "addPackageCommandsCommon", "(", "cfg", "CloudConfig", ",", "packageProxySettings", "proxy", ".", "Settings", ",", "packageMirror", "string", ",", "addUpdateScripts", "bool", ",", "addUpgradeScripts", "bool", ",", "series", "string", ",", ")", "{", "// Set the package mirror.", "cfg", ".", "SetPackageMirror", "(", "packageMirror", ")", "\n\n", "// For LTS series which need support for the cloud-tools archive,", "// we need to enable package-list update regardless of the environ", "// setting, otherwise bootstrap or provisioning will fail.", "if", "config", ".", "SeriesRequiresCloudArchiveTools", "(", "series", ")", "&&", "!", "addUpdateScripts", "{", "addUpdateScripts", "=", "true", "\n", "}", "\n\n", "// Bring packages up-to-date.", "cfg", ".", "SetSystemUpdate", "(", "addUpdateScripts", ")", "\n", "cfg", ".", "SetSystemUpgrade", "(", "addUpgradeScripts", ")", "\n\n", "// Always run this step - this is where we install packages that juju", "// requires.", "cfg", ".", "addRequiredPackages", "(", ")", "\n\n", "// TODO(bogdanteleaga): Deal with proxy settings on CentOS", "cfg", ".", "updateProxySettings", "(", "packageProxySettings", ")", "\n", "}" ]
// addPackageCommandsCommon is a helper function which applies the given // packaging-related options to the given CloudConfig.
[ "addPackageCommandsCommon", "is", "a", "helper", "function", "which", "applies", "the", "given", "packaging", "-", "related", "options", "to", "the", "given", "CloudConfig", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/cloudinit/helpers.go#L16-L44
4,173
juju/juju
cloudconfig/cloudinit/helpers.go
renderScriptCommon
func renderScriptCommon(cfg CloudConfig) (string, error) { // TODO(axw): 2013-08-23 bug 1215777 // Carry out configuration for ssh-keys-per-user, // machine-updates-authkeys, using cloud-init config. // // We should work with smoser to get a supported // command in (or next to) cloud-init for manually // invoking cloud-config. This would address the // above comment by removing the need to generate a // script "by hand". // Bootcmds must be run before anything else, // as they may affect package installation. bootcmds := cfg.BootCmds() // Depending on cfg, potentially add package sources and packages. pkgcmds, err := cfg.getCommandsForAddingPackages() if err != nil { return "", err } // Runcmds come last. runcmds := cfg.RunCmds() // We prepend "set -xe". This is already in runcmds, // but added here to avoid relying on that to be // invariant. script := []string{"#!/bin/bash", "set -e"} // We must initialise progress reporting before entering // the subshell and redirecting stderr. script = append(script, InitProgressCmd()) stdout, stderr := cfg.Output(OutAll) script = append(script, "(") if stderr != "" { script = append(script, "(") } script = append(script, bootcmds...) script = append(script, pkgcmds...) script = append(script, runcmds...) if stderr != "" { script = append(script, ") "+stdout) script = append(script, ") "+stderr) } else { script = append(script, ") "+stdout+" 2>&1") } return strings.Join(script, "\n"), nil }
go
func renderScriptCommon(cfg CloudConfig) (string, error) { // TODO(axw): 2013-08-23 bug 1215777 // Carry out configuration for ssh-keys-per-user, // machine-updates-authkeys, using cloud-init config. // // We should work with smoser to get a supported // command in (or next to) cloud-init for manually // invoking cloud-config. This would address the // above comment by removing the need to generate a // script "by hand". // Bootcmds must be run before anything else, // as they may affect package installation. bootcmds := cfg.BootCmds() // Depending on cfg, potentially add package sources and packages. pkgcmds, err := cfg.getCommandsForAddingPackages() if err != nil { return "", err } // Runcmds come last. runcmds := cfg.RunCmds() // We prepend "set -xe". This is already in runcmds, // but added here to avoid relying on that to be // invariant. script := []string{"#!/bin/bash", "set -e"} // We must initialise progress reporting before entering // the subshell and redirecting stderr. script = append(script, InitProgressCmd()) stdout, stderr := cfg.Output(OutAll) script = append(script, "(") if stderr != "" { script = append(script, "(") } script = append(script, bootcmds...) script = append(script, pkgcmds...) script = append(script, runcmds...) if stderr != "" { script = append(script, ") "+stdout) script = append(script, ") "+stderr) } else { script = append(script, ") "+stdout+" 2>&1") } return strings.Join(script, "\n"), nil }
[ "func", "renderScriptCommon", "(", "cfg", "CloudConfig", ")", "(", "string", ",", "error", ")", "{", "// TODO(axw): 2013-08-23 bug 1215777", "// Carry out configuration for ssh-keys-per-user,", "// machine-updates-authkeys, using cloud-init config.", "//", "// We should work with smoser to get a supported", "// command in (or next to) cloud-init for manually", "// invoking cloud-config. This would address the", "// above comment by removing the need to generate a", "// script \"by hand\".", "// Bootcmds must be run before anything else,", "// as they may affect package installation.", "bootcmds", ":=", "cfg", ".", "BootCmds", "(", ")", "\n\n", "// Depending on cfg, potentially add package sources and packages.", "pkgcmds", ",", "err", ":=", "cfg", ".", "getCommandsForAddingPackages", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// Runcmds come last.", "runcmds", ":=", "cfg", ".", "RunCmds", "(", ")", "\n\n", "// We prepend \"set -xe\". This is already in runcmds,", "// but added here to avoid relying on that to be", "// invariant.", "script", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", "\n", "// We must initialise progress reporting before entering", "// the subshell and redirecting stderr.", "script", "=", "append", "(", "script", ",", "InitProgressCmd", "(", ")", ")", "\n", "stdout", ",", "stderr", ":=", "cfg", ".", "Output", "(", "OutAll", ")", "\n", "script", "=", "append", "(", "script", ",", "\"", "\"", ")", "\n", "if", "stderr", "!=", "\"", "\"", "{", "script", "=", "append", "(", "script", ",", "\"", "\"", ")", "\n", "}", "\n", "script", "=", "append", "(", "script", ",", "bootcmds", "...", ")", "\n", "script", "=", "append", "(", "script", ",", "pkgcmds", "...", ")", "\n", "script", "=", "append", "(", "script", ",", "runcmds", "...", ")", "\n", "if", "stderr", "!=", "\"", "\"", "{", "script", "=", "append", "(", "script", ",", "\"", "\"", "+", "stdout", ")", "\n", "script", "=", "append", "(", "script", ",", "\"", "\"", "+", "stderr", ")", "\n", "}", "else", "{", "script", "=", "append", "(", "script", ",", "\"", "\"", "+", "stdout", "+", "\"", "\"", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "script", ",", "\"", "\\n", "\"", ")", ",", "nil", "\n", "}" ]
// renderScriptCommon is a helper function which generates a bash script that // applies all the settings given by the provided CloudConfig when run.
[ "renderScriptCommon", "is", "a", "helper", "function", "which", "generates", "a", "bash", "script", "that", "applies", "all", "the", "settings", "given", "by", "the", "provided", "CloudConfig", "when", "run", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/cloudinit/helpers.go#L48-L94
4,174
juju/juju
apiserver/restricted_root.go
restrictRoot
func restrictRoot(root rpc.Root, check func(string, string) error) *restrictedRoot { return &restrictedRoot{ Root: root, check: check, } }
go
func restrictRoot(root rpc.Root, check func(string, string) error) *restrictedRoot { return &restrictedRoot{ Root: root, check: check, } }
[ "func", "restrictRoot", "(", "root", "rpc", ".", "Root", ",", "check", "func", "(", "string", ",", "string", ")", "error", ")", "*", "restrictedRoot", "{", "return", "&", "restrictedRoot", "{", "Root", ":", "root", ",", "check", ":", "check", ",", "}", "\n", "}" ]
// restrictRoot wraps the provided root so that the check function is // called on all method lookups. If the check returns an error the API // call is blocked.
[ "restrictRoot", "wraps", "the", "provided", "root", "so", "that", "the", "check", "function", "is", "called", "on", "all", "method", "lookups", ".", "If", "the", "check", "returns", "an", "error", "the", "API", "call", "is", "blocked", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/restricted_root.go#L14-L19
4,175
juju/juju
apiserver/restricted_root.go
FindMethod
func (r *restrictedRoot) FindMethod(facadeName string, version int, methodName string) (rpcreflect.MethodCaller, error) { if err := r.check(facadeName, methodName); err != nil { return nil, err } return r.Root.FindMethod(facadeName, version, methodName) }
go
func (r *restrictedRoot) FindMethod(facadeName string, version int, methodName string) (rpcreflect.MethodCaller, error) { if err := r.check(facadeName, methodName); err != nil { return nil, err } return r.Root.FindMethod(facadeName, version, methodName) }
[ "func", "(", "r", "*", "restrictedRoot", ")", "FindMethod", "(", "facadeName", "string", ",", "version", "int", ",", "methodName", "string", ")", "(", "rpcreflect", ".", "MethodCaller", ",", "error", ")", "{", "if", "err", ":=", "r", ".", "check", "(", "facadeName", ",", "methodName", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "r", ".", "Root", ".", "FindMethod", "(", "facadeName", ",", "version", ",", "methodName", ")", "\n", "}" ]
// FindMethod implements rpc.Root.
[ "FindMethod", "implements", "rpc", ".", "Root", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/restricted_root.go#L27-L32
4,176
juju/juju
apiserver/restricted_root.go
restrictAll
func restrictAll(root rpc.Root, err error) *restrictedRoot { return restrictRoot(root, func(string, string) error { return err }) }
go
func restrictAll(root rpc.Root, err error) *restrictedRoot { return restrictRoot(root, func(string, string) error { return err }) }
[ "func", "restrictAll", "(", "root", "rpc", ".", "Root", ",", "err", "error", ")", "*", "restrictedRoot", "{", "return", "restrictRoot", "(", "root", ",", "func", "(", "string", ",", "string", ")", "error", "{", "return", "err", "\n", "}", ")", "\n", "}" ]
// restrictAll blocks all API requests, returned a fixed error.
[ "restrictAll", "blocks", "all", "API", "requests", "returned", "a", "fixed", "error", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/restricted_root.go#L35-L39
4,177
juju/juju
juju/paths/paths.go
osVal
func osVal(ser string, valname osVarType) (string, error) { os, err := series.GetOSFromSeries(ser) if err != nil { return "", err } switch os { case jujuos.Windows: return winVals[valname], nil default: return nixVals[valname], nil } }
go
func osVal(ser string, valname osVarType) (string, error) { os, err := series.GetOSFromSeries(ser) if err != nil { return "", err } switch os { case jujuos.Windows: return winVals[valname], nil default: return nixVals[valname], nil } }
[ "func", "osVal", "(", "ser", "string", ",", "valname", "osVarType", ")", "(", "string", ",", "error", ")", "{", "os", ",", "err", ":=", "series", ".", "GetOSFromSeries", "(", "ser", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "switch", "os", "{", "case", "jujuos", ".", "Windows", ":", "return", "winVals", "[", "valname", "]", ",", "nil", "\n", "default", ":", "return", "nixVals", "[", "valname", "]", ",", "nil", "\n", "}", "\n", "}" ]
// osVal will lookup the value of the key valname // in the appropriate map, based on the series. This will // help reduce boilerplate code
[ "osVal", "will", "lookup", "the", "value", "of", "the", "key", "valname", "in", "the", "appropriate", "map", "based", "on", "the", "series", ".", "This", "will", "help", "reduce", "boilerplate", "code" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/juju/paths/paths.go#L76-L87
4,178
juju/juju
api/watcher/watcher.go
makeWatcherAPICaller
func makeWatcherAPICaller(caller base.APICaller, facadeName, watcherId string) watcherAPICall { bestVersion := caller.BestFacadeVersion(facadeName) return func(request string, result interface{}) error { return caller.APICall(facadeName, bestVersion, watcherId, request, nil, &result) } }
go
func makeWatcherAPICaller(caller base.APICaller, facadeName, watcherId string) watcherAPICall { bestVersion := caller.BestFacadeVersion(facadeName) return func(request string, result interface{}) error { return caller.APICall(facadeName, bestVersion, watcherId, request, nil, &result) } }
[ "func", "makeWatcherAPICaller", "(", "caller", "base", ".", "APICaller", ",", "facadeName", ",", "watcherId", "string", ")", "watcherAPICall", "{", "bestVersion", ":=", "caller", ".", "BestFacadeVersion", "(", "facadeName", ")", "\n", "return", "func", "(", "request", "string", ",", "result", "interface", "{", "}", ")", "error", "{", "return", "caller", ".", "APICall", "(", "facadeName", ",", "bestVersion", ",", "watcherId", ",", "request", ",", "nil", ",", "&", "result", ")", "\n", "}", "\n", "}" ]
// makeWatcherAPICaller creates a watcherAPICall function for a given facade name // and watcherId.
[ "makeWatcherAPICaller", "creates", "a", "watcherAPICall", "function", "for", "a", "given", "facade", "name", "and", "watcherId", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/watcher/watcher.go#L51-L57
4,179
juju/juju
api/watcher/watcher.go
init
func (w *commonWatcher) init() { w.in = make(chan interface{}) if w.newResult == nil { panic("newResult must be set") } if w.call == nil { panic("call must be set") } }
go
func (w *commonWatcher) init() { w.in = make(chan interface{}) if w.newResult == nil { panic("newResult must be set") } if w.call == nil { panic("call must be set") } }
[ "func", "(", "w", "*", "commonWatcher", ")", "init", "(", ")", "{", "w", ".", "in", "=", "make", "(", "chan", "interface", "{", "}", ")", "\n", "if", "w", ".", "newResult", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "w", ".", "call", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// init must be called to initialize an embedded commonWatcher's // fields. Make sure newResult and call fields are set beforehand.
[ "init", "must", "be", "called", "to", "initialize", "an", "embedded", "commonWatcher", "s", "fields", ".", "Make", "sure", "newResult", "and", "call", "fields", "are", "set", "beforehand", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/watcher/watcher.go#L61-L69
4,180
juju/juju
api/watcher/watcher.go
commonLoop
func (w *commonWatcher) commonLoop() { defer close(w.in) var wg sync.WaitGroup wg.Add(1) go func() { // When the watcher has been stopped, we send a Stop request // to the server, which will remove the watcher and return a // CodeStopped error to any currently outstanding call to // Next. If a call to Next happens just after the watcher has // been stopped, we'll get a CodeNotFound error; Either way // we'll return, wait for the stop request to complete, and // the watcher will die with all resources cleaned up. defer wg.Done() <-w.tomb.Dying() if err := w.call("Stop", nil); err != nil { // Don't log an error if a watcher is stopped due to an agent restart. if err.Error() != worker.ErrRestartAgent.Error() && err.Error() != rpc.ErrShutdown.Error() { logger.Errorf("error trying to stop watcher: %v", err) } } }() wg.Add(1) go func() { // Because Next blocks until there are changes, we need to // call it in a separate goroutine, so the watcher can be // stopped normally. defer wg.Done() for { result := w.newResult() err := w.call("Next", &result) if err != nil { if params.IsCodeStopped(err) || params.IsCodeNotFound(err) { if w.tomb.Err() != tomb.ErrStillAlive { // The watcher has been stopped at the client end, so we're // expecting one of the above two kinds of error. // We might see the same errors if the server itself // has been shut down, in which case we leave them // untouched. err = tomb.ErrDying } } // Something went wrong, just report the error and bail out. w.tomb.Kill(err) return } select { case <-w.tomb.Dying(): return case w.in <- result: // Report back the result we just got. } } }() wg.Wait() }
go
func (w *commonWatcher) commonLoop() { defer close(w.in) var wg sync.WaitGroup wg.Add(1) go func() { // When the watcher has been stopped, we send a Stop request // to the server, which will remove the watcher and return a // CodeStopped error to any currently outstanding call to // Next. If a call to Next happens just after the watcher has // been stopped, we'll get a CodeNotFound error; Either way // we'll return, wait for the stop request to complete, and // the watcher will die with all resources cleaned up. defer wg.Done() <-w.tomb.Dying() if err := w.call("Stop", nil); err != nil { // Don't log an error if a watcher is stopped due to an agent restart. if err.Error() != worker.ErrRestartAgent.Error() && err.Error() != rpc.ErrShutdown.Error() { logger.Errorf("error trying to stop watcher: %v", err) } } }() wg.Add(1) go func() { // Because Next blocks until there are changes, we need to // call it in a separate goroutine, so the watcher can be // stopped normally. defer wg.Done() for { result := w.newResult() err := w.call("Next", &result) if err != nil { if params.IsCodeStopped(err) || params.IsCodeNotFound(err) { if w.tomb.Err() != tomb.ErrStillAlive { // The watcher has been stopped at the client end, so we're // expecting one of the above two kinds of error. // We might see the same errors if the server itself // has been shut down, in which case we leave them // untouched. err = tomb.ErrDying } } // Something went wrong, just report the error and bail out. w.tomb.Kill(err) return } select { case <-w.tomb.Dying(): return case w.in <- result: // Report back the result we just got. } } }() wg.Wait() }
[ "func", "(", "w", "*", "commonWatcher", ")", "commonLoop", "(", ")", "{", "defer", "close", "(", "w", ".", "in", ")", "\n", "var", "wg", "sync", ".", "WaitGroup", "\n", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "// When the watcher has been stopped, we send a Stop request", "// to the server, which will remove the watcher and return a", "// CodeStopped error to any currently outstanding call to", "// Next. If a call to Next happens just after the watcher has", "// been stopped, we'll get a CodeNotFound error; Either way", "// we'll return, wait for the stop request to complete, and", "// the watcher will die with all resources cleaned up.", "defer", "wg", ".", "Done", "(", ")", "\n", "<-", "w", ".", "tomb", ".", "Dying", "(", ")", "\n", "if", "err", ":=", "w", ".", "call", "(", "\"", "\"", ",", "nil", ")", ";", "err", "!=", "nil", "{", "// Don't log an error if a watcher is stopped due to an agent restart.", "if", "err", ".", "Error", "(", ")", "!=", "worker", ".", "ErrRestartAgent", ".", "Error", "(", ")", "&&", "err", ".", "Error", "(", ")", "!=", "rpc", ".", "ErrShutdown", ".", "Error", "(", ")", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "// Because Next blocks until there are changes, we need to", "// call it in a separate goroutine, so the watcher can be", "// stopped normally.", "defer", "wg", ".", "Done", "(", ")", "\n", "for", "{", "result", ":=", "w", ".", "newResult", "(", ")", "\n", "err", ":=", "w", ".", "call", "(", "\"", "\"", ",", "&", "result", ")", "\n", "if", "err", "!=", "nil", "{", "if", "params", ".", "IsCodeStopped", "(", "err", ")", "||", "params", ".", "IsCodeNotFound", "(", "err", ")", "{", "if", "w", ".", "tomb", ".", "Err", "(", ")", "!=", "tomb", ".", "ErrStillAlive", "{", "// The watcher has been stopped at the client end, so we're", "// expecting one of the above two kinds of error.", "// We might see the same errors if the server itself", "// has been shut down, in which case we leave them", "// untouched.", "err", "=", "tomb", ".", "ErrDying", "\n", "}", "\n", "}", "\n", "// Something went wrong, just report the error and bail out.", "w", ".", "tomb", ".", "Kill", "(", "err", ")", "\n", "return", "\n", "}", "\n", "select", "{", "case", "<-", "w", ".", "tomb", ".", "Dying", "(", ")", ":", "return", "\n", "case", "w", ".", "in", "<-", "result", ":", "// Report back the result we just got.", "}", "\n", "}", "\n", "}", "(", ")", "\n", "wg", ".", "Wait", "(", ")", "\n", "}" ]
// commonLoop implements the loop structure common to the client // watchers. It should be started in a separate goroutine by any // watcher that embeds commonWatcher. It kills the commonWatcher's // tomb when an error occurs.
[ "commonLoop", "implements", "the", "loop", "structure", "common", "to", "the", "client", "watchers", ".", "It", "should", "be", "started", "in", "a", "separate", "goroutine", "by", "any", "watcher", "that", "embeds", "commonWatcher", ".", "It", "kills", "the", "commonWatcher", "s", "tomb", "when", "an", "error", "occurs", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/watcher/watcher.go#L75-L129
4,181
juju/juju
api/watcher/watcher.go
NewNotifyWatcher
func NewNotifyWatcher(caller base.APICaller, result params.NotifyWatchResult) watcher.NotifyWatcher { w := &notifyWatcher{ caller: caller, notifyWatcherId: result.NotifyWatcherId, out: make(chan struct{}), } w.tomb.Go(w.loop) return w }
go
func NewNotifyWatcher(caller base.APICaller, result params.NotifyWatchResult) watcher.NotifyWatcher { w := &notifyWatcher{ caller: caller, notifyWatcherId: result.NotifyWatcherId, out: make(chan struct{}), } w.tomb.Go(w.loop) return w }
[ "func", "NewNotifyWatcher", "(", "caller", "base", ".", "APICaller", ",", "result", "params", ".", "NotifyWatchResult", ")", "watcher", ".", "NotifyWatcher", "{", "w", ":=", "&", "notifyWatcher", "{", "caller", ":", "caller", ",", "notifyWatcherId", ":", "result", ".", "NotifyWatcherId", ",", "out", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "w", ".", "tomb", ".", "Go", "(", "w", ".", "loop", ")", "\n", "return", "w", "\n", "}" ]
// If an API call returns a NotifyWatchResult, you can use this to turn it into // a local Watcher.
[ "If", "an", "API", "call", "returns", "a", "NotifyWatchResult", "you", "can", "use", "this", "to", "turn", "it", "into", "a", "local", "Watcher", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/watcher/watcher.go#L152-L160
4,182
juju/juju
api/watcher/watcher.go
NewRelationStatusWatcher
func NewRelationStatusWatcher( caller base.APICaller, result params.RelationLifeSuspendedStatusWatchResult, ) watcher.RelationStatusWatcher { w := &relationStatusWatcher{ caller: caller, relationStatusWatcherId: result.RelationStatusWatcherId, out: make(chan []watcher.RelationStatusChange), } w.tomb.Go(func() error { return w.loop(result.Changes) }) return w }
go
func NewRelationStatusWatcher( caller base.APICaller, result params.RelationLifeSuspendedStatusWatchResult, ) watcher.RelationStatusWatcher { w := &relationStatusWatcher{ caller: caller, relationStatusWatcherId: result.RelationStatusWatcherId, out: make(chan []watcher.RelationStatusChange), } w.tomb.Go(func() error { return w.loop(result.Changes) }) return w }
[ "func", "NewRelationStatusWatcher", "(", "caller", "base", ".", "APICaller", ",", "result", "params", ".", "RelationLifeSuspendedStatusWatchResult", ",", ")", "watcher", ".", "RelationStatusWatcher", "{", "w", ":=", "&", "relationStatusWatcher", "{", "caller", ":", "caller", ",", "relationStatusWatcherId", ":", "result", ".", "RelationStatusWatcherId", ",", "out", ":", "make", "(", "chan", "[", "]", "watcher", ".", "RelationStatusChange", ")", ",", "}", "\n", "w", ".", "tomb", ".", "Go", "(", "func", "(", ")", "error", "{", "return", "w", ".", "loop", "(", "result", ".", "Changes", ")", "\n", "}", ")", "\n", "return", "w", "\n", "}" ]
// NewRelationStatusWatcher returns a watcher notifying of changes to // relation life and suspended status.
[ "NewRelationStatusWatcher", "returns", "a", "watcher", "notifying", "of", "changes", "to", "relation", "life", "and", "suspended", "status", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/watcher/watcher.go#L323-L335
4,183
juju/juju
api/watcher/watcher.go
NewOfferStatusWatcher
func NewOfferStatusWatcher( caller base.APICaller, result params.OfferStatusWatchResult, ) watcher.OfferStatusWatcher { w := &offerStatusWatcher{ caller: caller, offerStatusWatcherId: result.OfferStatusWatcherId, out: make(chan []watcher.OfferStatusChange), } w.tomb.Go(func() error { return w.loop(result.Changes) }) return w }
go
func NewOfferStatusWatcher( caller base.APICaller, result params.OfferStatusWatchResult, ) watcher.OfferStatusWatcher { w := &offerStatusWatcher{ caller: caller, offerStatusWatcherId: result.OfferStatusWatcherId, out: make(chan []watcher.OfferStatusChange), } w.tomb.Go(func() error { return w.loop(result.Changes) }) return w }
[ "func", "NewOfferStatusWatcher", "(", "caller", "base", ".", "APICaller", ",", "result", "params", ".", "OfferStatusWatchResult", ",", ")", "watcher", ".", "OfferStatusWatcher", "{", "w", ":=", "&", "offerStatusWatcher", "{", "caller", ":", "caller", ",", "offerStatusWatcherId", ":", "result", ".", "OfferStatusWatcherId", ",", "out", ":", "make", "(", "chan", "[", "]", "watcher", ".", "OfferStatusChange", ")", ",", "}", "\n", "w", ".", "tomb", ".", "Go", "(", "func", "(", ")", "error", "{", "return", "w", ".", "loop", "(", "result", ".", "Changes", ")", "\n", "}", ")", "\n", "return", "w", "\n", "}" ]
// NewOfferStatusWatcher returns a watcher notifying of changes to // offer status.
[ "NewOfferStatusWatcher", "returns", "a", "watcher", "notifying", "of", "changes", "to", "offer", "status", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/watcher/watcher.go#L412-L424
4,184
juju/juju
api/watcher/watcher.go
NewVolumeAttachmentsWatcher
func NewVolumeAttachmentsWatcher(caller base.APICaller, result params.MachineStorageIdsWatchResult) watcher.MachineStorageIdsWatcher { return newMachineStorageIdsWatcher("VolumeAttachmentsWatcher", caller, result) }
go
func NewVolumeAttachmentsWatcher(caller base.APICaller, result params.MachineStorageIdsWatchResult) watcher.MachineStorageIdsWatcher { return newMachineStorageIdsWatcher("VolumeAttachmentsWatcher", caller, result) }
[ "func", "NewVolumeAttachmentsWatcher", "(", "caller", "base", ".", "APICaller", ",", "result", "params", ".", "MachineStorageIdsWatchResult", ")", "watcher", ".", "MachineStorageIdsWatcher", "{", "return", "newMachineStorageIdsWatcher", "(", "\"", "\"", ",", "caller", ",", "result", ")", "\n", "}" ]
// NewVolumeAttachmentsWatcher returns a MachineStorageIdsWatcher which // communicates with the VolumeAttachmentsWatcher API facade to watch // volume attachments.
[ "NewVolumeAttachmentsWatcher", "returns", "a", "MachineStorageIdsWatcher", "which", "communicates", "with", "the", "VolumeAttachmentsWatcher", "API", "facade", "to", "watch", "volume", "attachments", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/watcher/watcher.go#L507-L509
4,185
juju/juju
api/watcher/watcher.go
NewMigrationStatusWatcher
func NewMigrationStatusWatcher(caller base.APICaller, watcherId string) watcher.MigrationStatusWatcher { w := &migrationStatusWatcher{ caller: caller, id: watcherId, out: make(chan watcher.MigrationStatus), } w.tomb.Go(w.loop) return w }
go
func NewMigrationStatusWatcher(caller base.APICaller, watcherId string) watcher.MigrationStatusWatcher { w := &migrationStatusWatcher{ caller: caller, id: watcherId, out: make(chan watcher.MigrationStatus), } w.tomb.Go(w.loop) return w }
[ "func", "NewMigrationStatusWatcher", "(", "caller", "base", ".", "APICaller", ",", "watcherId", "string", ")", "watcher", ".", "MigrationStatusWatcher", "{", "w", ":=", "&", "migrationStatusWatcher", "{", "caller", ":", "caller", ",", "id", ":", "watcherId", ",", "out", ":", "make", "(", "chan", "watcher", ".", "MigrationStatus", ")", ",", "}", "\n", "w", ".", "tomb", ".", "Go", "(", "w", ".", "loop", ")", "\n", "return", "w", "\n", "}" ]
// NewMigrationStatusWatcher takes the NotifyWatcherId returns by the // MigrationSlave.Watch API and returns a watcher which will report // status changes for any migration of the model associated with the // API connection.
[ "NewMigrationStatusWatcher", "takes", "the", "NotifyWatcherId", "returns", "by", "the", "MigrationSlave", ".", "Watch", "API", "and", "returns", "a", "watcher", "which", "will", "report", "status", "changes", "for", "any", "migration", "of", "the", "model", "associated", "with", "the", "API", "connection", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/watcher/watcher.go#L583-L591
4,186
juju/juju
network/netplan/activate.go
BridgeAndActivate
func BridgeAndActivate(params ActivationParams) (*ActivationResult, error) { if len(params.Devices) == 0 { return nil, errors.Errorf("no devices specified") } netplan, err := ReadDirectory(params.Directory) if err != nil { return nil, err } for _, device := range params.Devices { var deviceId string deviceId, deviceType, err := netplan.FindDeviceByNameOrMAC(device.DeviceName, device.MACAddress) if err != nil { return nil, errors.Trace(err) } switch deviceType { case TypeEthernet: err = netplan.BridgeEthernetById(deviceId, device.BridgeName) if err != nil { return nil, err } case TypeBond: err = netplan.BridgeBondById(deviceId, device.BridgeName) if err != nil { return nil, err } case TypeVLAN: err = netplan.BridgeVLANById(deviceId, device.BridgeName) if err != nil { return nil, err } default: return nil, errors.Errorf("unable to create bridge for %q, unknown device type %q", deviceId, deviceType) } } _, err = netplan.Write("") if err != nil { return nil, err } err = netplan.MoveYamlsToBak() if err != nil { netplan.Rollback() return nil, err } environ := os.Environ() // TODO(wpk) 2017-06-21 Is there a way to verify that apply is finished? // https://bugs.launchpad.net/netplan/+bug/1701436 command := fmt.Sprintf("%snetplan generate && netplan apply && sleep 10", params.RunPrefix) result, err := scriptrunner.RunCommand(command, environ, params.Clock, params.Timeout) activationResult := ActivationResult{ Stderr: string(result.Stderr), Stdout: string(result.Stdout), Code: result.Code, } logger.Debugf("Netplan activation result %q %q %d", result.Stderr, result.Stdout, result.Code) if err != nil { netplan.Rollback() return &activationResult, errors.Errorf("bridge activation error: %s", err) } if result.Code != 0 { netplan.Rollback() return &activationResult, errors.Errorf("bridge activation error code %d", result.Code) } return nil, nil }
go
func BridgeAndActivate(params ActivationParams) (*ActivationResult, error) { if len(params.Devices) == 0 { return nil, errors.Errorf("no devices specified") } netplan, err := ReadDirectory(params.Directory) if err != nil { return nil, err } for _, device := range params.Devices { var deviceId string deviceId, deviceType, err := netplan.FindDeviceByNameOrMAC(device.DeviceName, device.MACAddress) if err != nil { return nil, errors.Trace(err) } switch deviceType { case TypeEthernet: err = netplan.BridgeEthernetById(deviceId, device.BridgeName) if err != nil { return nil, err } case TypeBond: err = netplan.BridgeBondById(deviceId, device.BridgeName) if err != nil { return nil, err } case TypeVLAN: err = netplan.BridgeVLANById(deviceId, device.BridgeName) if err != nil { return nil, err } default: return nil, errors.Errorf("unable to create bridge for %q, unknown device type %q", deviceId, deviceType) } } _, err = netplan.Write("") if err != nil { return nil, err } err = netplan.MoveYamlsToBak() if err != nil { netplan.Rollback() return nil, err } environ := os.Environ() // TODO(wpk) 2017-06-21 Is there a way to verify that apply is finished? // https://bugs.launchpad.net/netplan/+bug/1701436 command := fmt.Sprintf("%snetplan generate && netplan apply && sleep 10", params.RunPrefix) result, err := scriptrunner.RunCommand(command, environ, params.Clock, params.Timeout) activationResult := ActivationResult{ Stderr: string(result.Stderr), Stdout: string(result.Stdout), Code: result.Code, } logger.Debugf("Netplan activation result %q %q %d", result.Stderr, result.Stdout, result.Code) if err != nil { netplan.Rollback() return &activationResult, errors.Errorf("bridge activation error: %s", err) } if result.Code != 0 { netplan.Rollback() return &activationResult, errors.Errorf("bridge activation error code %d", result.Code) } return nil, nil }
[ "func", "BridgeAndActivate", "(", "params", "ActivationParams", ")", "(", "*", "ActivationResult", ",", "error", ")", "{", "if", "len", "(", "params", ".", "Devices", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "netplan", ",", "err", ":=", "ReadDirectory", "(", "params", ".", "Directory", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "device", ":=", "range", "params", ".", "Devices", "{", "var", "deviceId", "string", "\n", "deviceId", ",", "deviceType", ",", "err", ":=", "netplan", ".", "FindDeviceByNameOrMAC", "(", "device", ".", "DeviceName", ",", "device", ".", "MACAddress", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "switch", "deviceType", "{", "case", "TypeEthernet", ":", "err", "=", "netplan", ".", "BridgeEthernetById", "(", "deviceId", ",", "device", ".", "BridgeName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "case", "TypeBond", ":", "err", "=", "netplan", ".", "BridgeBondById", "(", "deviceId", ",", "device", ".", "BridgeName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "case", "TypeVLAN", ":", "err", "=", "netplan", ".", "BridgeVLANById", "(", "deviceId", ",", "device", ".", "BridgeName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "default", ":", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "deviceId", ",", "deviceType", ")", "\n", "}", "\n", "}", "\n", "_", ",", "err", "=", "netplan", ".", "Write", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "netplan", ".", "MoveYamlsToBak", "(", ")", "\n", "if", "err", "!=", "nil", "{", "netplan", ".", "Rollback", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "environ", ":=", "os", ".", "Environ", "(", ")", "\n", "// TODO(wpk) 2017-06-21 Is there a way to verify that apply is finished?", "// https://bugs.launchpad.net/netplan/+bug/1701436", "command", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "params", ".", "RunPrefix", ")", "\n\n", "result", ",", "err", ":=", "scriptrunner", ".", "RunCommand", "(", "command", ",", "environ", ",", "params", ".", "Clock", ",", "params", ".", "Timeout", ")", "\n\n", "activationResult", ":=", "ActivationResult", "{", "Stderr", ":", "string", "(", "result", ".", "Stderr", ")", ",", "Stdout", ":", "string", "(", "result", ".", "Stdout", ")", ",", "Code", ":", "result", ".", "Code", ",", "}", "\n\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "result", ".", "Stderr", ",", "result", ".", "Stdout", ",", "result", ".", "Code", ")", "\n\n", "if", "err", "!=", "nil", "{", "netplan", ".", "Rollback", "(", ")", "\n", "return", "&", "activationResult", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "result", ".", "Code", "!=", "0", "{", "netplan", ".", "Rollback", "(", ")", "\n", "return", "&", "activationResult", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "result", ".", "Code", ")", "\n", "}", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// BridgeAndActivate will parse a set of netplan yaml files in a directory, // create a new netplan config with the provided interfaces bridged // bridged, then reconfigure the network using the ifupdown package // for the new bridges.
[ "BridgeAndActivate", "will", "parse", "a", "set", "of", "netplan", "yaml", "files", "in", "a", "directory", "create", "a", "new", "netplan", "config", "with", "the", "provided", "interfaces", "bridged", "bridged", "then", "reconfigure", "the", "network", "using", "the", "ifupdown", "package", "for", "the", "new", "bridges", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/network/netplan/activate.go#L41-L113
4,187
juju/juju
cmd/juju/interact/pollster.go
New
func New(in io.Reader, out, errOut io.Writer) *Pollster { return &Pollster{ scanner: bufio.NewScanner(byteAtATimeReader{in}), out: out, errOut: errOut, in: in, } }
go
func New(in io.Reader, out, errOut io.Writer) *Pollster { return &Pollster{ scanner: bufio.NewScanner(byteAtATimeReader{in}), out: out, errOut: errOut, in: in, } }
[ "func", "New", "(", "in", "io", ".", "Reader", ",", "out", ",", "errOut", "io", ".", "Writer", ")", "*", "Pollster", "{", "return", "&", "Pollster", "{", "scanner", ":", "bufio", ".", "NewScanner", "(", "byteAtATimeReader", "{", "in", "}", ")", ",", "out", ":", "out", ",", "errOut", ":", "errOut", ",", "in", ":", "in", ",", "}", "\n", "}" ]
// New returns a Pollster that wraps the given reader and writer.
[ "New", "returns", "a", "Pollster", "that", "wraps", "the", "given", "reader", "and", "writer", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/interact/pollster.go#L39-L46
4,188
juju/juju
cmd/juju/interact/pollster.go
Select
func (p *Pollster) Select(l List) (string, error) { return p.SelectVerify(l, VerifyOptions(l.Singular, l.Options, l.Default != "")) }
go
func (p *Pollster) Select(l List) (string, error) { return p.SelectVerify(l, VerifyOptions(l.Singular, l.Options, l.Default != "")) }
[ "func", "(", "p", "*", "Pollster", ")", "Select", "(", "l", "List", ")", "(", "string", ",", "error", ")", "{", "return", "p", ".", "SelectVerify", "(", "l", ",", "VerifyOptions", "(", "l", ".", "Singular", ",", "l", ".", "Options", ",", "l", ".", "Default", "!=", "\"", "\"", ")", ")", "\n", "}" ]
// Select queries the user to select from the given list of options.
[ "Select", "queries", "the", "user", "to", "select", "from", "the", "given", "list", "of", "options", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/interact/pollster.go#L76-L78
4,189
juju/juju
cmd/juju/interact/pollster.go
SelectVerify
func (p *Pollster) SelectVerify(l List, verify VerifyFunc) (string, error) { if err := listTmpl.Execute(p.out, l); err != nil { return "", err } question, err := sprint(selectTmpl, l) if err != nil { return "", errors.Trace(err) } val, err := QueryVerify(question, p.scanner, p.out, p.errOut, verify) if err != nil { return "", errors.Trace(err) } if val == "" { return l.Default, nil } return val, nil }
go
func (p *Pollster) SelectVerify(l List, verify VerifyFunc) (string, error) { if err := listTmpl.Execute(p.out, l); err != nil { return "", err } question, err := sprint(selectTmpl, l) if err != nil { return "", errors.Trace(err) } val, err := QueryVerify(question, p.scanner, p.out, p.errOut, verify) if err != nil { return "", errors.Trace(err) } if val == "" { return l.Default, nil } return val, nil }
[ "func", "(", "p", "*", "Pollster", ")", "SelectVerify", "(", "l", "List", ",", "verify", "VerifyFunc", ")", "(", "string", ",", "error", ")", "{", "if", "err", ":=", "listTmpl", ".", "Execute", "(", "p", ".", "out", ",", "l", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "question", ",", "err", ":=", "sprint", "(", "selectTmpl", ",", "l", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "val", ",", "err", ":=", "QueryVerify", "(", "question", ",", "p", ".", "scanner", ",", "p", ".", "out", ",", "p", ".", "errOut", ",", "verify", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "val", "==", "\"", "\"", "{", "return", "l", ".", "Default", ",", "nil", "\n", "}", "\n", "return", "val", ",", "nil", "\n", "}" ]
// SelectVerify queries the user to select from the given list of options, // verifying the choice by passing responses through verify.
[ "SelectVerify", "queries", "the", "user", "to", "select", "from", "the", "given", "list", "of", "options", "verifying", "the", "choice", "by", "passing", "responses", "through", "verify", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/interact/pollster.go#L82-L99
4,190
juju/juju
cmd/juju/interact/pollster.go
Enter
func (p *Pollster) Enter(valueName string) (string, error) { return p.EnterVerify(valueName, func(s string) (ok bool, msg string, err error) { return s != "", "", nil }) }
go
func (p *Pollster) Enter(valueName string) (string, error) { return p.EnterVerify(valueName, func(s string) (ok bool, msg string, err error) { return s != "", "", nil }) }
[ "func", "(", "p", "*", "Pollster", ")", "Enter", "(", "valueName", "string", ")", "(", "string", ",", "error", ")", "{", "return", "p", ".", "EnterVerify", "(", "valueName", ",", "func", "(", "s", "string", ")", "(", "ok", "bool", ",", "msg", "string", ",", "err", "error", ")", "{", "return", "s", "!=", "\"", "\"", ",", "\"", "\"", ",", "nil", "\n", "}", ")", "\n", "}" ]
// Enter requests that the user enter a value. Any value except an empty string // is accepted.
[ "Enter", "requests", "that", "the", "user", "enter", "a", "value", ".", "Any", "value", "except", "an", "empty", "string", "is", "accepted", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/interact/pollster.go#L146-L150
4,191
juju/juju
cmd/juju/interact/pollster.go
EnterPassword
func (p *Pollster) EnterPassword(valueName string) (string, error) { if f, ok := p.in.(*os.File); ok && terminal.IsTerminal(int(f.Fd())) { defer fmt.Fprint(p.out, "\n\n") if _, err := fmt.Fprintf(p.out, "Enter "+valueName+": "); err != nil { return "", errors.Trace(err) } value, err := terminal.ReadPassword(int(f.Fd())) if err != nil { return "", errors.Trace(err) } return string(value), nil } return p.Enter(valueName) }
go
func (p *Pollster) EnterPassword(valueName string) (string, error) { if f, ok := p.in.(*os.File); ok && terminal.IsTerminal(int(f.Fd())) { defer fmt.Fprint(p.out, "\n\n") if _, err := fmt.Fprintf(p.out, "Enter "+valueName+": "); err != nil { return "", errors.Trace(err) } value, err := terminal.ReadPassword(int(f.Fd())) if err != nil { return "", errors.Trace(err) } return string(value), nil } return p.Enter(valueName) }
[ "func", "(", "p", "*", "Pollster", ")", "EnterPassword", "(", "valueName", "string", ")", "(", "string", ",", "error", ")", "{", "if", "f", ",", "ok", ":=", "p", ".", "in", ".", "(", "*", "os", ".", "File", ")", ";", "ok", "&&", "terminal", ".", "IsTerminal", "(", "int", "(", "f", ".", "Fd", "(", ")", ")", ")", "{", "defer", "fmt", ".", "Fprint", "(", "p", ".", "out", ",", "\"", "\\n", "\\n", "\"", ")", "\n", "if", "_", ",", "err", ":=", "fmt", ".", "Fprintf", "(", "p", ".", "out", ",", "\"", "\"", "+", "valueName", "+", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "value", ",", "err", ":=", "terminal", ".", "ReadPassword", "(", "int", "(", "f", ".", "Fd", "(", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "string", "(", "value", ")", ",", "nil", "\n", "}", "\n", "return", "p", ".", "Enter", "(", "valueName", ")", "\n", "}" ]
// EnterPassword works like Enter except that if the pollster's input wraps a // terminal, the user's input will be read without local echo.
[ "EnterPassword", "works", "like", "Enter", "except", "that", "if", "the", "pollster", "s", "input", "wraps", "a", "terminal", "the", "user", "s", "input", "will", "be", "read", "without", "local", "echo", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/interact/pollster.go#L154-L167
4,192
juju/juju
cmd/juju/interact/pollster.go
EnterDefault
func (p *Pollster) EnterDefault(valueName, defVal string) (string, error) { return p.EnterVerifyDefault(valueName, nil, defVal) }
go
func (p *Pollster) EnterDefault(valueName, defVal string) (string, error) { return p.EnterVerifyDefault(valueName, nil, defVal) }
[ "func", "(", "p", "*", "Pollster", ")", "EnterDefault", "(", "valueName", ",", "defVal", "string", ")", "(", "string", ",", "error", ")", "{", "return", "p", ".", "EnterVerifyDefault", "(", "valueName", ",", "nil", ",", "defVal", ")", "\n", "}" ]
// EnterDefault requests that the user enter a value. Any value is accepted. // An empty string is treated as defVal.
[ "EnterDefault", "requests", "that", "the", "user", "enter", "a", "value", ".", "Any", "value", "is", "accepted", ".", "An", "empty", "string", "is", "treated", "as", "defVal", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/interact/pollster.go#L171-L173
4,193
juju/juju
cmd/juju/interact/pollster.go
EnterOptional
func (p *Pollster) EnterOptional(valueName string) (string, error) { return QueryVerify("Enter "+valueName+" (optional): ", p.scanner, p.out, p.errOut, nil) }
go
func (p *Pollster) EnterOptional(valueName string) (string, error) { return QueryVerify("Enter "+valueName+" (optional): ", p.scanner, p.out, p.errOut, nil) }
[ "func", "(", "p", "*", "Pollster", ")", "EnterOptional", "(", "valueName", "string", ")", "(", "string", ",", "error", ")", "{", "return", "QueryVerify", "(", "\"", "\"", "+", "valueName", "+", "\"", "\"", ",", "p", ".", "scanner", ",", "p", ".", "out", ",", "p", ".", "errOut", ",", "nil", ")", "\n", "}" ]
// EnterOptional requests that the user enter a value. It accepts any value, // even an empty string.
[ "EnterOptional", "requests", "that", "the", "user", "enter", "a", "value", ".", "It", "accepts", "any", "value", "even", "an", "empty", "string", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/interact/pollster.go#L193-L195
4,194
juju/juju
cmd/juju/interact/pollster.go
EnterVerifyDefault
func (p *Pollster) EnterVerifyDefault(valueName string, verify VerifyFunc, defVal string) (string, error) { var verifyDefault VerifyFunc if verify != nil { verifyDefault = func(s string) (ok bool, errmsg string, err error) { if s == "" { return true, "", nil } return verify(s) } } s, err := QueryVerify("Enter "+valueName+" ["+defVal+"]: ", p.scanner, p.out, p.errOut, verifyDefault) if err != nil { return "", errors.Trace(err) } if s == "" { return defVal, nil } return s, nil }
go
func (p *Pollster) EnterVerifyDefault(valueName string, verify VerifyFunc, defVal string) (string, error) { var verifyDefault VerifyFunc if verify != nil { verifyDefault = func(s string) (ok bool, errmsg string, err error) { if s == "" { return true, "", nil } return verify(s) } } s, err := QueryVerify("Enter "+valueName+" ["+defVal+"]: ", p.scanner, p.out, p.errOut, verifyDefault) if err != nil { return "", errors.Trace(err) } if s == "" { return defVal, nil } return s, nil }
[ "func", "(", "p", "*", "Pollster", ")", "EnterVerifyDefault", "(", "valueName", "string", ",", "verify", "VerifyFunc", ",", "defVal", "string", ")", "(", "string", ",", "error", ")", "{", "var", "verifyDefault", "VerifyFunc", "\n", "if", "verify", "!=", "nil", "{", "verifyDefault", "=", "func", "(", "s", "string", ")", "(", "ok", "bool", ",", "errmsg", "string", ",", "err", "error", ")", "{", "if", "s", "==", "\"", "\"", "{", "return", "true", ",", "\"", "\"", ",", "nil", "\n", "}", "\n", "return", "verify", "(", "s", ")", "\n", "}", "\n", "}", "\n", "s", ",", "err", ":=", "QueryVerify", "(", "\"", "\"", "+", "valueName", "+", "\"", "\"", "+", "defVal", "+", "\"", "\"", ",", "p", ".", "scanner", ",", "p", ".", "out", ",", "p", ".", "errOut", ",", "verifyDefault", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "s", "==", "\"", "\"", "{", "return", "defVal", ",", "nil", "\n", "}", "\n", "return", "s", ",", "nil", "\n", "}" ]
// EnterVerifyDefault requests that the user enter a value. Values failing to // verify will be rejected with the error message returned by verify. An empty // string will be accepted as the default value even if it would fail // verification.
[ "EnterVerifyDefault", "requests", "that", "the", "user", "enter", "a", "value", ".", "Values", "failing", "to", "verify", "will", "be", "rejected", "with", "the", "error", "message", "returned", "by", "verify", ".", "An", "empty", "string", "will", "be", "accepted", "as", "the", "default", "value", "even", "if", "it", "would", "fail", "verification", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/interact/pollster.go#L201-L219
4,195
juju/juju
cmd/juju/interact/pollster.go
VerifyOptions
func VerifyOptions(singular string, options []string, hasDefault bool) VerifyFunc { return func(s string) (ok bool, errmsg string, err error) { if s == "" { return hasDefault, "", nil } for _, opt := range options { if strings.ToLower(opt) == strings.ToLower(s) { return true, "", nil } } return false, fmt.Sprintf("Invalid %s: %q", singular, s), nil } }
go
func VerifyOptions(singular string, options []string, hasDefault bool) VerifyFunc { return func(s string) (ok bool, errmsg string, err error) { if s == "" { return hasDefault, "", nil } for _, opt := range options { if strings.ToLower(opt) == strings.ToLower(s) { return true, "", nil } } return false, fmt.Sprintf("Invalid %s: %q", singular, s), nil } }
[ "func", "VerifyOptions", "(", "singular", "string", ",", "options", "[", "]", "string", ",", "hasDefault", "bool", ")", "VerifyFunc", "{", "return", "func", "(", "s", "string", ")", "(", "ok", "bool", ",", "errmsg", "string", ",", "err", "error", ")", "{", "if", "s", "==", "\"", "\"", "{", "return", "hasDefault", ",", "\"", "\"", ",", "nil", "\n", "}", "\n", "for", "_", ",", "opt", ":=", "range", "options", "{", "if", "strings", ".", "ToLower", "(", "opt", ")", "==", "strings", ".", "ToLower", "(", "s", ")", "{", "return", "true", ",", "\"", "\"", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "false", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "singular", ",", "s", ")", ",", "nil", "\n", "}", "\n", "}" ]
// VerifyOptions is the verifier used by pollster.Select.
[ "VerifyOptions", "is", "the", "verifier", "used", "by", "pollster", ".", "Select", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/interact/pollster.go#L257-L269
4,196
juju/juju
cmd/juju/interact/pollster.go
names
func names(m map[string]*jsonschema.Schema) []string { ret := make([]string, 0, len(m)) for n := range m { ret = append(ret, n) } sort.Strings(ret) return ret }
go
func names(m map[string]*jsonschema.Schema) []string { ret := make([]string, 0, len(m)) for n := range m { ret = append(ret, n) } sort.Strings(ret) return ret }
[ "func", "names", "(", "m", "map", "[", "string", "]", "*", "jsonschema", ".", "Schema", ")", "[", "]", "string", "{", "ret", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "m", ")", ")", "\n", "for", "n", ":=", "range", "m", "{", "ret", "=", "append", "(", "ret", ",", "n", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "ret", ")", "\n", "return", "ret", "\n", "}" ]
// names returns the list of names of schema in alphabetical order.
[ "names", "returns", "the", "list", "of", "names", "of", "schema", "in", "alphabetical", "order", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/interact/pollster.go#L359-L366
4,197
juju/juju
cmd/juju/interact/pollster.go
convert
func convert(s string, t jsonschema.Type) (interface{}, error) { switch t { case jsonschema.IntegerType: return strconv.Atoi(s) case jsonschema.NumberType: return strconv.ParseFloat(s, 64) case jsonschema.StringType: return s, nil case jsonschema.BooleanType: switch strings.ToLower(s) { case "y", "yes", "true", "t": return true, nil case "n", "no", "false", "f": return false, nil default: return nil, errors.Errorf("unknown value for boolean type: %q", s) } default: return nil, errors.Errorf("don't know how to convert value %q of type %q", s, t) } }
go
func convert(s string, t jsonschema.Type) (interface{}, error) { switch t { case jsonschema.IntegerType: return strconv.Atoi(s) case jsonschema.NumberType: return strconv.ParseFloat(s, 64) case jsonschema.StringType: return s, nil case jsonschema.BooleanType: switch strings.ToLower(s) { case "y", "yes", "true", "t": return true, nil case "n", "no", "false", "f": return false, nil default: return nil, errors.Errorf("unknown value for boolean type: %q", s) } default: return nil, errors.Errorf("don't know how to convert value %q of type %q", s, t) } }
[ "func", "convert", "(", "s", "string", ",", "t", "jsonschema", ".", "Type", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "switch", "t", "{", "case", "jsonschema", ".", "IntegerType", ":", "return", "strconv", ".", "Atoi", "(", "s", ")", "\n", "case", "jsonschema", ".", "NumberType", ":", "return", "strconv", ".", "ParseFloat", "(", "s", ",", "64", ")", "\n", "case", "jsonschema", ".", "StringType", ":", "return", "s", ",", "nil", "\n", "case", "jsonschema", ".", "BooleanType", ":", "switch", "strings", ".", "ToLower", "(", "s", ")", "{", "case", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ":", "return", "true", ",", "nil", "\n", "case", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ":", "return", "false", ",", "nil", "\n", "default", ":", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "s", ")", "\n", "}", "\n", "default", ":", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "s", ",", "t", ")", "\n", "}", "\n", "}" ]
// convert converts the given string to a specific value based on the schema // type that validated it.
[ "convert", "converts", "the", "given", "string", "to", "a", "specific", "value", "based", "on", "the", "schema", "type", "that", "validated", "it", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/interact/pollster.go#L656-L676
4,198
juju/juju
cmd/jujud/agent/unit.go
NewUnitAgent
func NewUnitAgent(ctx *cmd.Context, bufferedLogger *logsender.BufferedLogWriter) (*UnitAgent, error) { prometheusRegistry, err := newPrometheusRegistry() if err != nil { return nil, errors.Trace(err) } return &UnitAgent{ AgentConf: NewAgentConf(""), configChangedVal: voyeur.NewValue(true), ctx: ctx, dead: make(chan struct{}), initialUpgradeCheckComplete: gate.NewLock(), bufferedLogger: bufferedLogger, prometheusRegistry: prometheusRegistry, preUpgradeSteps: upgrades.PreUpgradeSteps, }, nil }
go
func NewUnitAgent(ctx *cmd.Context, bufferedLogger *logsender.BufferedLogWriter) (*UnitAgent, error) { prometheusRegistry, err := newPrometheusRegistry() if err != nil { return nil, errors.Trace(err) } return &UnitAgent{ AgentConf: NewAgentConf(""), configChangedVal: voyeur.NewValue(true), ctx: ctx, dead: make(chan struct{}), initialUpgradeCheckComplete: gate.NewLock(), bufferedLogger: bufferedLogger, prometheusRegistry: prometheusRegistry, preUpgradeSteps: upgrades.PreUpgradeSteps, }, nil }
[ "func", "NewUnitAgent", "(", "ctx", "*", "cmd", ".", "Context", ",", "bufferedLogger", "*", "logsender", ".", "BufferedLogWriter", ")", "(", "*", "UnitAgent", ",", "error", ")", "{", "prometheusRegistry", ",", "err", ":=", "newPrometheusRegistry", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "&", "UnitAgent", "{", "AgentConf", ":", "NewAgentConf", "(", "\"", "\"", ")", ",", "configChangedVal", ":", "voyeur", ".", "NewValue", "(", "true", ")", ",", "ctx", ":", "ctx", ",", "dead", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "initialUpgradeCheckComplete", ":", "gate", ".", "NewLock", "(", ")", ",", "bufferedLogger", ":", "bufferedLogger", ",", "prometheusRegistry", ":", "prometheusRegistry", ",", "preUpgradeSteps", ":", "upgrades", ".", "PreUpgradeSteps", ",", "}", ",", "nil", "\n", "}" ]
// NewUnitAgent creates a new UnitAgent value properly initialized.
[ "NewUnitAgent", "creates", "a", "new", "UnitAgent", "value", "properly", "initialized", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/unit.go#L66-L81
4,199
juju/juju
cmd/jujud/agent/unit.go
Done
func (a *UnitAgent) Done(err error) { a.errReason = err close(a.dead) }
go
func (a *UnitAgent) Done(err error) { a.errReason = err close(a.dead) }
[ "func", "(", "a", "*", "UnitAgent", ")", "Done", "(", "err", "error", ")", "{", "a", ".", "errReason", "=", "err", "\n", "close", "(", "a", ".", "dead", ")", "\n", "}" ]
// Done signals the unit agent is finished
[ "Done", "signals", "the", "unit", "agent", "is", "finished" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/unit.go#L145-L148