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
156,400
juju/juju
resource/serialization.go
DeserializeFingerprint
func DeserializeFingerprint(fpSum []byte) (resource.Fingerprint, error) { var fp resource.Fingerprint if len(fpSum) != 0 { var err error fp, err = resource.NewFingerprint(fpSum) if err != nil { return fp, errors.Trace(err) } } return fp, nil }
go
func DeserializeFingerprint(fpSum []byte) (resource.Fingerprint, error) { var fp resource.Fingerprint if len(fpSum) != 0 { var err error fp, err = resource.NewFingerprint(fpSum) if err != nil { return fp, errors.Trace(err) } } return fp, nil }
[ "func", "DeserializeFingerprint", "(", "fpSum", "[", "]", "byte", ")", "(", "resource", ".", "Fingerprint", ",", "error", ")", "{", "var", "fp", "resource", ".", "Fingerprint", "\n", "if", "len", "(", "fpSum", ")", "!=", "0", "{", "var", "err", "error", "\n", "fp", ",", "err", "=", "resource", ".", "NewFingerprint", "(", "fpSum", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fp", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "fp", ",", "nil", "\n", "}" ]
// DeserializeFingerprint converts the serialized fingerprint back into // a Fingerprint. "zero" values are treated appropriately.
[ "DeserializeFingerprint", "converts", "the", "serialized", "fingerprint", "back", "into", "a", "Fingerprint", ".", "zero", "values", "are", "treated", "appropriately", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/serialization.go#L13-L23
156,401
juju/juju
apiserver/leadership.go
LeadershipCheck
func (m leadershipChecker) LeadershipCheck(applicationName, unitName string) leadership.Token { token := m.checker.Token(applicationName, unitName) return leadershipToken{ applicationName: applicationName, unitName: unitName, token: token, } }
go
func (m leadershipChecker) LeadershipCheck(applicationName, unitName string) leadership.Token { token := m.checker.Token(applicationName, unitName) return leadershipToken{ applicationName: applicationName, unitName: unitName, token: token, } }
[ "func", "(", "m", "leadershipChecker", ")", "LeadershipCheck", "(", "applicationName", ",", "unitName", "string", ")", "leadership", ".", "Token", "{", "token", ":=", "m", ".", "checker", ".", "Token", "(", "applicationName", ",", "unitName", ")", "\n", "return", "leadershipToken", "{", "applicationName", ":", "applicationName", ",", "unitName", ":", "unitName", ",", "token", ":", "token", ",", "}", "\n", "}" ]
// LeadershipCheck is part of the leadership.Checker interface.
[ "LeadershipCheck", "is", "part", "of", "the", "leadership", ".", "Checker", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/leadership.go#L22-L29
156,402
juju/juju
apiserver/leadership.go
Check
func (t leadershipToken) Check(attempt int, out interface{}) error { err := t.token.Check(attempt, out) if errors.Cause(err) == lease.ErrNotHeld { return errors.Errorf("%q is not leader of %q", t.unitName, t.applicationName) } return errors.Trace(err) }
go
func (t leadershipToken) Check(attempt int, out interface{}) error { err := t.token.Check(attempt, out) if errors.Cause(err) == lease.ErrNotHeld { return errors.Errorf("%q is not leader of %q", t.unitName, t.applicationName) } return errors.Trace(err) }
[ "func", "(", "t", "leadershipToken", ")", "Check", "(", "attempt", "int", ",", "out", "interface", "{", "}", ")", "error", "{", "err", ":=", "t", ".", "token", ".", "Check", "(", "attempt", ",", "out", ")", "\n", "if", "errors", ".", "Cause", "(", "err", ")", "==", "lease", ".", "ErrNotHeld", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "t", ".", "unitName", ",", "t", ".", "applicationName", ")", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// Check is part of the leadership.Token interface.
[ "Check", "is", "part", "of", "the", "leadership", ".", "Token", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/leadership.go#L39-L45
156,403
juju/juju
cmd/juju/crossmodel/listformatter.go
formatListSummary
func formatListSummary(writer io.Writer, value interface{}) error { offers, ok := value.(offeredApplications) if !ok { return errors.Errorf("expected value of type %T, got %T", offers, value) } return formatListEndpointsSummary(writer, offers) }
go
func formatListSummary(writer io.Writer, value interface{}) error { offers, ok := value.(offeredApplications) if !ok { return errors.Errorf("expected value of type %T, got %T", offers, value) } return formatListEndpointsSummary(writer, offers) }
[ "func", "formatListSummary", "(", "writer", "io", ".", "Writer", ",", "value", "interface", "{", "}", ")", "error", "{", "offers", ",", "ok", ":=", "value", ".", "(", "offeredApplications", ")", "\n", "if", "!", "ok", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "offers", ",", "value", ")", "\n", "}", "\n", "return", "formatListEndpointsSummary", "(", "writer", ",", "offers", ")", "\n", "}" ]
// formatListSummary returns a tabular summary of remote application offers or // errors out if parameter is not of expected type.
[ "formatListSummary", "returns", "a", "tabular", "summary", "of", "remote", "application", "offers", "or", "errors", "out", "if", "parameter", "is", "not", "of", "expected", "type", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/crossmodel/listformatter.go#L21-L27
156,404
juju/juju
cmd/juju/crossmodel/listformatter.go
formatListEndpointsSummary
func formatListEndpointsSummary(writer io.Writer, offers offeredApplications) error { tw := output.TabWriter(writer) w := output.Wrapper{tw} // Sort offers by source then application name. allOffers := offerItems{} for _, offer := range offers { allOffers = append(allOffers, offer) } sort.Sort(allOffers) w.Println("Offer", "Application", "Charm", "Connected", "Store", "URL", "Endpoint", "Interface", "Role") for _, offer := range allOffers { // Sort endpoints alphabetically. endpoints := []string{} for endpoint := range offer.Endpoints { endpoints = append(endpoints, endpoint) } sort.Strings(endpoints) for i, endpointName := range endpoints { endpoint := offer.Endpoints[endpointName] if i == 0 { // As there is some information about offer and its endpoints, // only display offer information once when the first endpoint is displayed. totalConnectedCount := len(offer.Connections) activeConnectedCount := 0 for _, conn := range offer.Connections { if conn.Status.Current == relation.Joined.String() { activeConnectedCount++ } } w.Println(offer.OfferName, offer.ApplicationName, offer.CharmURL, fmt.Sprintf("%v/%v", activeConnectedCount, totalConnectedCount), offer.Source, offer.OfferURL, endpointName, endpoint.Interface, endpoint.Role) continue } // Subsequent lines only need to display endpoint information. // This will display less noise. w.Println("", "", "", "", "", "", endpointName, endpoint.Interface, endpoint.Role) } } tw.Flush() return nil }
go
func formatListEndpointsSummary(writer io.Writer, offers offeredApplications) error { tw := output.TabWriter(writer) w := output.Wrapper{tw} // Sort offers by source then application name. allOffers := offerItems{} for _, offer := range offers { allOffers = append(allOffers, offer) } sort.Sort(allOffers) w.Println("Offer", "Application", "Charm", "Connected", "Store", "URL", "Endpoint", "Interface", "Role") for _, offer := range allOffers { // Sort endpoints alphabetically. endpoints := []string{} for endpoint := range offer.Endpoints { endpoints = append(endpoints, endpoint) } sort.Strings(endpoints) for i, endpointName := range endpoints { endpoint := offer.Endpoints[endpointName] if i == 0 { // As there is some information about offer and its endpoints, // only display offer information once when the first endpoint is displayed. totalConnectedCount := len(offer.Connections) activeConnectedCount := 0 for _, conn := range offer.Connections { if conn.Status.Current == relation.Joined.String() { activeConnectedCount++ } } w.Println(offer.OfferName, offer.ApplicationName, offer.CharmURL, fmt.Sprintf("%v/%v", activeConnectedCount, totalConnectedCount), offer.Source, offer.OfferURL, endpointName, endpoint.Interface, endpoint.Role) continue } // Subsequent lines only need to display endpoint information. // This will display less noise. w.Println("", "", "", "", "", "", endpointName, endpoint.Interface, endpoint.Role) } } tw.Flush() return nil }
[ "func", "formatListEndpointsSummary", "(", "writer", "io", ".", "Writer", ",", "offers", "offeredApplications", ")", "error", "{", "tw", ":=", "output", ".", "TabWriter", "(", "writer", ")", "\n", "w", ":=", "output", ".", "Wrapper", "{", "tw", "}", "\n\n", "// Sort offers by source then application name.", "allOffers", ":=", "offerItems", "{", "}", "\n", "for", "_", ",", "offer", ":=", "range", "offers", "{", "allOffers", "=", "append", "(", "allOffers", ",", "offer", ")", "\n", "}", "\n", "sort", ".", "Sort", "(", "allOffers", ")", "\n\n", "w", ".", "Println", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "for", "_", ",", "offer", ":=", "range", "allOffers", "{", "// Sort endpoints alphabetically.", "endpoints", ":=", "[", "]", "string", "{", "}", "\n", "for", "endpoint", ":=", "range", "offer", ".", "Endpoints", "{", "endpoints", "=", "append", "(", "endpoints", ",", "endpoint", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "endpoints", ")", "\n\n", "for", "i", ",", "endpointName", ":=", "range", "endpoints", "{", "endpoint", ":=", "offer", ".", "Endpoints", "[", "endpointName", "]", "\n", "if", "i", "==", "0", "{", "// As there is some information about offer and its endpoints,", "// only display offer information once when the first endpoint is displayed.", "totalConnectedCount", ":=", "len", "(", "offer", ".", "Connections", ")", "\n", "activeConnectedCount", ":=", "0", "\n", "for", "_", ",", "conn", ":=", "range", "offer", ".", "Connections", "{", "if", "conn", ".", "Status", ".", "Current", "==", "relation", ".", "Joined", ".", "String", "(", ")", "{", "activeConnectedCount", "++", "\n", "}", "\n", "}", "\n", "w", ".", "Println", "(", "offer", ".", "OfferName", ",", "offer", ".", "ApplicationName", ",", "offer", ".", "CharmURL", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "activeConnectedCount", ",", "totalConnectedCount", ")", ",", "offer", ".", "Source", ",", "offer", ".", "OfferURL", ",", "endpointName", ",", "endpoint", ".", "Interface", ",", "endpoint", ".", "Role", ")", "\n", "continue", "\n", "}", "\n", "// Subsequent lines only need to display endpoint information.", "// This will display less noise.", "w", ".", "Println", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "endpointName", ",", "endpoint", ".", "Interface", ",", "endpoint", ".", "Role", ")", "\n", "}", "\n", "}", "\n", "tw", ".", "Flush", "(", ")", "\n", "return", "nil", "\n", "}" ]
// formatListEndpointsSummary returns a tabular summary of listed applications' endpoints.
[ "formatListEndpointsSummary", "returns", "a", "tabular", "summary", "of", "listed", "applications", "endpoints", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/crossmodel/listformatter.go#L32-L76
156,405
juju/juju
cmd/juju/crossmodel/listformatter.go
formatListEndpointsTabular
func formatListEndpointsTabular(writer io.Writer, offers offeredApplications) error { tw := output.TabWriter(writer) w := output.Wrapper{tw} // Sort offers by source then application name. allOffers := offerItems{} for _, offer := range offers { allOffers = append(allOffers, offer) } sort.Sort(allOffers) w.Println("Offer", "User", "Relation id", "Status", "Endpoint", "Interface", "Role", "Ingress subnets") for _, offer := range allOffers { // Sort endpoints alphabetically. endpoints := []string{} for endpoint := range offer.Endpoints { endpoints = append(endpoints, endpoint) } sort.Strings(endpoints) // Sort connections by relation id and username. sort.Sort(byUserRelationId(offer.Connections)) // If there are no connections, print am empty row. if len(offer.Connections) == 0 { w.Println(offer.OfferName, "-", "", "", "", "", "", "") } for i, conn := range offer.Connections { if i == 0 { w.Print(offer.OfferName) } else { w.Print("") } endpoints := make(map[string]RemoteEndpoint) for alias, ep := range offer.Endpoints { aliasedEp := ep aliasedEp.Name = alias endpoints[ep.Name] = ep } connEp := endpoints[conn.Endpoint] w.Print(conn.Username, conn.RelationId) w.PrintColor(RelationStatusColor(relation.Status(conn.Status.Current)), conn.Status.Current) w.Println(connEp.Name, connEp.Interface, connEp.Role, strings.Join(conn.IngressSubnets, ",")) } } tw.Flush() return nil }
go
func formatListEndpointsTabular(writer io.Writer, offers offeredApplications) error { tw := output.TabWriter(writer) w := output.Wrapper{tw} // Sort offers by source then application name. allOffers := offerItems{} for _, offer := range offers { allOffers = append(allOffers, offer) } sort.Sort(allOffers) w.Println("Offer", "User", "Relation id", "Status", "Endpoint", "Interface", "Role", "Ingress subnets") for _, offer := range allOffers { // Sort endpoints alphabetically. endpoints := []string{} for endpoint := range offer.Endpoints { endpoints = append(endpoints, endpoint) } sort.Strings(endpoints) // Sort connections by relation id and username. sort.Sort(byUserRelationId(offer.Connections)) // If there are no connections, print am empty row. if len(offer.Connections) == 0 { w.Println(offer.OfferName, "-", "", "", "", "", "", "") } for i, conn := range offer.Connections { if i == 0 { w.Print(offer.OfferName) } else { w.Print("") } endpoints := make(map[string]RemoteEndpoint) for alias, ep := range offer.Endpoints { aliasedEp := ep aliasedEp.Name = alias endpoints[ep.Name] = ep } connEp := endpoints[conn.Endpoint] w.Print(conn.Username, conn.RelationId) w.PrintColor(RelationStatusColor(relation.Status(conn.Status.Current)), conn.Status.Current) w.Println(connEp.Name, connEp.Interface, connEp.Role, strings.Join(conn.IngressSubnets, ",")) } } tw.Flush() return nil }
[ "func", "formatListEndpointsTabular", "(", "writer", "io", ".", "Writer", ",", "offers", "offeredApplications", ")", "error", "{", "tw", ":=", "output", ".", "TabWriter", "(", "writer", ")", "\n", "w", ":=", "output", ".", "Wrapper", "{", "tw", "}", "\n\n", "// Sort offers by source then application name.", "allOffers", ":=", "offerItems", "{", "}", "\n", "for", "_", ",", "offer", ":=", "range", "offers", "{", "allOffers", "=", "append", "(", "allOffers", ",", "offer", ")", "\n", "}", "\n", "sort", ".", "Sort", "(", "allOffers", ")", "\n\n", "w", ".", "Println", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "for", "_", ",", "offer", ":=", "range", "allOffers", "{", "// Sort endpoints alphabetically.", "endpoints", ":=", "[", "]", "string", "{", "}", "\n", "for", "endpoint", ":=", "range", "offer", ".", "Endpoints", "{", "endpoints", "=", "append", "(", "endpoints", ",", "endpoint", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "endpoints", ")", "\n\n", "// Sort connections by relation id and username.", "sort", ".", "Sort", "(", "byUserRelationId", "(", "offer", ".", "Connections", ")", ")", "\n\n", "// If there are no connections, print am empty row.", "if", "len", "(", "offer", ".", "Connections", ")", "==", "0", "{", "w", ".", "Println", "(", "offer", ".", "OfferName", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "for", "i", ",", "conn", ":=", "range", "offer", ".", "Connections", "{", "if", "i", "==", "0", "{", "w", ".", "Print", "(", "offer", ".", "OfferName", ")", "\n", "}", "else", "{", "w", ".", "Print", "(", "\"", "\"", ")", "\n", "}", "\n", "endpoints", ":=", "make", "(", "map", "[", "string", "]", "RemoteEndpoint", ")", "\n", "for", "alias", ",", "ep", ":=", "range", "offer", ".", "Endpoints", "{", "aliasedEp", ":=", "ep", "\n", "aliasedEp", ".", "Name", "=", "alias", "\n", "endpoints", "[", "ep", ".", "Name", "]", "=", "ep", "\n", "}", "\n", "connEp", ":=", "endpoints", "[", "conn", ".", "Endpoint", "]", "\n", "w", ".", "Print", "(", "conn", ".", "Username", ",", "conn", ".", "RelationId", ")", "\n", "w", ".", "PrintColor", "(", "RelationStatusColor", "(", "relation", ".", "Status", "(", "conn", ".", "Status", ".", "Current", ")", ")", ",", "conn", ".", "Status", ".", "Current", ")", "\n", "w", ".", "Println", "(", "connEp", ".", "Name", ",", "connEp", ".", "Interface", ",", "connEp", ".", "Role", ",", "strings", ".", "Join", "(", "conn", ".", "IngressSubnets", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "}", "\n", "tw", ".", "Flush", "(", ")", "\n", "return", "nil", "\n", "}" ]
// formatListEndpointsTabular returns a tabular summary of listed applications' endpoints.
[ "formatListEndpointsTabular", "returns", "a", "tabular", "summary", "of", "listed", "applications", "endpoints", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/crossmodel/listformatter.go#L93-L141
156,406
juju/juju
cmd/juju/crossmodel/listformatter.go
RelationStatusColor
func RelationStatusColor(status relation.Status) *ansiterm.Context { switch status { case relation.Joined: return output.GoodHighlight case relation.Suspended: return output.WarningHighlight case relation.Broken, relation.Error: return output.ErrorHighlight } return nil }
go
func RelationStatusColor(status relation.Status) *ansiterm.Context { switch status { case relation.Joined: return output.GoodHighlight case relation.Suspended: return output.WarningHighlight case relation.Broken, relation.Error: return output.ErrorHighlight } return nil }
[ "func", "RelationStatusColor", "(", "status", "relation", ".", "Status", ")", "*", "ansiterm", ".", "Context", "{", "switch", "status", "{", "case", "relation", ".", "Joined", ":", "return", "output", ".", "GoodHighlight", "\n", "case", "relation", ".", "Suspended", ":", "return", "output", ".", "WarningHighlight", "\n", "case", "relation", ".", "Broken", ",", "relation", ".", "Error", ":", "return", "output", ".", "ErrorHighlight", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// RelationStatusColor returns a context used to print the status with the relevant color.
[ "RelationStatusColor", "returns", "a", "context", "used", "to", "print", "the", "status", "with", "the", "relevant", "color", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/crossmodel/listformatter.go#L144-L154
156,407
juju/juju
state/backups/exec.go
runCommand
func runCommand(cmd string, args ...string) error { command := exec.Command(cmd, args...) out, err := command.CombinedOutput() if err == nil { return nil } if _, ok := err.(*exec.ExitError); ok && len(out) > 0 { return errors.Errorf( "error executing %q: %s", cmd, strings.Replace(string(out), "\n", "; ", -1), ) } return errors.Annotatef(err, "error executing %q", cmd) }
go
func runCommand(cmd string, args ...string) error { command := exec.Command(cmd, args...) out, err := command.CombinedOutput() if err == nil { return nil } if _, ok := err.(*exec.ExitError); ok && len(out) > 0 { return errors.Errorf( "error executing %q: %s", cmd, strings.Replace(string(out), "\n", "; ", -1), ) } return errors.Annotatef(err, "error executing %q", cmd) }
[ "func", "runCommand", "(", "cmd", "string", ",", "args", "...", "string", ")", "error", "{", "command", ":=", "exec", ".", "Command", "(", "cmd", ",", "args", "...", ")", "\n", "out", ",", "err", ":=", "command", ".", "CombinedOutput", "(", ")", "\n", "if", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "err", ".", "(", "*", "exec", ".", "ExitError", ")", ";", "ok", "&&", "len", "(", "out", ")", ">", "0", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "cmd", ",", "strings", ".", "Replace", "(", "string", "(", "out", ")", ",", "\"", "\\n", "\"", ",", "\"", "\"", ",", "-", "1", ")", ",", ")", "\n", "}", "\n", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "cmd", ")", "\n", "}" ]
// runCommand execs the provided command. It exists // here so it can be overridden in export_test.go
[ "runCommand", "execs", "the", "provided", "command", ".", "It", "exists", "here", "so", "it", "can", "be", "overridden", "in", "export_test", ".", "go" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/state/backups/exec.go#L15-L29
156,408
juju/juju
container/lxd/initialisation_linux.go
ConfigureLXDProxies
func ConfigureLXDProxies(proxies proxy.Settings) error { running, err := IsRunningLocally() if err != nil { return errors.Trace(err) } if !running { logger.Debugf("LXD is not running; skipping proxy configuration") return nil } svr, err := NewLocalServer() if err != nil { return errors.Trace(err) } return errors.Trace(svr.UpdateServerConfig(map[string]string{ "core.proxy_http": proxies.Http, "core.proxy_https": proxies.Https, "core.proxy_ignore_hosts": proxies.NoProxy, })) }
go
func ConfigureLXDProxies(proxies proxy.Settings) error { running, err := IsRunningLocally() if err != nil { return errors.Trace(err) } if !running { logger.Debugf("LXD is not running; skipping proxy configuration") return nil } svr, err := NewLocalServer() if err != nil { return errors.Trace(err) } return errors.Trace(svr.UpdateServerConfig(map[string]string{ "core.proxy_http": proxies.Http, "core.proxy_https": proxies.Https, "core.proxy_ignore_hosts": proxies.NoProxy, })) }
[ "func", "ConfigureLXDProxies", "(", "proxies", "proxy", ".", "Settings", ")", "error", "{", "running", ",", "err", ":=", "IsRunningLocally", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "!", "running", "{", "logger", ".", "Debugf", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "svr", ",", "err", ":=", "NewLocalServer", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "errors", ".", "Trace", "(", "svr", ".", "UpdateServerConfig", "(", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "proxies", ".", "Http", ",", "\"", "\"", ":", "proxies", ".", "Https", ",", "\"", "\"", ":", "proxies", ".", "NoProxy", ",", "}", ")", ")", "\n", "}" ]
// ConfigureLXDProxies will try to set the lxc config core.proxy_http and // core.proxy_https configuration values based on the current environment. // If LXD is not installed, we skip the configuration.
[ "ConfigureLXDProxies", "will", "try", "to", "set", "the", "lxc", "config", "core", ".", "proxy_http", "and", "core", ".", "proxy_https", "configuration", "values", "based", "on", "the", "current", "environment", ".", "If", "LXD", "is", "not", "installed", "we", "skip", "the", "configuration", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/initialisation_linux.go#L109-L130
156,409
juju/juju
container/lxd/initialisation_linux.go
ensureDependencies
func ensureDependencies(series string) error { if series == "precise" { return errors.NotSupportedf(`LXD containers on series "precise"`) } if lxdViaSnap() { logger.Infof("LXD snap is installed; skipping package installation") return nil } pacman, err := getPackageManager(series) if err != nil { return errors.Trace(err) } pacconfer, err := getPackagingConfigurer(series) if err != nil { return errors.Trace(err) } for _, pack := range requiredPackages { pkg := pack if config.SeriesRequiresCloudArchiveTools(series) && pacconfer.IsCloudArchivePackage(pack) { pkg = strings.Join(pacconfer.ApplyCloudArchiveTarget(pack), " ") } if config.RequiresBackports(series, pack) { pkg = fmt.Sprintf("--target-release %s-backports %s", series, pkg) } if err := pacman.Install(pkg); err != nil { return errors.Trace(err) } } return errors.Trace(err) }
go
func ensureDependencies(series string) error { if series == "precise" { return errors.NotSupportedf(`LXD containers on series "precise"`) } if lxdViaSnap() { logger.Infof("LXD snap is installed; skipping package installation") return nil } pacman, err := getPackageManager(series) if err != nil { return errors.Trace(err) } pacconfer, err := getPackagingConfigurer(series) if err != nil { return errors.Trace(err) } for _, pack := range requiredPackages { pkg := pack if config.SeriesRequiresCloudArchiveTools(series) && pacconfer.IsCloudArchivePackage(pack) { pkg = strings.Join(pacconfer.ApplyCloudArchiveTarget(pack), " ") } if config.RequiresBackports(series, pack) { pkg = fmt.Sprintf("--target-release %s-backports %s", series, pkg) } if err := pacman.Install(pkg); err != nil { return errors.Trace(err) } } return errors.Trace(err) }
[ "func", "ensureDependencies", "(", "series", "string", ")", "error", "{", "if", "series", "==", "\"", "\"", "{", "return", "errors", ".", "NotSupportedf", "(", "`LXD containers on series \"precise\"`", ")", "\n", "}", "\n\n", "if", "lxdViaSnap", "(", ")", "{", "logger", ".", "Infof", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "pacman", ",", "err", ":=", "getPackageManager", "(", "series", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "pacconfer", ",", "err", ":=", "getPackagingConfigurer", "(", "series", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "for", "_", ",", "pack", ":=", "range", "requiredPackages", "{", "pkg", ":=", "pack", "\n", "if", "config", ".", "SeriesRequiresCloudArchiveTools", "(", "series", ")", "&&", "pacconfer", ".", "IsCloudArchivePackage", "(", "pack", ")", "{", "pkg", "=", "strings", ".", "Join", "(", "pacconfer", ".", "ApplyCloudArchiveTarget", "(", "pack", ")", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "config", ".", "RequiresBackports", "(", "series", ",", "pack", ")", "{", "pkg", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "series", ",", "pkg", ")", "\n", "}", "\n\n", "if", "err", ":=", "pacman", ".", "Install", "(", "pkg", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// ensureDependencies creates a set of install packages using // apt.GetPreparePackages and runs each set of packages through // apt.GetInstall.
[ "ensureDependencies", "creates", "a", "set", "of", "install", "packages", "using", "apt", ".", "GetPreparePackages", "and", "runs", "each", "set", "of", "packages", "through", "apt", ".", "GetInstall", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/initialisation_linux.go#L263-L299
156,410
juju/juju
container/lxd/initialisation_linux.go
getKnownV4IPsAndCIDRs
func getKnownV4IPsAndCIDRs(addrFunc func() ([]net.Addr, error)) ([]net.IP, []*net.IPNet, error) { addrs, err := addrFunc() if err != nil { return nil, nil, errors.Annotate(err, "cannot get network interface addresses") } knownIPs := []net.IP{} seenIPs := set.NewStrings() knownCIDRs := []*net.IPNet{} seenCIDRs := set.NewStrings() for _, netAddr := range addrs { ip, ipNet, err := net.ParseCIDR(netAddr.String()) if err != nil { continue } if ip.To4() == nil { continue } if !seenIPs.Contains(ip.String()) { knownIPs = append(knownIPs, ip) seenIPs.Add(ip.String()) } if !seenCIDRs.Contains(ipNet.String()) { knownCIDRs = append(knownCIDRs, ipNet) seenCIDRs.Add(ipNet.String()) } } return knownIPs, knownCIDRs, nil }
go
func getKnownV4IPsAndCIDRs(addrFunc func() ([]net.Addr, error)) ([]net.IP, []*net.IPNet, error) { addrs, err := addrFunc() if err != nil { return nil, nil, errors.Annotate(err, "cannot get network interface addresses") } knownIPs := []net.IP{} seenIPs := set.NewStrings() knownCIDRs := []*net.IPNet{} seenCIDRs := set.NewStrings() for _, netAddr := range addrs { ip, ipNet, err := net.ParseCIDR(netAddr.String()) if err != nil { continue } if ip.To4() == nil { continue } if !seenIPs.Contains(ip.String()) { knownIPs = append(knownIPs, ip) seenIPs.Add(ip.String()) } if !seenCIDRs.Contains(ipNet.String()) { knownCIDRs = append(knownCIDRs, ipNet) seenCIDRs.Add(ipNet.String()) } } return knownIPs, knownCIDRs, nil }
[ "func", "getKnownV4IPsAndCIDRs", "(", "addrFunc", "func", "(", ")", "(", "[", "]", "net", ".", "Addr", ",", "error", ")", ")", "(", "[", "]", "net", ".", "IP", ",", "[", "]", "*", "net", ".", "IPNet", ",", "error", ")", "{", "addrs", ",", "err", ":=", "addrFunc", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "knownIPs", ":=", "[", "]", "net", ".", "IP", "{", "}", "\n", "seenIPs", ":=", "set", ".", "NewStrings", "(", ")", "\n", "knownCIDRs", ":=", "[", "]", "*", "net", ".", "IPNet", "{", "}", "\n", "seenCIDRs", ":=", "set", ".", "NewStrings", "(", ")", "\n", "for", "_", ",", "netAddr", ":=", "range", "addrs", "{", "ip", ",", "ipNet", ",", "err", ":=", "net", ".", "ParseCIDR", "(", "netAddr", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "if", "ip", ".", "To4", "(", ")", "==", "nil", "{", "continue", "\n", "}", "\n", "if", "!", "seenIPs", ".", "Contains", "(", "ip", ".", "String", "(", ")", ")", "{", "knownIPs", "=", "append", "(", "knownIPs", ",", "ip", ")", "\n", "seenIPs", ".", "Add", "(", "ip", ".", "String", "(", ")", ")", "\n", "}", "\n", "if", "!", "seenCIDRs", ".", "Contains", "(", "ipNet", ".", "String", "(", ")", ")", "{", "knownCIDRs", "=", "append", "(", "knownCIDRs", ",", "ipNet", ")", "\n", "seenCIDRs", ".", "Add", "(", "ipNet", ".", "String", "(", ")", ")", "\n", "}", "\n", "}", "\n", "return", "knownIPs", ",", "knownCIDRs", ",", "nil", "\n", "}" ]
// getKnownV4IPsAndCIDRs iterates all of the known Addresses on this machine // and groups them up into known CIDRs and IP addresses.
[ "getKnownV4IPsAndCIDRs", "iterates", "all", "of", "the", "known", "Addresses", "on", "this", "machine", "and", "groups", "them", "up", "into", "known", "CIDRs", "and", "IP", "addresses", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/initialisation_linux.go#L315-L343
156,411
juju/juju
container/lxd/initialisation_linux.go
bridgeConfiguration
func bridgeConfiguration(input string) (string, error) { values := parseLXDBridgeConfigValues(input) ipAddr := net.ParseIP(values["LXD_IPV4_ADDR"]) if ipAddr == nil || ipAddr.To4() == nil { logger.Infof("LXD_IPV4_ADDR is not set; searching for unused subnet") subnet, err := findNextAvailableIPv4Subnet() if err != nil { return "", errors.Trace(err) } logger.Infof("setting LXD_IPV4_ADDR=10.0.%s.1", subnet) return editLXDBridgeFile(input, subnet), nil } return input, nil }
go
func bridgeConfiguration(input string) (string, error) { values := parseLXDBridgeConfigValues(input) ipAddr := net.ParseIP(values["LXD_IPV4_ADDR"]) if ipAddr == nil || ipAddr.To4() == nil { logger.Infof("LXD_IPV4_ADDR is not set; searching for unused subnet") subnet, err := findNextAvailableIPv4Subnet() if err != nil { return "", errors.Trace(err) } logger.Infof("setting LXD_IPV4_ADDR=10.0.%s.1", subnet) return editLXDBridgeFile(input, subnet), nil } return input, nil }
[ "func", "bridgeConfiguration", "(", "input", "string", ")", "(", "string", ",", "error", ")", "{", "values", ":=", "parseLXDBridgeConfigValues", "(", "input", ")", "\n", "ipAddr", ":=", "net", ".", "ParseIP", "(", "values", "[", "\"", "\"", "]", ")", "\n\n", "if", "ipAddr", "==", "nil", "||", "ipAddr", ".", "To4", "(", ")", "==", "nil", "{", "logger", ".", "Infof", "(", "\"", "\"", ")", "\n", "subnet", ",", "err", ":=", "findNextAvailableIPv4Subnet", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "logger", ".", "Infof", "(", "\"", "\"", ",", "subnet", ")", "\n", "return", "editLXDBridgeFile", "(", "input", ",", "subnet", ")", ",", "nil", "\n", "}", "\n", "return", "input", ",", "nil", "\n", "}" ]
// bridgeConfiguration ensures that input has a valid setting for // LXD_IPV4_ADDR, returning the existing input if is already set, and // allocating the next available subnet if it is not.
[ "bridgeConfiguration", "ensures", "that", "input", "has", "a", "valid", "setting", "for", "LXD_IPV4_ADDR", "returning", "the", "existing", "input", "if", "is", "already", "set", "and", "allocating", "the", "next", "available", "subnet", "if", "it", "is", "not", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/initialisation_linux.go#L421-L435
156,412
juju/juju
container/lxd/initialisation_linux.go
InstalledServiceName
func InstalledServiceName() (string, error) { names, err := service.ListServices() if err != nil { return "", errors.Trace(err) } // Prefer the Snap service. svcName := "" for _, name := range names { if name == "snap.lxd.daemon" { return name, nil } if name == "lxd" { svcName = name } } return svcName, nil }
go
func InstalledServiceName() (string, error) { names, err := service.ListServices() if err != nil { return "", errors.Trace(err) } // Prefer the Snap service. svcName := "" for _, name := range names { if name == "snap.lxd.daemon" { return name, nil } if name == "lxd" { svcName = name } } return svcName, nil }
[ "func", "InstalledServiceName", "(", ")", "(", "string", ",", "error", ")", "{", "names", ",", "err", ":=", "service", ".", "ListServices", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// Prefer the Snap service.", "svcName", ":=", "\"", "\"", "\n", "for", "_", ",", "name", ":=", "range", "names", "{", "if", "name", "==", "\"", "\"", "{", "return", "name", ",", "nil", "\n", "}", "\n", "if", "name", "==", "\"", "\"", "{", "svcName", "=", "name", "\n", "}", "\n", "}", "\n", "return", "svcName", ",", "nil", "\n", "}" ]
// InstalledServiceName returns the name of the running service for the LXD // daemon. If LXD is not installed, the return is an empty string.
[ "InstalledServiceName", "returns", "the", "name", "of", "the", "running", "service", "for", "the", "LXD", "daemon", ".", "If", "LXD", "is", "not", "installed", "the", "return", "is", "an", "empty", "string", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/initialisation_linux.go#L464-L481
156,413
juju/juju
cloudconfig/podcfg/podcfg.go
AgentConfig
func (cfg *ControllerPodConfig) AgentConfig(tag names.Tag) (agent.ConfigSetterWriter, error) { var password, cacert string if cfg.Controller == nil { password = cfg.APIInfo.Password cacert = cfg.APIInfo.CACert } else { password = cfg.Controller.MongoInfo.Password cacert = cfg.Controller.MongoInfo.CACert } configParams := agent.AgentConfigParams{ Paths: agent.Paths{ DataDir: cfg.DataDir, LogDir: cfg.LogDir, MetricsSpoolDir: cfg.MetricsSpoolDir, }, Jobs: cfg.Jobs, Tag: tag, UpgradedToVersion: cfg.JujuVersion, Password: password, Nonce: cfg.PodNonce, APIAddresses: cfg.APIHostAddrs(), CACert: cacert, Values: cfg.AgentEnvironment, Controller: cfg.ControllerTag, Model: cfg.APIInfo.ModelTag, MongoVersion: jujudbVersion, MongoMemoryProfile: mongo.MemoryProfile(cfg.Controller.Config.MongoMemoryProfile()), } return agent.NewStateMachineConfig(configParams, cfg.Bootstrap.StateServingInfo) }
go
func (cfg *ControllerPodConfig) AgentConfig(tag names.Tag) (agent.ConfigSetterWriter, error) { var password, cacert string if cfg.Controller == nil { password = cfg.APIInfo.Password cacert = cfg.APIInfo.CACert } else { password = cfg.Controller.MongoInfo.Password cacert = cfg.Controller.MongoInfo.CACert } configParams := agent.AgentConfigParams{ Paths: agent.Paths{ DataDir: cfg.DataDir, LogDir: cfg.LogDir, MetricsSpoolDir: cfg.MetricsSpoolDir, }, Jobs: cfg.Jobs, Tag: tag, UpgradedToVersion: cfg.JujuVersion, Password: password, Nonce: cfg.PodNonce, APIAddresses: cfg.APIHostAddrs(), CACert: cacert, Values: cfg.AgentEnvironment, Controller: cfg.ControllerTag, Model: cfg.APIInfo.ModelTag, MongoVersion: jujudbVersion, MongoMemoryProfile: mongo.MemoryProfile(cfg.Controller.Config.MongoMemoryProfile()), } return agent.NewStateMachineConfig(configParams, cfg.Bootstrap.StateServingInfo) }
[ "func", "(", "cfg", "*", "ControllerPodConfig", ")", "AgentConfig", "(", "tag", "names", ".", "Tag", ")", "(", "agent", ".", "ConfigSetterWriter", ",", "error", ")", "{", "var", "password", ",", "cacert", "string", "\n", "if", "cfg", ".", "Controller", "==", "nil", "{", "password", "=", "cfg", ".", "APIInfo", ".", "Password", "\n", "cacert", "=", "cfg", ".", "APIInfo", ".", "CACert", "\n", "}", "else", "{", "password", "=", "cfg", ".", "Controller", ".", "MongoInfo", ".", "Password", "\n", "cacert", "=", "cfg", ".", "Controller", ".", "MongoInfo", ".", "CACert", "\n", "}", "\n", "configParams", ":=", "agent", ".", "AgentConfigParams", "{", "Paths", ":", "agent", ".", "Paths", "{", "DataDir", ":", "cfg", ".", "DataDir", ",", "LogDir", ":", "cfg", ".", "LogDir", ",", "MetricsSpoolDir", ":", "cfg", ".", "MetricsSpoolDir", ",", "}", ",", "Jobs", ":", "cfg", ".", "Jobs", ",", "Tag", ":", "tag", ",", "UpgradedToVersion", ":", "cfg", ".", "JujuVersion", ",", "Password", ":", "password", ",", "Nonce", ":", "cfg", ".", "PodNonce", ",", "APIAddresses", ":", "cfg", ".", "APIHostAddrs", "(", ")", ",", "CACert", ":", "cacert", ",", "Values", ":", "cfg", ".", "AgentEnvironment", ",", "Controller", ":", "cfg", ".", "ControllerTag", ",", "Model", ":", "cfg", ".", "APIInfo", ".", "ModelTag", ",", "MongoVersion", ":", "jujudbVersion", ",", "MongoMemoryProfile", ":", "mongo", ".", "MemoryProfile", "(", "cfg", ".", "Controller", ".", "Config", ".", "MongoMemoryProfile", "(", ")", ")", ",", "}", "\n", "return", "agent", ".", "NewStateMachineConfig", "(", "configParams", ",", "cfg", ".", "Bootstrap", ".", "StateServingInfo", ")", "\n", "}" ]
// AgentConfig returns an agent config.
[ "AgentConfig", "returns", "an", "agent", "config", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/podcfg/podcfg.go#L105-L134
156,414
juju/juju
cloudconfig/podcfg/podcfg.go
APIHostAddrs
func (cfg *ControllerPodConfig) APIHostAddrs() []string { var hosts []string if cfg.Bootstrap != nil { hosts = append(hosts, net.JoinHostPort( "localhost", strconv.Itoa(cfg.Bootstrap.StateServingInfo.APIPort)), ) } if cfg.APIInfo != nil { hosts = append(hosts, cfg.APIInfo.Addrs...) } return hosts }
go
func (cfg *ControllerPodConfig) APIHostAddrs() []string { var hosts []string if cfg.Bootstrap != nil { hosts = append(hosts, net.JoinHostPort( "localhost", strconv.Itoa(cfg.Bootstrap.StateServingInfo.APIPort)), ) } if cfg.APIInfo != nil { hosts = append(hosts, cfg.APIInfo.Addrs...) } return hosts }
[ "func", "(", "cfg", "*", "ControllerPodConfig", ")", "APIHostAddrs", "(", ")", "[", "]", "string", "{", "var", "hosts", "[", "]", "string", "\n", "if", "cfg", ".", "Bootstrap", "!=", "nil", "{", "hosts", "=", "append", "(", "hosts", ",", "net", ".", "JoinHostPort", "(", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "cfg", ".", "Bootstrap", ".", "StateServingInfo", ".", "APIPort", ")", ")", ",", ")", "\n", "}", "\n", "if", "cfg", ".", "APIInfo", "!=", "nil", "{", "hosts", "=", "append", "(", "hosts", ",", "cfg", ".", "APIInfo", ".", "Addrs", "...", ")", "\n", "}", "\n", "return", "hosts", "\n", "}" ]
// APIHostAddrs returns a list of api server addresses.
[ "APIHostAddrs", "returns", "a", "list", "of", "api", "server", "addresses", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/podcfg/podcfg.go#L137-L148
156,415
juju/juju
cloudconfig/podcfg/podcfg.go
VerifyConfig
func (cfg *ControllerPodConfig) VerifyConfig() (err error) { defer errors.DeferredAnnotatef(&err, "invalid controller pod configuration") if !names.IsValidMachine(cfg.MachineId) { return errors.New("invalid machine id") } if cfg.DataDir == "" { return errors.New("missing var directory") } if cfg.LogDir == "" { return errors.New("missing log directory") } if cfg.MetricsSpoolDir == "" { return errors.New("missing metrics spool directory") } if len(cfg.Jobs) == 0 { return errors.New("missing machine jobs") } if cfg.JujuVersion == version.Zero { return errors.New("missing juju version") } if cfg.APIInfo == nil { return errors.New("missing API info") } if cfg.APIInfo.ModelTag.Id() == "" { return errors.New("missing model tag") } if len(cfg.APIInfo.CACert) == 0 { return errors.New("missing API CA certificate") } if cfg.PodNonce == "" { return errors.New("missing pod nonce") } if cfg.ControllerName == "" { return errors.New("missing controller name") } if cfg.Controller != nil { if err := cfg.verifyControllerConfig(); err != nil { return errors.Trace(err) } } if cfg.Bootstrap != nil { if err := cfg.verifyBootstrapConfig(); err != nil { return errors.Trace(err) } } else { if cfg.APIInfo.Tag != names.NewMachineTag(cfg.MachineId) { return errors.New("API entity tag must match started machine") } if len(cfg.APIInfo.Addrs) == 0 { return errors.New("missing API hosts") } } return nil }
go
func (cfg *ControllerPodConfig) VerifyConfig() (err error) { defer errors.DeferredAnnotatef(&err, "invalid controller pod configuration") if !names.IsValidMachine(cfg.MachineId) { return errors.New("invalid machine id") } if cfg.DataDir == "" { return errors.New("missing var directory") } if cfg.LogDir == "" { return errors.New("missing log directory") } if cfg.MetricsSpoolDir == "" { return errors.New("missing metrics spool directory") } if len(cfg.Jobs) == 0 { return errors.New("missing machine jobs") } if cfg.JujuVersion == version.Zero { return errors.New("missing juju version") } if cfg.APIInfo == nil { return errors.New("missing API info") } if cfg.APIInfo.ModelTag.Id() == "" { return errors.New("missing model tag") } if len(cfg.APIInfo.CACert) == 0 { return errors.New("missing API CA certificate") } if cfg.PodNonce == "" { return errors.New("missing pod nonce") } if cfg.ControllerName == "" { return errors.New("missing controller name") } if cfg.Controller != nil { if err := cfg.verifyControllerConfig(); err != nil { return errors.Trace(err) } } if cfg.Bootstrap != nil { if err := cfg.verifyBootstrapConfig(); err != nil { return errors.Trace(err) } } else { if cfg.APIInfo.Tag != names.NewMachineTag(cfg.MachineId) { return errors.New("API entity tag must match started machine") } if len(cfg.APIInfo.Addrs) == 0 { return errors.New("missing API hosts") } } return nil }
[ "func", "(", "cfg", "*", "ControllerPodConfig", ")", "VerifyConfig", "(", ")", "(", "err", "error", ")", "{", "defer", "errors", ".", "DeferredAnnotatef", "(", "&", "err", ",", "\"", "\"", ")", "\n", "if", "!", "names", ".", "IsValidMachine", "(", "cfg", ".", "MachineId", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "DataDir", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "LogDir", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "MetricsSpoolDir", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "cfg", ".", "Jobs", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "JujuVersion", "==", "version", ".", "Zero", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "APIInfo", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "APIInfo", ".", "ModelTag", ".", "Id", "(", ")", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "cfg", ".", "APIInfo", ".", "CACert", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "PodNonce", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "ControllerName", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "cfg", ".", "Controller", "!=", "nil", "{", "if", "err", ":=", "cfg", ".", "verifyControllerConfig", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "if", "cfg", ".", "Bootstrap", "!=", "nil", "{", "if", "err", ":=", "cfg", ".", "verifyBootstrapConfig", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "else", "{", "if", "cfg", ".", "APIInfo", ".", "Tag", "!=", "names", ".", "NewMachineTag", "(", "cfg", ".", "MachineId", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "cfg", ".", "APIInfo", ".", "Addrs", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// VerifyConfig verifies that the ControllerPodConfig is valid.
[ "VerifyConfig", "verifies", "that", "the", "ControllerPodConfig", "is", "valid", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/podcfg/podcfg.go#L151-L205
156,416
juju/juju
cloudconfig/podcfg/podcfg.go
GetHostedModel
func (cfg *ControllerPodConfig) GetHostedModel() (string, bool) { hasHostedModel := len(cfg.Bootstrap.HostedModelConfig) > 0 if hasHostedModel { modelName := cfg.Bootstrap.HostedModelConfig[config.NameKey].(string) logger.Debugf("configured hosted model %q for bootstrapping", modelName) return modelName, true } return "", false }
go
func (cfg *ControllerPodConfig) GetHostedModel() (string, bool) { hasHostedModel := len(cfg.Bootstrap.HostedModelConfig) > 0 if hasHostedModel { modelName := cfg.Bootstrap.HostedModelConfig[config.NameKey].(string) logger.Debugf("configured hosted model %q for bootstrapping", modelName) return modelName, true } return "", false }
[ "func", "(", "cfg", "*", "ControllerPodConfig", ")", "GetHostedModel", "(", ")", "(", "string", ",", "bool", ")", "{", "hasHostedModel", ":=", "len", "(", "cfg", ".", "Bootstrap", ".", "HostedModelConfig", ")", ">", "0", "\n", "if", "hasHostedModel", "{", "modelName", ":=", "cfg", ".", "Bootstrap", ".", "HostedModelConfig", "[", "config", ".", "NameKey", "]", ".", "(", "string", ")", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "modelName", ")", "\n", "return", "modelName", ",", "true", "\n", "}", "\n", "return", "\"", "\"", ",", "false", "\n", "}" ]
// GetHostedModel checks if hosted model was requested to create.
[ "GetHostedModel", "checks", "if", "hosted", "model", "was", "requested", "to", "create", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/podcfg/podcfg.go#L253-L261
156,417
juju/juju
cloudconfig/podcfg/podcfg.go
VerifyConfig
func (cfg *ControllerConfig) VerifyConfig() error { if cfg.MongoInfo == nil { return errors.New("missing state info") } if len(cfg.MongoInfo.CACert) == 0 { return errors.New("missing CA certificate") } return nil }
go
func (cfg *ControllerConfig) VerifyConfig() error { if cfg.MongoInfo == nil { return errors.New("missing state info") } if len(cfg.MongoInfo.CACert) == 0 { return errors.New("missing CA certificate") } return nil }
[ "func", "(", "cfg", "*", "ControllerConfig", ")", "VerifyConfig", "(", ")", "error", "{", "if", "cfg", ".", "MongoInfo", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "cfg", ".", "MongoInfo", ".", "CACert", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// VerifyConfig verifies that the ControllerConfig is valid.
[ "VerifyConfig", "verifies", "that", "the", "ControllerConfig", "is", "valid", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/podcfg/podcfg.go#L287-L295
156,418
juju/juju
cloudconfig/podcfg/podcfg.go
NewControllerPodConfig
func NewControllerPodConfig( controllerTag names.ControllerTag, podID, podNonce, controllerName, series string, apiInfo *api.Info, ) (*ControllerPodConfig, error) { dataDir, err := paths.DataDir(series) if err != nil { return nil, err } logDir, err := paths.LogDir(series) if err != nil { return nil, err } metricsSpoolDir, err := paths.MetricsSpoolDir(series) if err != nil { return nil, err } pcfg := &ControllerPodConfig{ // Fixed entries. DataDir: dataDir, LogDir: path.Join(logDir, "juju"), MetricsSpoolDir: metricsSpoolDir, Tags: map[string]string{}, // Parameter entries. ControllerTag: controllerTag, MachineId: podID, PodNonce: podNonce, ControllerName: controllerName, APIInfo: apiInfo, } return pcfg, nil }
go
func NewControllerPodConfig( controllerTag names.ControllerTag, podID, podNonce, controllerName, series string, apiInfo *api.Info, ) (*ControllerPodConfig, error) { dataDir, err := paths.DataDir(series) if err != nil { return nil, err } logDir, err := paths.LogDir(series) if err != nil { return nil, err } metricsSpoolDir, err := paths.MetricsSpoolDir(series) if err != nil { return nil, err } pcfg := &ControllerPodConfig{ // Fixed entries. DataDir: dataDir, LogDir: path.Join(logDir, "juju"), MetricsSpoolDir: metricsSpoolDir, Tags: map[string]string{}, // Parameter entries. ControllerTag: controllerTag, MachineId: podID, PodNonce: podNonce, ControllerName: controllerName, APIInfo: apiInfo, } return pcfg, nil }
[ "func", "NewControllerPodConfig", "(", "controllerTag", "names", ".", "ControllerTag", ",", "podID", ",", "podNonce", ",", "controllerName", ",", "series", "string", ",", "apiInfo", "*", "api", ".", "Info", ",", ")", "(", "*", "ControllerPodConfig", ",", "error", ")", "{", "dataDir", ",", "err", ":=", "paths", ".", "DataDir", "(", "series", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "logDir", ",", "err", ":=", "paths", ".", "LogDir", "(", "series", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "metricsSpoolDir", ",", "err", ":=", "paths", ".", "MetricsSpoolDir", "(", "series", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "pcfg", ":=", "&", "ControllerPodConfig", "{", "// Fixed entries.", "DataDir", ":", "dataDir", ",", "LogDir", ":", "path", ".", "Join", "(", "logDir", ",", "\"", "\"", ")", ",", "MetricsSpoolDir", ":", "metricsSpoolDir", ",", "Tags", ":", "map", "[", "string", "]", "string", "{", "}", ",", "// Parameter entries.", "ControllerTag", ":", "controllerTag", ",", "MachineId", ":", "podID", ",", "PodNonce", ":", "podNonce", ",", "ControllerName", ":", "controllerName", ",", "APIInfo", ":", "apiInfo", ",", "}", "\n", "return", "pcfg", ",", "nil", "\n", "}" ]
// NewControllerPodConfig sets up a basic pod configuration. You'll still need to supply more information, // but this takes care of the fixed entries and the ones that are // always needed.
[ "NewControllerPodConfig", "sets", "up", "a", "basic", "pod", "configuration", ".", "You", "ll", "still", "need", "to", "supply", "more", "information", "but", "this", "takes", "care", "of", "the", "fixed", "entries", "and", "the", "ones", "that", "are", "always", "needed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/podcfg/podcfg.go#L300-L334
156,419
juju/juju
cloudconfig/podcfg/podcfg.go
NewBootstrapControllerPodConfig
func NewBootstrapControllerPodConfig( config controller.Config, controllerName, series string, ) (*ControllerPodConfig, error) { // For a bootstrap pod, the caller must provide the state.Info // and the api.Info. The machine id must *always* be "0". pcfg, err := NewControllerPodConfig( names.NewControllerTag(config.ControllerUUID()), "0", agent.BootstrapNonce, controllerName, series, nil, ) if err != nil { return nil, err } pcfg.Controller = &ControllerConfig{} pcfg.Controller.Config = make(map[string]interface{}) for k, v := range config { pcfg.Controller.Config[k] = v } // TODO(bootstrap): remove me. arch := arch.AMD64 var cores uint64 = 2 var mem uint64 = 123 var rootDisk uint64 = 123 pcfg.Bootstrap = &BootstrapConfig{ BootstrapConfig: instancecfg.BootstrapConfig{ StateInitializationParams: instancecfg.StateInitializationParams{ // TODO(bootstrap): remove me once agentbootstrap.initBootstrapMachine works for CAAS bootstrap in jujud. BootstrapMachineHardwareCharacteristics: &instance.HardwareCharacteristics{ Arch: &arch, CpuCores: &cores, Mem: &mem, RootDisk: &rootDisk, }, BootstrapMachineInstanceId: "i-0a373a526fcf5c882", BootstrapMachineConstraints: constraints.Value{Mem: &mem}, }, }, } pcfg.Jobs = []multiwatcher.MachineJob{ multiwatcher.JobManageModel, multiwatcher.JobHostUnits, } return pcfg, nil }
go
func NewBootstrapControllerPodConfig( config controller.Config, controllerName, series string, ) (*ControllerPodConfig, error) { // For a bootstrap pod, the caller must provide the state.Info // and the api.Info. The machine id must *always* be "0". pcfg, err := NewControllerPodConfig( names.NewControllerTag(config.ControllerUUID()), "0", agent.BootstrapNonce, controllerName, series, nil, ) if err != nil { return nil, err } pcfg.Controller = &ControllerConfig{} pcfg.Controller.Config = make(map[string]interface{}) for k, v := range config { pcfg.Controller.Config[k] = v } // TODO(bootstrap): remove me. arch := arch.AMD64 var cores uint64 = 2 var mem uint64 = 123 var rootDisk uint64 = 123 pcfg.Bootstrap = &BootstrapConfig{ BootstrapConfig: instancecfg.BootstrapConfig{ StateInitializationParams: instancecfg.StateInitializationParams{ // TODO(bootstrap): remove me once agentbootstrap.initBootstrapMachine works for CAAS bootstrap in jujud. BootstrapMachineHardwareCharacteristics: &instance.HardwareCharacteristics{ Arch: &arch, CpuCores: &cores, Mem: &mem, RootDisk: &rootDisk, }, BootstrapMachineInstanceId: "i-0a373a526fcf5c882", BootstrapMachineConstraints: constraints.Value{Mem: &mem}, }, }, } pcfg.Jobs = []multiwatcher.MachineJob{ multiwatcher.JobManageModel, multiwatcher.JobHostUnits, } return pcfg, nil }
[ "func", "NewBootstrapControllerPodConfig", "(", "config", "controller", ".", "Config", ",", "controllerName", ",", "series", "string", ",", ")", "(", "*", "ControllerPodConfig", ",", "error", ")", "{", "// For a bootstrap pod, the caller must provide the state.Info", "// and the api.Info. The machine id must *always* be \"0\".", "pcfg", ",", "err", ":=", "NewControllerPodConfig", "(", "names", ".", "NewControllerTag", "(", "config", ".", "ControllerUUID", "(", ")", ")", ",", "\"", "\"", ",", "agent", ".", "BootstrapNonce", ",", "controllerName", ",", "series", ",", "nil", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "pcfg", ".", "Controller", "=", "&", "ControllerConfig", "{", "}", "\n", "pcfg", ".", "Controller", ".", "Config", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "for", "k", ",", "v", ":=", "range", "config", "{", "pcfg", ".", "Controller", ".", "Config", "[", "k", "]", "=", "v", "\n", "}", "\n", "// TODO(bootstrap): remove me.", "arch", ":=", "arch", ".", "AMD64", "\n", "var", "cores", "uint64", "=", "2", "\n", "var", "mem", "uint64", "=", "123", "\n", "var", "rootDisk", "uint64", "=", "123", "\n", "pcfg", ".", "Bootstrap", "=", "&", "BootstrapConfig", "{", "BootstrapConfig", ":", "instancecfg", ".", "BootstrapConfig", "{", "StateInitializationParams", ":", "instancecfg", ".", "StateInitializationParams", "{", "// TODO(bootstrap): remove me once agentbootstrap.initBootstrapMachine works for CAAS bootstrap in jujud.", "BootstrapMachineHardwareCharacteristics", ":", "&", "instance", ".", "HardwareCharacteristics", "{", "Arch", ":", "&", "arch", ",", "CpuCores", ":", "&", "cores", ",", "Mem", ":", "&", "mem", ",", "RootDisk", ":", "&", "rootDisk", ",", "}", ",", "BootstrapMachineInstanceId", ":", "\"", "\"", ",", "BootstrapMachineConstraints", ":", "constraints", ".", "Value", "{", "Mem", ":", "&", "mem", "}", ",", "}", ",", "}", ",", "}", "\n\n", "pcfg", ".", "Jobs", "=", "[", "]", "multiwatcher", ".", "MachineJob", "{", "multiwatcher", ".", "JobManageModel", ",", "multiwatcher", ".", "JobHostUnits", ",", "}", "\n", "return", "pcfg", ",", "nil", "\n", "}" ]
// NewBootstrapControllerPodConfig sets up a basic pod configuration for a // bootstrap pod. You'll still need to supply more information, but this // takes care of the fixed entries and the ones that are always needed.
[ "NewBootstrapControllerPodConfig", "sets", "up", "a", "basic", "pod", "configuration", "for", "a", "bootstrap", "pod", ".", "You", "ll", "still", "need", "to", "supply", "more", "information", "but", "this", "takes", "care", "of", "the", "fixed", "entries", "and", "the", "ones", "that", "are", "always", "needed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/podcfg/podcfg.go#L339-L383
156,420
juju/juju
cloudconfig/podcfg/podcfg.go
PopulateControllerPodConfig
func PopulateControllerPodConfig(pcfg *ControllerPodConfig, providerType string) error { if pcfg.AgentEnvironment == nil { pcfg.AgentEnvironment = make(map[string]string) } pcfg.AgentEnvironment[agent.ProviderType] = providerType pcfg.AgentEnvironment[agent.AgentServiceName] = "jujud-" + names.NewMachineTag(pcfg.MachineId).String() return nil }
go
func PopulateControllerPodConfig(pcfg *ControllerPodConfig, providerType string) error { if pcfg.AgentEnvironment == nil { pcfg.AgentEnvironment = make(map[string]string) } pcfg.AgentEnvironment[agent.ProviderType] = providerType pcfg.AgentEnvironment[agent.AgentServiceName] = "jujud-" + names.NewMachineTag(pcfg.MachineId).String() return nil }
[ "func", "PopulateControllerPodConfig", "(", "pcfg", "*", "ControllerPodConfig", ",", "providerType", "string", ")", "error", "{", "if", "pcfg", ".", "AgentEnvironment", "==", "nil", "{", "pcfg", ".", "AgentEnvironment", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "}", "\n", "pcfg", ".", "AgentEnvironment", "[", "agent", ".", "ProviderType", "]", "=", "providerType", "\n", "pcfg", ".", "AgentEnvironment", "[", "agent", ".", "AgentServiceName", "]", "=", "\"", "\"", "+", "names", ".", "NewMachineTag", "(", "pcfg", ".", "MachineId", ")", ".", "String", "(", ")", "\n", "return", "nil", "\n", "}" ]
// PopulateControllerPodConfig is called both from the FinishControllerPodConfig below, // which does have access to the environment config, and from the container // provisioners, which don't have access to the environment config. Everything // that is needed to provision a container needs to be returned to the // provisioner in the ContainerConfig structure. Those values are then used to // call this function.
[ "PopulateControllerPodConfig", "is", "called", "both", "from", "the", "FinishControllerPodConfig", "below", "which", "does", "have", "access", "to", "the", "environment", "config", "and", "from", "the", "container", "provisioners", "which", "don", "t", "have", "access", "to", "the", "environment", "config", ".", "Everything", "that", "is", "needed", "to", "provision", "a", "container", "needs", "to", "be", "returned", "to", "the", "provisioner", "in", "the", "ContainerConfig", "structure", ".", "Those", "values", "are", "then", "used", "to", "call", "this", "function", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/podcfg/podcfg.go#L391-L398
156,421
juju/juju
cloudconfig/podcfg/podcfg.go
PodLabels
func PodLabels(modelUUID, controllerUUID string, tagger tags.ResourceTagger, jobs []multiwatcher.MachineJob) map[string]string { podLabels := tags.ResourceTags( names.NewModelTag(modelUUID), names.NewControllerTag(controllerUUID), tagger, ) // always be a controller. podLabels[tags.JujuIsController] = "true" return podLabels }
go
func PodLabels(modelUUID, controllerUUID string, tagger tags.ResourceTagger, jobs []multiwatcher.MachineJob) map[string]string { podLabels := tags.ResourceTags( names.NewModelTag(modelUUID), names.NewControllerTag(controllerUUID), tagger, ) // always be a controller. podLabels[tags.JujuIsController] = "true" return podLabels }
[ "func", "PodLabels", "(", "modelUUID", ",", "controllerUUID", "string", ",", "tagger", "tags", ".", "ResourceTagger", ",", "jobs", "[", "]", "multiwatcher", ".", "MachineJob", ")", "map", "[", "string", "]", "string", "{", "podLabels", ":=", "tags", ".", "ResourceTags", "(", "names", ".", "NewModelTag", "(", "modelUUID", ")", ",", "names", ".", "NewControllerTag", "(", "controllerUUID", ")", ",", "tagger", ",", ")", "\n", "// always be a controller.", "podLabels", "[", "tags", ".", "JujuIsController", "]", "=", "\"", "\"", "\n", "return", "podLabels", "\n", "}" ]
// PodLabels returns the minimum set of tags that should be set on a // pod, if the provider supports them.
[ "PodLabels", "returns", "the", "minimum", "set", "of", "tags", "that", "should", "be", "set", "on", "a", "pod", "if", "the", "provider", "supports", "them", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cloudconfig/podcfg/podcfg.go#L416-L425
156,422
juju/juju
worker/resumer/shim.go
NewFacade
func NewFacade(apiCaller base.APICaller) (Facade, error) { return resumer.NewAPI(apiCaller), nil }
go
func NewFacade(apiCaller base.APICaller) (Facade, error) { return resumer.NewAPI(apiCaller), nil }
[ "func", "NewFacade", "(", "apiCaller", "base", ".", "APICaller", ")", "(", "Facade", ",", "error", ")", "{", "return", "resumer", ".", "NewAPI", "(", "apiCaller", ")", ",", "nil", "\n", "}" ]
// NewFacade returns a useful live implementation for // ManifoldConfig.NewFacade.
[ "NewFacade", "returns", "a", "useful", "live", "implementation", "for", "ManifoldConfig", ".", "NewFacade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/resumer/shim.go#L16-L18
156,423
juju/juju
worker/firewaller/firewaller.go
Validate
func (cfg Config) Validate() error { if cfg.ModelUUID == "" { return errors.NotValidf("empty model uuid") } if cfg.FirewallerAPI == nil { return errors.NotValidf("nil Firewaller Facade") } if cfg.RemoteRelationsApi == nil { return errors.NotValidf("nil RemoteRelations Facade") } if cfg.Mode == config.FwGlobal && cfg.EnvironFirewaller == nil { return errors.NotValidf("nil EnvironFirewaller") } if cfg.EnvironInstances == nil { return errors.NotValidf("nil EnvironInstances") } if cfg.NewCrossModelFacadeFunc == nil { return errors.NotValidf("nil Cross Model Facade func") } if cfg.CredentialAPI == nil { return errors.NotValidf("nil Credential Facade") } return nil }
go
func (cfg Config) Validate() error { if cfg.ModelUUID == "" { return errors.NotValidf("empty model uuid") } if cfg.FirewallerAPI == nil { return errors.NotValidf("nil Firewaller Facade") } if cfg.RemoteRelationsApi == nil { return errors.NotValidf("nil RemoteRelations Facade") } if cfg.Mode == config.FwGlobal && cfg.EnvironFirewaller == nil { return errors.NotValidf("nil EnvironFirewaller") } if cfg.EnvironInstances == nil { return errors.NotValidf("nil EnvironInstances") } if cfg.NewCrossModelFacadeFunc == nil { return errors.NotValidf("nil Cross Model Facade func") } if cfg.CredentialAPI == nil { return errors.NotValidf("nil Credential Facade") } return nil }
[ "func", "(", "cfg", "Config", ")", "Validate", "(", ")", "error", "{", "if", "cfg", ".", "ModelUUID", "==", "\"", "\"", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "FirewallerAPI", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "RemoteRelationsApi", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "Mode", "==", "config", ".", "FwGlobal", "&&", "cfg", ".", "EnvironFirewaller", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "EnvironInstances", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "NewCrossModelFacadeFunc", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "CredentialAPI", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate returns an error if cfg cannot drive a Worker.
[ "Validate", "returns", "an", "error", "if", "cfg", "cannot", "drive", "a", "Worker", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L97-L120
156,424
juju/juju
worker/firewaller/firewaller.go
NewFirewaller
func NewFirewaller(cfg Config) (worker.Worker, error) { if err := cfg.Validate(); err != nil { return nil, errors.Trace(err) } clk := cfg.Clock if clk == nil { clk = clock.WallClock } fw := &Firewaller{ firewallerApi: cfg.FirewallerAPI, remoteRelationsApi: cfg.RemoteRelationsApi, environFirewaller: cfg.EnvironFirewaller, environInstances: cfg.EnvironInstances, newRemoteFirewallerAPIFunc: cfg.NewCrossModelFacadeFunc, modelUUID: cfg.ModelUUID, machineds: make(map[names.MachineTag]*machineData), unitsChange: make(chan *unitsChange), unitds: make(map[names.UnitTag]*unitData), applicationids: make(map[names.ApplicationTag]*applicationData), exposedChange: make(chan *exposedChange), relationIngress: make(map[names.RelationTag]*remoteRelationData), localRelationsChange: make(chan *remoteRelationNetworkChange), pollClock: clk, relationWorkerRunner: worker.NewRunner(worker.RunnerParams{ Clock: clk, // One of the remote relation workers failing should not // prevent the others from running. IsFatal: func(error) bool { return false }, // For any failures, try again in 1 minute. RestartDelay: time.Minute, }), cloudCallContext: common.NewCloudCallContext(cfg.CredentialAPI, nil), } switch cfg.Mode { case config.FwInstance: case config.FwGlobal: fw.globalMode = true fw.globalIngressRuleRef = make(map[string]int) default: return nil, errors.Errorf("invalid firewall-mode %q", cfg.Mode) } err := catacomb.Invoke(catacomb.Plan{ Site: &fw.catacomb, Work: fw.loop, Init: []worker.Worker{fw.relationWorkerRunner}, }) if err != nil { return nil, errors.Trace(err) } return fw, nil }
go
func NewFirewaller(cfg Config) (worker.Worker, error) { if err := cfg.Validate(); err != nil { return nil, errors.Trace(err) } clk := cfg.Clock if clk == nil { clk = clock.WallClock } fw := &Firewaller{ firewallerApi: cfg.FirewallerAPI, remoteRelationsApi: cfg.RemoteRelationsApi, environFirewaller: cfg.EnvironFirewaller, environInstances: cfg.EnvironInstances, newRemoteFirewallerAPIFunc: cfg.NewCrossModelFacadeFunc, modelUUID: cfg.ModelUUID, machineds: make(map[names.MachineTag]*machineData), unitsChange: make(chan *unitsChange), unitds: make(map[names.UnitTag]*unitData), applicationids: make(map[names.ApplicationTag]*applicationData), exposedChange: make(chan *exposedChange), relationIngress: make(map[names.RelationTag]*remoteRelationData), localRelationsChange: make(chan *remoteRelationNetworkChange), pollClock: clk, relationWorkerRunner: worker.NewRunner(worker.RunnerParams{ Clock: clk, // One of the remote relation workers failing should not // prevent the others from running. IsFatal: func(error) bool { return false }, // For any failures, try again in 1 minute. RestartDelay: time.Minute, }), cloudCallContext: common.NewCloudCallContext(cfg.CredentialAPI, nil), } switch cfg.Mode { case config.FwInstance: case config.FwGlobal: fw.globalMode = true fw.globalIngressRuleRef = make(map[string]int) default: return nil, errors.Errorf("invalid firewall-mode %q", cfg.Mode) } err := catacomb.Invoke(catacomb.Plan{ Site: &fw.catacomb, Work: fw.loop, Init: []worker.Worker{fw.relationWorkerRunner}, }) if err != nil { return nil, errors.Trace(err) } return fw, nil }
[ "func", "NewFirewaller", "(", "cfg", "Config", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "if", "err", ":=", "cfg", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "clk", ":=", "cfg", ".", "Clock", "\n", "if", "clk", "==", "nil", "{", "clk", "=", "clock", ".", "WallClock", "\n", "}", "\n\n", "fw", ":=", "&", "Firewaller", "{", "firewallerApi", ":", "cfg", ".", "FirewallerAPI", ",", "remoteRelationsApi", ":", "cfg", ".", "RemoteRelationsApi", ",", "environFirewaller", ":", "cfg", ".", "EnvironFirewaller", ",", "environInstances", ":", "cfg", ".", "EnvironInstances", ",", "newRemoteFirewallerAPIFunc", ":", "cfg", ".", "NewCrossModelFacadeFunc", ",", "modelUUID", ":", "cfg", ".", "ModelUUID", ",", "machineds", ":", "make", "(", "map", "[", "names", ".", "MachineTag", "]", "*", "machineData", ")", ",", "unitsChange", ":", "make", "(", "chan", "*", "unitsChange", ")", ",", "unitds", ":", "make", "(", "map", "[", "names", ".", "UnitTag", "]", "*", "unitData", ")", ",", "applicationids", ":", "make", "(", "map", "[", "names", ".", "ApplicationTag", "]", "*", "applicationData", ")", ",", "exposedChange", ":", "make", "(", "chan", "*", "exposedChange", ")", ",", "relationIngress", ":", "make", "(", "map", "[", "names", ".", "RelationTag", "]", "*", "remoteRelationData", ")", ",", "localRelationsChange", ":", "make", "(", "chan", "*", "remoteRelationNetworkChange", ")", ",", "pollClock", ":", "clk", ",", "relationWorkerRunner", ":", "worker", ".", "NewRunner", "(", "worker", ".", "RunnerParams", "{", "Clock", ":", "clk", ",", "// One of the remote relation workers failing should not", "// prevent the others from running.", "IsFatal", ":", "func", "(", "error", ")", "bool", "{", "return", "false", "}", ",", "// For any failures, try again in 1 minute.", "RestartDelay", ":", "time", ".", "Minute", ",", "}", ")", ",", "cloudCallContext", ":", "common", ".", "NewCloudCallContext", "(", "cfg", ".", "CredentialAPI", ",", "nil", ")", ",", "}", "\n\n", "switch", "cfg", ".", "Mode", "{", "case", "config", ".", "FwInstance", ":", "case", "config", ".", "FwGlobal", ":", "fw", ".", "globalMode", "=", "true", "\n", "fw", ".", "globalIngressRuleRef", "=", "make", "(", "map", "[", "string", "]", "int", ")", "\n", "default", ":", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "cfg", ".", "Mode", ")", "\n", "}", "\n\n", "err", ":=", "catacomb", ".", "Invoke", "(", "catacomb", ".", "Plan", "{", "Site", ":", "&", "fw", ".", "catacomb", ",", "Work", ":", "fw", ".", "loop", ",", "Init", ":", "[", "]", "worker", ".", "Worker", "{", "fw", ".", "relationWorkerRunner", "}", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "fw", ",", "nil", "\n", "}" ]
// NewFirewaller returns a new Firewaller.
[ "NewFirewaller", "returns", "a", "new", "Firewaller", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L156-L211
156,425
juju/juju
worker/firewaller/firewaller.go
startMachine
func (fw *Firewaller) startMachine(tag names.MachineTag) error { machined := &machineData{ fw: fw, tag: tag, unitds: make(map[names.UnitTag]*unitData), ingressRules: make([]network.IngressRule, 0), definedPorts: make(map[names.UnitTag]portRanges), } m, err := machined.machine() if params.IsCodeNotFound(err) { logger.Debugf("not watching %q", tag) return nil } else if err != nil { return errors.Annotate(err, "cannot watch machine units") } manual, err := m.IsManual() if err != nil { return errors.Trace(err) } if manual { // Don't track manual machines, we can't change their ports. logger.Debugf("not watching manual %q", tag) return nil } unitw, err := m.WatchUnits() if err != nil { return errors.Trace(err) } // XXX(fwereade): this is the best of a bunch of bad options. We've started // the watch, so we're responsible for it; but we (probably?) need to do this // little dance below to update the machined data on the fw loop goroutine, // whence it's usually accessed, before we start the machined watchLoop // below. That catacomb *should* be the only one responsible -- and it *is* // responsible -- but having it in the main fw catacomb as well does no harm, // and greatly simplifies the code below (which would otherwise have to // manage unitw lifetime and errors manually). if err := fw.catacomb.Add(unitw); err != nil { return errors.Trace(err) } select { case <-fw.catacomb.Dying(): return fw.catacomb.ErrDying() case change, ok := <-unitw.Changes(): if !ok { return errors.New("machine units watcher closed") } fw.machineds[tag] = machined err = fw.unitsChanged(&unitsChange{machined, change}) if err != nil { delete(fw.machineds, tag) return errors.Annotatef(err, "cannot respond to units changes for %q", tag) } } err = catacomb.Invoke(catacomb.Plan{ Site: &machined.catacomb, Work: func() error { return machined.watchLoop(unitw) }, }) if err != nil { delete(fw.machineds, tag) return errors.Trace(err) } // register the machined with the firewaller's catacomb. err = fw.catacomb.Add(machined) if err == nil { logger.Debugf("started watching %q", tag) } return err }
go
func (fw *Firewaller) startMachine(tag names.MachineTag) error { machined := &machineData{ fw: fw, tag: tag, unitds: make(map[names.UnitTag]*unitData), ingressRules: make([]network.IngressRule, 0), definedPorts: make(map[names.UnitTag]portRanges), } m, err := machined.machine() if params.IsCodeNotFound(err) { logger.Debugf("not watching %q", tag) return nil } else if err != nil { return errors.Annotate(err, "cannot watch machine units") } manual, err := m.IsManual() if err != nil { return errors.Trace(err) } if manual { // Don't track manual machines, we can't change their ports. logger.Debugf("not watching manual %q", tag) return nil } unitw, err := m.WatchUnits() if err != nil { return errors.Trace(err) } // XXX(fwereade): this is the best of a bunch of bad options. We've started // the watch, so we're responsible for it; but we (probably?) need to do this // little dance below to update the machined data on the fw loop goroutine, // whence it's usually accessed, before we start the machined watchLoop // below. That catacomb *should* be the only one responsible -- and it *is* // responsible -- but having it in the main fw catacomb as well does no harm, // and greatly simplifies the code below (which would otherwise have to // manage unitw lifetime and errors manually). if err := fw.catacomb.Add(unitw); err != nil { return errors.Trace(err) } select { case <-fw.catacomb.Dying(): return fw.catacomb.ErrDying() case change, ok := <-unitw.Changes(): if !ok { return errors.New("machine units watcher closed") } fw.machineds[tag] = machined err = fw.unitsChanged(&unitsChange{machined, change}) if err != nil { delete(fw.machineds, tag) return errors.Annotatef(err, "cannot respond to units changes for %q", tag) } } err = catacomb.Invoke(catacomb.Plan{ Site: &machined.catacomb, Work: func() error { return machined.watchLoop(unitw) }, }) if err != nil { delete(fw.machineds, tag) return errors.Trace(err) } // register the machined with the firewaller's catacomb. err = fw.catacomb.Add(machined) if err == nil { logger.Debugf("started watching %q", tag) } return err }
[ "func", "(", "fw", "*", "Firewaller", ")", "startMachine", "(", "tag", "names", ".", "MachineTag", ")", "error", "{", "machined", ":=", "&", "machineData", "{", "fw", ":", "fw", ",", "tag", ":", "tag", ",", "unitds", ":", "make", "(", "map", "[", "names", ".", "UnitTag", "]", "*", "unitData", ")", ",", "ingressRules", ":", "make", "(", "[", "]", "network", ".", "IngressRule", ",", "0", ")", ",", "definedPorts", ":", "make", "(", "map", "[", "names", ".", "UnitTag", "]", "portRanges", ")", ",", "}", "\n", "m", ",", "err", ":=", "machined", ".", "machine", "(", ")", "\n", "if", "params", ".", "IsCodeNotFound", "(", "err", ")", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "tag", ")", "\n", "return", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "manual", ",", "err", ":=", "m", ".", "IsManual", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "manual", "{", "// Don't track manual machines, we can't change their ports.", "logger", ".", "Debugf", "(", "\"", "\"", ",", "tag", ")", "\n", "return", "nil", "\n", "}", "\n", "unitw", ",", "err", ":=", "m", ".", "WatchUnits", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "// XXX(fwereade): this is the best of a bunch of bad options. We've started", "// the watch, so we're responsible for it; but we (probably?) need to do this", "// little dance below to update the machined data on the fw loop goroutine,", "// whence it's usually accessed, before we start the machined watchLoop", "// below. That catacomb *should* be the only one responsible -- and it *is*", "// responsible -- but having it in the main fw catacomb as well does no harm,", "// and greatly simplifies the code below (which would otherwise have to", "// manage unitw lifetime and errors manually).", "if", "err", ":=", "fw", ".", "catacomb", ".", "Add", "(", "unitw", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "select", "{", "case", "<-", "fw", ".", "catacomb", ".", "Dying", "(", ")", ":", "return", "fw", ".", "catacomb", ".", "ErrDying", "(", ")", "\n", "case", "change", ",", "ok", ":=", "<-", "unitw", ".", "Changes", "(", ")", ":", "if", "!", "ok", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "fw", ".", "machineds", "[", "tag", "]", "=", "machined", "\n", "err", "=", "fw", ".", "unitsChanged", "(", "&", "unitsChange", "{", "machined", ",", "change", "}", ")", "\n", "if", "err", "!=", "nil", "{", "delete", "(", "fw", ".", "machineds", ",", "tag", ")", "\n", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "tag", ")", "\n", "}", "\n", "}", "\n\n", "err", "=", "catacomb", ".", "Invoke", "(", "catacomb", ".", "Plan", "{", "Site", ":", "&", "machined", ".", "catacomb", ",", "Work", ":", "func", "(", ")", "error", "{", "return", "machined", ".", "watchLoop", "(", "unitw", ")", "\n", "}", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "delete", "(", "fw", ".", "machineds", ",", "tag", ")", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// register the machined with the firewaller's catacomb.", "err", "=", "fw", ".", "catacomb", ".", "Add", "(", "machined", ")", "\n", "if", "err", "==", "nil", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "tag", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// startMachine creates a new data value for tracking details of the // machine and starts watching the machine for units added or removed.
[ "startMachine", "creates", "a", "new", "data", "value", "for", "tracking", "details", "of", "the", "machine", "and", "starts", "watching", "the", "machine", "for", "units", "added", "or", "removed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L344-L415
156,426
juju/juju
worker/firewaller/firewaller.go
startUnit
func (fw *Firewaller) startUnit(unit *firewaller.Unit, machineTag names.MachineTag) error { application, err := unit.Application() if err != nil { return err } applicationTag := application.Tag() unitTag := unit.Tag() if err != nil { return err } unitd := &unitData{ fw: fw, unit: unit, tag: unitTag, } fw.unitds[unitTag] = unitd unitd.machined = fw.machineds[machineTag] unitd.machined.unitds[unitTag] = unitd if fw.applicationids[applicationTag] == nil { err := fw.startApplication(application) if err != nil { delete(fw.unitds, unitTag) delete(unitd.machined.unitds, unitTag) return err } } unitd.applicationd = fw.applicationids[applicationTag] unitd.applicationd.unitds[unitTag] = unitd m, err := unitd.machined.machine() if err != nil { return err } // check if the machine has ports open on any subnets subnetTags, err := m.ActiveSubnets() if err != nil { return errors.Annotatef(err, "failed getting %q active subnets", machineTag) } for _, subnetTag := range subnetTags { err := fw.openedPortsChanged(machineTag, subnetTag) if err != nil { return err } } return nil }
go
func (fw *Firewaller) startUnit(unit *firewaller.Unit, machineTag names.MachineTag) error { application, err := unit.Application() if err != nil { return err } applicationTag := application.Tag() unitTag := unit.Tag() if err != nil { return err } unitd := &unitData{ fw: fw, unit: unit, tag: unitTag, } fw.unitds[unitTag] = unitd unitd.machined = fw.machineds[machineTag] unitd.machined.unitds[unitTag] = unitd if fw.applicationids[applicationTag] == nil { err := fw.startApplication(application) if err != nil { delete(fw.unitds, unitTag) delete(unitd.machined.unitds, unitTag) return err } } unitd.applicationd = fw.applicationids[applicationTag] unitd.applicationd.unitds[unitTag] = unitd m, err := unitd.machined.machine() if err != nil { return err } // check if the machine has ports open on any subnets subnetTags, err := m.ActiveSubnets() if err != nil { return errors.Annotatef(err, "failed getting %q active subnets", machineTag) } for _, subnetTag := range subnetTags { err := fw.openedPortsChanged(machineTag, subnetTag) if err != nil { return err } } return nil }
[ "func", "(", "fw", "*", "Firewaller", ")", "startUnit", "(", "unit", "*", "firewaller", ".", "Unit", ",", "machineTag", "names", ".", "MachineTag", ")", "error", "{", "application", ",", "err", ":=", "unit", ".", "Application", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "applicationTag", ":=", "application", ".", "Tag", "(", ")", "\n", "unitTag", ":=", "unit", ".", "Tag", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "unitd", ":=", "&", "unitData", "{", "fw", ":", "fw", ",", "unit", ":", "unit", ",", "tag", ":", "unitTag", ",", "}", "\n", "fw", ".", "unitds", "[", "unitTag", "]", "=", "unitd", "\n\n", "unitd", ".", "machined", "=", "fw", ".", "machineds", "[", "machineTag", "]", "\n", "unitd", ".", "machined", ".", "unitds", "[", "unitTag", "]", "=", "unitd", "\n", "if", "fw", ".", "applicationids", "[", "applicationTag", "]", "==", "nil", "{", "err", ":=", "fw", ".", "startApplication", "(", "application", ")", "\n", "if", "err", "!=", "nil", "{", "delete", "(", "fw", ".", "unitds", ",", "unitTag", ")", "\n", "delete", "(", "unitd", ".", "machined", ".", "unitds", ",", "unitTag", ")", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "unitd", ".", "applicationd", "=", "fw", ".", "applicationids", "[", "applicationTag", "]", "\n", "unitd", ".", "applicationd", ".", "unitds", "[", "unitTag", "]", "=", "unitd", "\n\n", "m", ",", "err", ":=", "unitd", ".", "machined", ".", "machine", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// check if the machine has ports open on any subnets", "subnetTags", ",", "err", ":=", "m", ".", "ActiveSubnets", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "machineTag", ")", "\n", "}", "\n", "for", "_", ",", "subnetTag", ":=", "range", "subnetTags", "{", "err", ":=", "fw", ".", "openedPortsChanged", "(", "machineTag", ",", "subnetTag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// startUnit creates a new data value for tracking details of the unit // The provided machineTag must be the tag for the machine the unit was last // observed to be assigned to.
[ "startUnit", "creates", "a", "new", "data", "value", "for", "tracking", "details", "of", "the", "unit", "The", "provided", "machineTag", "must", "be", "the", "tag", "for", "the", "machine", "the", "unit", "was", "last", "observed", "to", "be", "assigned", "to", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L420-L468
156,427
juju/juju
worker/firewaller/firewaller.go
startApplication
func (fw *Firewaller) startApplication(app *firewaller.Application) error { exposed, err := app.IsExposed() if err != nil { return err } applicationd := &applicationData{ fw: fw, application: app, exposed: exposed, unitds: make(map[names.UnitTag]*unitData), } fw.applicationids[app.Tag()] = applicationd err = catacomb.Invoke(catacomb.Plan{ Site: &applicationd.catacomb, Work: func() error { return applicationd.watchLoop(exposed) }, }) if err != nil { return errors.Trace(err) } if err := fw.catacomb.Add(applicationd); err != nil { return errors.Trace(err) } return nil }
go
func (fw *Firewaller) startApplication(app *firewaller.Application) error { exposed, err := app.IsExposed() if err != nil { return err } applicationd := &applicationData{ fw: fw, application: app, exposed: exposed, unitds: make(map[names.UnitTag]*unitData), } fw.applicationids[app.Tag()] = applicationd err = catacomb.Invoke(catacomb.Plan{ Site: &applicationd.catacomb, Work: func() error { return applicationd.watchLoop(exposed) }, }) if err != nil { return errors.Trace(err) } if err := fw.catacomb.Add(applicationd); err != nil { return errors.Trace(err) } return nil }
[ "func", "(", "fw", "*", "Firewaller", ")", "startApplication", "(", "app", "*", "firewaller", ".", "Application", ")", "error", "{", "exposed", ",", "err", ":=", "app", ".", "IsExposed", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "applicationd", ":=", "&", "applicationData", "{", "fw", ":", "fw", ",", "application", ":", "app", ",", "exposed", ":", "exposed", ",", "unitds", ":", "make", "(", "map", "[", "names", ".", "UnitTag", "]", "*", "unitData", ")", ",", "}", "\n", "fw", ".", "applicationids", "[", "app", ".", "Tag", "(", ")", "]", "=", "applicationd", "\n\n", "err", "=", "catacomb", ".", "Invoke", "(", "catacomb", ".", "Plan", "{", "Site", ":", "&", "applicationd", ".", "catacomb", ",", "Work", ":", "func", "(", ")", "error", "{", "return", "applicationd", ".", "watchLoop", "(", "exposed", ")", "\n", "}", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "fw", ".", "catacomb", ".", "Add", "(", "applicationd", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// startApplication creates a new data value for tracking details of the // application and starts watching the application for exposure changes.
[ "startApplication", "creates", "a", "new", "data", "value", "for", "tracking", "details", "of", "the", "application", "and", "starts", "watching", "the", "application", "for", "exposure", "changes", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L472-L498
156,428
juju/juju
worker/firewaller/firewaller.go
reconcileGlobal
func (fw *Firewaller) reconcileGlobal() error { var machines []*machineData for _, machined := range fw.machineds { machines = append(machines, machined) } want, err := fw.gatherIngressRules(machines...) initialPortRanges, err := fw.environFirewaller.IngressRules(fw.cloudCallContext) if err != nil { return err } // Check which ports to open or to close. toOpen, toClose := diffRanges(initialPortRanges, want) if len(toOpen) > 0 { logger.Infof("opening global ports %v", toOpen) if err := fw.environFirewaller.OpenPorts(fw.cloudCallContext, toOpen); err != nil { return err } } if len(toClose) > 0 { logger.Infof("closing global ports %v", toClose) if err := fw.environFirewaller.ClosePorts(fw.cloudCallContext, toClose); err != nil { return err } } return nil }
go
func (fw *Firewaller) reconcileGlobal() error { var machines []*machineData for _, machined := range fw.machineds { machines = append(machines, machined) } want, err := fw.gatherIngressRules(machines...) initialPortRanges, err := fw.environFirewaller.IngressRules(fw.cloudCallContext) if err != nil { return err } // Check which ports to open or to close. toOpen, toClose := diffRanges(initialPortRanges, want) if len(toOpen) > 0 { logger.Infof("opening global ports %v", toOpen) if err := fw.environFirewaller.OpenPorts(fw.cloudCallContext, toOpen); err != nil { return err } } if len(toClose) > 0 { logger.Infof("closing global ports %v", toClose) if err := fw.environFirewaller.ClosePorts(fw.cloudCallContext, toClose); err != nil { return err } } return nil }
[ "func", "(", "fw", "*", "Firewaller", ")", "reconcileGlobal", "(", ")", "error", "{", "var", "machines", "[", "]", "*", "machineData", "\n", "for", "_", ",", "machined", ":=", "range", "fw", ".", "machineds", "{", "machines", "=", "append", "(", "machines", ",", "machined", ")", "\n", "}", "\n", "want", ",", "err", ":=", "fw", ".", "gatherIngressRules", "(", "machines", "...", ")", "\n", "initialPortRanges", ",", "err", ":=", "fw", ".", "environFirewaller", ".", "IngressRules", "(", "fw", ".", "cloudCallContext", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Check which ports to open or to close.", "toOpen", ",", "toClose", ":=", "diffRanges", "(", "initialPortRanges", ",", "want", ")", "\n", "if", "len", "(", "toOpen", ")", ">", "0", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "toOpen", ")", "\n", "if", "err", ":=", "fw", ".", "environFirewaller", ".", "OpenPorts", "(", "fw", ".", "cloudCallContext", ",", "toOpen", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "if", "len", "(", "toClose", ")", ">", "0", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "toClose", ")", "\n", "if", "err", ":=", "fw", ".", "environFirewaller", ".", "ClosePorts", "(", "fw", ".", "cloudCallContext", ",", "toClose", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// reconcileGlobal compares the initially started watcher for machines, // units and applications with the opened and closed ports globally and // opens and closes the appropriate ports for the whole environment.
[ "reconcileGlobal", "compares", "the", "initially", "started", "watcher", "for", "machines", "units", "and", "applications", "with", "the", "opened", "and", "closed", "ports", "globally", "and", "opens", "and", "closes", "the", "appropriate", "ports", "for", "the", "whole", "environment", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L503-L529
156,429
juju/juju
worker/firewaller/firewaller.go
reconcileInstances
func (fw *Firewaller) reconcileInstances() error { for _, machined := range fw.machineds { m, err := machined.machine() if params.IsCodeNotFound(err) { if err := fw.forgetMachine(machined); err != nil { return err } continue } if err != nil { return err } instanceId, err := m.InstanceId() if errors.IsNotProvisioned(err) { logger.Errorf("Machine not yet provisioned: %v", err) continue } if err != nil { return err } envInstances, err := fw.environInstances.Instances(fw.cloudCallContext, []instance.Id{instanceId}) if err == environs.ErrNoInstances { return nil } if err != nil { return err } machineId := machined.tag.Id() fwInstance, ok := envInstances[0].(instances.InstanceFirewaller) if !ok { return nil } initialRules, err := fwInstance.IngressRules(fw.cloudCallContext, machineId) if err != nil { return err } // Check which ports to open or to close. toOpen, toClose := diffRanges(initialRules, machined.ingressRules) if len(toOpen) > 0 { logger.Infof("opening instance port ranges %v for %q", toOpen, machined.tag) if err := fwInstance.OpenPorts(fw.cloudCallContext, machineId, toOpen); err != nil { // TODO(mue) Add local retry logic. return err } } if len(toClose) > 0 { logger.Infof("closing instance port ranges %v for %q", toClose, machined.tag) if err := fwInstance.ClosePorts(fw.cloudCallContext, machineId, toClose); err != nil { // TODO(mue) Add local retry logic. return err } } } return nil }
go
func (fw *Firewaller) reconcileInstances() error { for _, machined := range fw.machineds { m, err := machined.machine() if params.IsCodeNotFound(err) { if err := fw.forgetMachine(machined); err != nil { return err } continue } if err != nil { return err } instanceId, err := m.InstanceId() if errors.IsNotProvisioned(err) { logger.Errorf("Machine not yet provisioned: %v", err) continue } if err != nil { return err } envInstances, err := fw.environInstances.Instances(fw.cloudCallContext, []instance.Id{instanceId}) if err == environs.ErrNoInstances { return nil } if err != nil { return err } machineId := machined.tag.Id() fwInstance, ok := envInstances[0].(instances.InstanceFirewaller) if !ok { return nil } initialRules, err := fwInstance.IngressRules(fw.cloudCallContext, machineId) if err != nil { return err } // Check which ports to open or to close. toOpen, toClose := diffRanges(initialRules, machined.ingressRules) if len(toOpen) > 0 { logger.Infof("opening instance port ranges %v for %q", toOpen, machined.tag) if err := fwInstance.OpenPorts(fw.cloudCallContext, machineId, toOpen); err != nil { // TODO(mue) Add local retry logic. return err } } if len(toClose) > 0 { logger.Infof("closing instance port ranges %v for %q", toClose, machined.tag) if err := fwInstance.ClosePorts(fw.cloudCallContext, machineId, toClose); err != nil { // TODO(mue) Add local retry logic. return err } } } return nil }
[ "func", "(", "fw", "*", "Firewaller", ")", "reconcileInstances", "(", ")", "error", "{", "for", "_", ",", "machined", ":=", "range", "fw", ".", "machineds", "{", "m", ",", "err", ":=", "machined", ".", "machine", "(", ")", "\n", "if", "params", ".", "IsCodeNotFound", "(", "err", ")", "{", "if", "err", ":=", "fw", ".", "forgetMachine", "(", "machined", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "continue", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "instanceId", ",", "err", ":=", "m", ".", "InstanceId", "(", ")", "\n", "if", "errors", ".", "IsNotProvisioned", "(", "err", ")", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "envInstances", ",", "err", ":=", "fw", ".", "environInstances", ".", "Instances", "(", "fw", ".", "cloudCallContext", ",", "[", "]", "instance", ".", "Id", "{", "instanceId", "}", ")", "\n", "if", "err", "==", "environs", ".", "ErrNoInstances", "{", "return", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "machineId", ":=", "machined", ".", "tag", ".", "Id", "(", ")", "\n\n", "fwInstance", ",", "ok", ":=", "envInstances", "[", "0", "]", ".", "(", "instances", ".", "InstanceFirewaller", ")", "\n", "if", "!", "ok", "{", "return", "nil", "\n", "}", "\n\n", "initialRules", ",", "err", ":=", "fwInstance", ".", "IngressRules", "(", "fw", ".", "cloudCallContext", ",", "machineId", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Check which ports to open or to close.", "toOpen", ",", "toClose", ":=", "diffRanges", "(", "initialRules", ",", "machined", ".", "ingressRules", ")", "\n", "if", "len", "(", "toOpen", ")", ">", "0", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "toOpen", ",", "machined", ".", "tag", ")", "\n", "if", "err", ":=", "fwInstance", ".", "OpenPorts", "(", "fw", ".", "cloudCallContext", ",", "machineId", ",", "toOpen", ")", ";", "err", "!=", "nil", "{", "// TODO(mue) Add local retry logic.", "return", "err", "\n", "}", "\n", "}", "\n", "if", "len", "(", "toClose", ")", ">", "0", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "toClose", ",", "machined", ".", "tag", ")", "\n", "if", "err", ":=", "fwInstance", ".", "ClosePorts", "(", "fw", ".", "cloudCallContext", ",", "machineId", ",", "toClose", ")", ";", "err", "!=", "nil", "{", "// TODO(mue) Add local retry logic.", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// reconcileInstances compares the initially started watcher for machines, // units and applications with the opened and closed ports of the instances and // opens and closes the appropriate ports for each instance.
[ "reconcileInstances", "compares", "the", "initially", "started", "watcher", "for", "machines", "units", "and", "applications", "with", "the", "opened", "and", "closed", "ports", "of", "the", "instances", "and", "opens", "and", "closes", "the", "appropriate", "ports", "for", "each", "instance", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L534-L593
156,430
juju/juju
worker/firewaller/firewaller.go
unitsChanged
func (fw *Firewaller) unitsChanged(change *unitsChange) error { changed := []*unitData{} for _, name := range change.units { unitTag := names.NewUnitTag(name) unit, err := fw.firewallerApi.Unit(unitTag) if err != nil && !params.IsCodeNotFound(err) { return err } var machineTag names.MachineTag if unit != nil { machineTag, err = unit.AssignedMachine() if params.IsCodeNotFound(err) { continue } else if err != nil && !params.IsCodeNotAssigned(err) { return err } } if unitd, known := fw.unitds[unitTag]; known { knownMachineTag := fw.unitds[unitTag].machined.tag if unit == nil || unit.Life() == params.Dead || machineTag != knownMachineTag { fw.forgetUnit(unitd) changed = append(changed, unitd) logger.Debugf("stopped watching unit %s", name) } // TODO(dfc) fw.machineds should be map[names.Tag] } else if unit != nil && unit.Life() != params.Dead && fw.machineds[machineTag] != nil { err = fw.startUnit(unit, machineTag) if params.IsCodeNotFound(err) { continue } if err != nil { return err } changed = append(changed, fw.unitds[unitTag]) logger.Debugf("started watching %q", unitTag) } } if err := fw.flushUnits(changed); err != nil { return errors.Annotate(err, "cannot change firewall ports") } return nil }
go
func (fw *Firewaller) unitsChanged(change *unitsChange) error { changed := []*unitData{} for _, name := range change.units { unitTag := names.NewUnitTag(name) unit, err := fw.firewallerApi.Unit(unitTag) if err != nil && !params.IsCodeNotFound(err) { return err } var machineTag names.MachineTag if unit != nil { machineTag, err = unit.AssignedMachine() if params.IsCodeNotFound(err) { continue } else if err != nil && !params.IsCodeNotAssigned(err) { return err } } if unitd, known := fw.unitds[unitTag]; known { knownMachineTag := fw.unitds[unitTag].machined.tag if unit == nil || unit.Life() == params.Dead || machineTag != knownMachineTag { fw.forgetUnit(unitd) changed = append(changed, unitd) logger.Debugf("stopped watching unit %s", name) } // TODO(dfc) fw.machineds should be map[names.Tag] } else if unit != nil && unit.Life() != params.Dead && fw.machineds[machineTag] != nil { err = fw.startUnit(unit, machineTag) if params.IsCodeNotFound(err) { continue } if err != nil { return err } changed = append(changed, fw.unitds[unitTag]) logger.Debugf("started watching %q", unitTag) } } if err := fw.flushUnits(changed); err != nil { return errors.Annotate(err, "cannot change firewall ports") } return nil }
[ "func", "(", "fw", "*", "Firewaller", ")", "unitsChanged", "(", "change", "*", "unitsChange", ")", "error", "{", "changed", ":=", "[", "]", "*", "unitData", "{", "}", "\n", "for", "_", ",", "name", ":=", "range", "change", ".", "units", "{", "unitTag", ":=", "names", ".", "NewUnitTag", "(", "name", ")", "\n", "unit", ",", "err", ":=", "fw", ".", "firewallerApi", ".", "Unit", "(", "unitTag", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "params", ".", "IsCodeNotFound", "(", "err", ")", "{", "return", "err", "\n", "}", "\n", "var", "machineTag", "names", ".", "MachineTag", "\n", "if", "unit", "!=", "nil", "{", "machineTag", ",", "err", "=", "unit", ".", "AssignedMachine", "(", ")", "\n", "if", "params", ".", "IsCodeNotFound", "(", "err", ")", "{", "continue", "\n", "}", "else", "if", "err", "!=", "nil", "&&", "!", "params", ".", "IsCodeNotAssigned", "(", "err", ")", "{", "return", "err", "\n", "}", "\n", "}", "\n", "if", "unitd", ",", "known", ":=", "fw", ".", "unitds", "[", "unitTag", "]", ";", "known", "{", "knownMachineTag", ":=", "fw", ".", "unitds", "[", "unitTag", "]", ".", "machined", ".", "tag", "\n", "if", "unit", "==", "nil", "||", "unit", ".", "Life", "(", ")", "==", "params", ".", "Dead", "||", "machineTag", "!=", "knownMachineTag", "{", "fw", ".", "forgetUnit", "(", "unitd", ")", "\n", "changed", "=", "append", "(", "changed", ",", "unitd", ")", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "// TODO(dfc) fw.machineds should be map[names.Tag]", "}", "else", "if", "unit", "!=", "nil", "&&", "unit", ".", "Life", "(", ")", "!=", "params", ".", "Dead", "&&", "fw", ".", "machineds", "[", "machineTag", "]", "!=", "nil", "{", "err", "=", "fw", ".", "startUnit", "(", "unit", ",", "machineTag", ")", "\n", "if", "params", ".", "IsCodeNotFound", "(", "err", ")", "{", "continue", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "changed", "=", "append", "(", "changed", ",", "fw", ".", "unitds", "[", "unitTag", "]", ")", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "unitTag", ")", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "fw", ".", "flushUnits", "(", "changed", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// unitsChanged responds to changes to the assigned units.
[ "unitsChanged", "responds", "to", "changes", "to", "the", "assigned", "units", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L596-L637
156,431
juju/juju
worker/firewaller/firewaller.go
openedPortsChanged
func (fw *Firewaller) openedPortsChanged(machineTag names.MachineTag, subnetTag names.SubnetTag) (err error) { defer func() { if params.IsCodeNotFound(err) { err = nil } }() machined, ok := fw.machineds[machineTag] if !ok { // It is common to receive a port change notification before // registering the machine, so if a machine is not found in // firewaller's list, just skip the change. Look up will also // fail if it's a manual machine. logger.Debugf("failed to lookup %q, skipping port change", machineTag) return nil } m, err := machined.machine() if err != nil { return err } ports, err := m.OpenedPorts(subnetTag) if err != nil { return err } newPortRanges := make(map[names.UnitTag]portRanges) for portRange, unitTag := range ports { unitd, ok := machined.unitds[unitTag] if !ok { // It is common to receive port change notification before // registering a unit. Skip handling the port change - it will // be handled when the unit is registered. logger.Debugf("failed to lookup %q, skipping port change", unitTag) return nil } ranges, ok := newPortRanges[unitd.tag] if !ok { ranges = make(portRanges) newPortRanges[unitd.tag] = ranges } ranges[portRange] = true } if !unitPortsEqual(machined.definedPorts, newPortRanges) { machined.definedPorts = newPortRanges return fw.flushMachine(machined) } return nil }
go
func (fw *Firewaller) openedPortsChanged(machineTag names.MachineTag, subnetTag names.SubnetTag) (err error) { defer func() { if params.IsCodeNotFound(err) { err = nil } }() machined, ok := fw.machineds[machineTag] if !ok { // It is common to receive a port change notification before // registering the machine, so if a machine is not found in // firewaller's list, just skip the change. Look up will also // fail if it's a manual machine. logger.Debugf("failed to lookup %q, skipping port change", machineTag) return nil } m, err := machined.machine() if err != nil { return err } ports, err := m.OpenedPorts(subnetTag) if err != nil { return err } newPortRanges := make(map[names.UnitTag]portRanges) for portRange, unitTag := range ports { unitd, ok := machined.unitds[unitTag] if !ok { // It is common to receive port change notification before // registering a unit. Skip handling the port change - it will // be handled when the unit is registered. logger.Debugf("failed to lookup %q, skipping port change", unitTag) return nil } ranges, ok := newPortRanges[unitd.tag] if !ok { ranges = make(portRanges) newPortRanges[unitd.tag] = ranges } ranges[portRange] = true } if !unitPortsEqual(machined.definedPorts, newPortRanges) { machined.definedPorts = newPortRanges return fw.flushMachine(machined) } return nil }
[ "func", "(", "fw", "*", "Firewaller", ")", "openedPortsChanged", "(", "machineTag", "names", ".", "MachineTag", ",", "subnetTag", "names", ".", "SubnetTag", ")", "(", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "params", ".", "IsCodeNotFound", "(", "err", ")", "{", "err", "=", "nil", "\n", "}", "\n", "}", "(", ")", "\n", "machined", ",", "ok", ":=", "fw", ".", "machineds", "[", "machineTag", "]", "\n", "if", "!", "ok", "{", "// It is common to receive a port change notification before", "// registering the machine, so if a machine is not found in", "// firewaller's list, just skip the change. Look up will also", "// fail if it's a manual machine.", "logger", ".", "Debugf", "(", "\"", "\"", ",", "machineTag", ")", "\n", "return", "nil", "\n", "}", "\n\n", "m", ",", "err", ":=", "machined", ".", "machine", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "ports", ",", "err", ":=", "m", ".", "OpenedPorts", "(", "subnetTag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "newPortRanges", ":=", "make", "(", "map", "[", "names", ".", "UnitTag", "]", "portRanges", ")", "\n", "for", "portRange", ",", "unitTag", ":=", "range", "ports", "{", "unitd", ",", "ok", ":=", "machined", ".", "unitds", "[", "unitTag", "]", "\n", "if", "!", "ok", "{", "// It is common to receive port change notification before", "// registering a unit. Skip handling the port change - it will", "// be handled when the unit is registered.", "logger", ".", "Debugf", "(", "\"", "\"", ",", "unitTag", ")", "\n", "return", "nil", "\n", "}", "\n", "ranges", ",", "ok", ":=", "newPortRanges", "[", "unitd", ".", "tag", "]", "\n", "if", "!", "ok", "{", "ranges", "=", "make", "(", "portRanges", ")", "\n", "newPortRanges", "[", "unitd", ".", "tag", "]", "=", "ranges", "\n", "}", "\n", "ranges", "[", "portRange", "]", "=", "true", "\n", "}", "\n\n", "if", "!", "unitPortsEqual", "(", "machined", ".", "definedPorts", ",", "newPortRanges", ")", "{", "machined", ".", "definedPorts", "=", "newPortRanges", "\n", "return", "fw", ".", "flushMachine", "(", "machined", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// openedPortsChanged handles port change notifications
[ "openedPortsChanged", "handles", "port", "change", "notifications" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L640-L689
156,432
juju/juju
worker/firewaller/firewaller.go
flushUnits
func (fw *Firewaller) flushUnits(unitds []*unitData) error { machineds := map[names.MachineTag]*machineData{} for _, unitd := range unitds { machineds[unitd.machined.tag] = unitd.machined } for _, machined := range machineds { if err := fw.flushMachine(machined); err != nil { return err } } return nil }
go
func (fw *Firewaller) flushUnits(unitds []*unitData) error { machineds := map[names.MachineTag]*machineData{} for _, unitd := range unitds { machineds[unitd.machined.tag] = unitd.machined } for _, machined := range machineds { if err := fw.flushMachine(machined); err != nil { return err } } return nil }
[ "func", "(", "fw", "*", "Firewaller", ")", "flushUnits", "(", "unitds", "[", "]", "*", "unitData", ")", "error", "{", "machineds", ":=", "map", "[", "names", ".", "MachineTag", "]", "*", "machineData", "{", "}", "\n", "for", "_", ",", "unitd", ":=", "range", "unitds", "{", "machineds", "[", "unitd", ".", "machined", ".", "tag", "]", "=", "unitd", ".", "machined", "\n", "}", "\n", "for", "_", ",", "machined", ":=", "range", "machineds", "{", "if", "err", ":=", "fw", ".", "flushMachine", "(", "machined", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// flushUnits opens and closes ports for the passed unit data.
[ "flushUnits", "opens", "and", "closes", "ports", "for", "the", "passed", "unit", "data", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L724-L735
156,433
juju/juju
worker/firewaller/firewaller.go
flushMachine
func (fw *Firewaller) flushMachine(machined *machineData) error { want, err := fw.gatherIngressRules(machined) if err != nil { return errors.Trace(err) } toOpen, toClose := diffRanges(machined.ingressRules, want) machined.ingressRules = want if fw.globalMode { return fw.flushGlobalPorts(toOpen, toClose) } return fw.flushInstancePorts(machined, toOpen, toClose) }
go
func (fw *Firewaller) flushMachine(machined *machineData) error { want, err := fw.gatherIngressRules(machined) if err != nil { return errors.Trace(err) } toOpen, toClose := diffRanges(machined.ingressRules, want) machined.ingressRules = want if fw.globalMode { return fw.flushGlobalPorts(toOpen, toClose) } return fw.flushInstancePorts(machined, toOpen, toClose) }
[ "func", "(", "fw", "*", "Firewaller", ")", "flushMachine", "(", "machined", "*", "machineData", ")", "error", "{", "want", ",", "err", ":=", "fw", ".", "gatherIngressRules", "(", "machined", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "toOpen", ",", "toClose", ":=", "diffRanges", "(", "machined", ".", "ingressRules", ",", "want", ")", "\n", "machined", ".", "ingressRules", "=", "want", "\n", "if", "fw", ".", "globalMode", "{", "return", "fw", ".", "flushGlobalPorts", "(", "toOpen", ",", "toClose", ")", "\n", "}", "\n", "return", "fw", ".", "flushInstancePorts", "(", "machined", ",", "toOpen", ",", "toClose", ")", "\n", "}" ]
// flushMachine opens and closes ports for the passed machine.
[ "flushMachine", "opens", "and", "closes", "ports", "for", "the", "passed", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L738-L749
156,434
juju/juju
worker/firewaller/firewaller.go
gatherIngressRules
func (fw *Firewaller) gatherIngressRules(machines ...*machineData) ([]network.IngressRule, error) { var want []network.IngressRule for _, machined := range machines { for unitTag, portRanges := range machined.definedPorts { unitd, known := machined.unitds[unitTag] if !known { logger.Debugf("no ingress rules for unknown %v on %v", unitTag, machined.tag) continue } cidrs := set.NewStrings() // If the unit is exposed, allow access from everywhere. if unitd.applicationd.exposed { cidrs.Add("0.0.0.0/0") } else { // Not exposed, so add any ingress rules required by remote relations. if err := fw.updateForRemoteRelationIngress(unitd.applicationd.application.Tag(), cidrs); err != nil { return nil, errors.Trace(err) } logger.Debugf("CIDRS for %v: %v", unitTag, cidrs.Values()) } if cidrs.Size() > 0 { for portRange := range portRanges { sourceCidrs := cidrs.SortedValues() rule, err := network.NewIngressRule(portRange.Protocol, portRange.FromPort, portRange.ToPort, sourceCidrs...) if err != nil { return nil, errors.Trace(err) } want = append(want, rule) } } } } return want, nil }
go
func (fw *Firewaller) gatherIngressRules(machines ...*machineData) ([]network.IngressRule, error) { var want []network.IngressRule for _, machined := range machines { for unitTag, portRanges := range machined.definedPorts { unitd, known := machined.unitds[unitTag] if !known { logger.Debugf("no ingress rules for unknown %v on %v", unitTag, machined.tag) continue } cidrs := set.NewStrings() // If the unit is exposed, allow access from everywhere. if unitd.applicationd.exposed { cidrs.Add("0.0.0.0/0") } else { // Not exposed, so add any ingress rules required by remote relations. if err := fw.updateForRemoteRelationIngress(unitd.applicationd.application.Tag(), cidrs); err != nil { return nil, errors.Trace(err) } logger.Debugf("CIDRS for %v: %v", unitTag, cidrs.Values()) } if cidrs.Size() > 0 { for portRange := range portRanges { sourceCidrs := cidrs.SortedValues() rule, err := network.NewIngressRule(portRange.Protocol, portRange.FromPort, portRange.ToPort, sourceCidrs...) if err != nil { return nil, errors.Trace(err) } want = append(want, rule) } } } } return want, nil }
[ "func", "(", "fw", "*", "Firewaller", ")", "gatherIngressRules", "(", "machines", "...", "*", "machineData", ")", "(", "[", "]", "network", ".", "IngressRule", ",", "error", ")", "{", "var", "want", "[", "]", "network", ".", "IngressRule", "\n", "for", "_", ",", "machined", ":=", "range", "machines", "{", "for", "unitTag", ",", "portRanges", ":=", "range", "machined", ".", "definedPorts", "{", "unitd", ",", "known", ":=", "machined", ".", "unitds", "[", "unitTag", "]", "\n", "if", "!", "known", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "unitTag", ",", "machined", ".", "tag", ")", "\n", "continue", "\n", "}", "\n\n", "cidrs", ":=", "set", ".", "NewStrings", "(", ")", "\n", "// If the unit is exposed, allow access from everywhere.", "if", "unitd", ".", "applicationd", ".", "exposed", "{", "cidrs", ".", "Add", "(", "\"", "\"", ")", "\n", "}", "else", "{", "// Not exposed, so add any ingress rules required by remote relations.", "if", "err", ":=", "fw", ".", "updateForRemoteRelationIngress", "(", "unitd", ".", "applicationd", ".", "application", ".", "Tag", "(", ")", ",", "cidrs", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "unitTag", ",", "cidrs", ".", "Values", "(", ")", ")", "\n", "}", "\n", "if", "cidrs", ".", "Size", "(", ")", ">", "0", "{", "for", "portRange", ":=", "range", "portRanges", "{", "sourceCidrs", ":=", "cidrs", ".", "SortedValues", "(", ")", "\n", "rule", ",", "err", ":=", "network", ".", "NewIngressRule", "(", "portRange", ".", "Protocol", ",", "portRange", ".", "FromPort", ",", "portRange", ".", "ToPort", ",", "sourceCidrs", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "want", "=", "append", "(", "want", ",", "rule", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "want", ",", "nil", "\n", "}" ]
// gatherIngressRules returns the ingress rules to open and close // for the specified machines.
[ "gatherIngressRules", "returns", "the", "ingress", "rules", "to", "open", "and", "close", "for", "the", "specified", "machines", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L753-L787
156,435
juju/juju
worker/firewaller/firewaller.go
flushGlobalPorts
func (fw *Firewaller) flushGlobalPorts(rawOpen, rawClose []network.IngressRule) error { // Filter which ports are really to open or close. var toOpen, toClose []network.IngressRule for _, rule := range rawOpen { ruleName := rule.String() if fw.globalIngressRuleRef[ruleName] == 0 { toOpen = append(toOpen, rule) } fw.globalIngressRuleRef[ruleName]++ } for _, rule := range rawClose { ruleName := rule.String() fw.globalIngressRuleRef[ruleName]-- if fw.globalIngressRuleRef[ruleName] == 0 { toClose = append(toClose, rule) delete(fw.globalIngressRuleRef, ruleName) } } // Open and close the ports. if len(toOpen) > 0 { if err := fw.environFirewaller.OpenPorts(fw.cloudCallContext, toOpen); err != nil { // TODO(mue) Add local retry logic. return err } network.SortIngressRules(toOpen) logger.Infof("opened port ranges %v in environment", toOpen) } if len(toClose) > 0 { if err := fw.environFirewaller.ClosePorts(fw.cloudCallContext, toClose); err != nil { // TODO(mue) Add local retry logic. return err } network.SortIngressRules(toClose) logger.Infof("closed port ranges %v in environment", toClose) } return nil }
go
func (fw *Firewaller) flushGlobalPorts(rawOpen, rawClose []network.IngressRule) error { // Filter which ports are really to open or close. var toOpen, toClose []network.IngressRule for _, rule := range rawOpen { ruleName := rule.String() if fw.globalIngressRuleRef[ruleName] == 0 { toOpen = append(toOpen, rule) } fw.globalIngressRuleRef[ruleName]++ } for _, rule := range rawClose { ruleName := rule.String() fw.globalIngressRuleRef[ruleName]-- if fw.globalIngressRuleRef[ruleName] == 0 { toClose = append(toClose, rule) delete(fw.globalIngressRuleRef, ruleName) } } // Open and close the ports. if len(toOpen) > 0 { if err := fw.environFirewaller.OpenPorts(fw.cloudCallContext, toOpen); err != nil { // TODO(mue) Add local retry logic. return err } network.SortIngressRules(toOpen) logger.Infof("opened port ranges %v in environment", toOpen) } if len(toClose) > 0 { if err := fw.environFirewaller.ClosePorts(fw.cloudCallContext, toClose); err != nil { // TODO(mue) Add local retry logic. return err } network.SortIngressRules(toClose) logger.Infof("closed port ranges %v in environment", toClose) } return nil }
[ "func", "(", "fw", "*", "Firewaller", ")", "flushGlobalPorts", "(", "rawOpen", ",", "rawClose", "[", "]", "network", ".", "IngressRule", ")", "error", "{", "// Filter which ports are really to open or close.", "var", "toOpen", ",", "toClose", "[", "]", "network", ".", "IngressRule", "\n", "for", "_", ",", "rule", ":=", "range", "rawOpen", "{", "ruleName", ":=", "rule", ".", "String", "(", ")", "\n", "if", "fw", ".", "globalIngressRuleRef", "[", "ruleName", "]", "==", "0", "{", "toOpen", "=", "append", "(", "toOpen", ",", "rule", ")", "\n", "}", "\n", "fw", ".", "globalIngressRuleRef", "[", "ruleName", "]", "++", "\n", "}", "\n", "for", "_", ",", "rule", ":=", "range", "rawClose", "{", "ruleName", ":=", "rule", ".", "String", "(", ")", "\n", "fw", ".", "globalIngressRuleRef", "[", "ruleName", "]", "--", "\n", "if", "fw", ".", "globalIngressRuleRef", "[", "ruleName", "]", "==", "0", "{", "toClose", "=", "append", "(", "toClose", ",", "rule", ")", "\n", "delete", "(", "fw", ".", "globalIngressRuleRef", ",", "ruleName", ")", "\n", "}", "\n", "}", "\n", "// Open and close the ports.", "if", "len", "(", "toOpen", ")", ">", "0", "{", "if", "err", ":=", "fw", ".", "environFirewaller", ".", "OpenPorts", "(", "fw", ".", "cloudCallContext", ",", "toOpen", ")", ";", "err", "!=", "nil", "{", "// TODO(mue) Add local retry logic.", "return", "err", "\n", "}", "\n", "network", ".", "SortIngressRules", "(", "toOpen", ")", "\n", "logger", ".", "Infof", "(", "\"", "\"", ",", "toOpen", ")", "\n", "}", "\n", "if", "len", "(", "toClose", ")", ">", "0", "{", "if", "err", ":=", "fw", ".", "environFirewaller", ".", "ClosePorts", "(", "fw", ".", "cloudCallContext", ",", "toClose", ")", ";", "err", "!=", "nil", "{", "// TODO(mue) Add local retry logic.", "return", "err", "\n", "}", "\n", "network", ".", "SortIngressRules", "(", "toClose", ")", "\n", "logger", ".", "Infof", "(", "\"", "\"", ",", "toClose", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// flushGlobalPorts opens and closes global ports in the environment. // It keeps a reference count for ports so that only 0-to-1 and 1-to-0 events // modify the environment.
[ "flushGlobalPorts", "opens", "and", "closes", "global", "ports", "in", "the", "environment", ".", "It", "keeps", "a", "reference", "count", "for", "ports", "so", "that", "only", "0", "-", "to", "-", "1", "and", "1", "-", "to", "-", "0", "events", "modify", "the", "environment", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L849-L885
156,436
juju/juju
worker/firewaller/firewaller.go
flushInstancePorts
func (fw *Firewaller) flushInstancePorts(machined *machineData, toOpen, toClose []network.IngressRule) (err error) { defer func() { if params.IsCodeNotFound(err) { err = nil } }() // If there's nothing to do, do nothing. // This is important because when a machine is first created, // it will have no instance id but also no open ports - // InstanceId will fail but we don't care. logger.Debugf("flush instance ports: to open %v, to close %v", toOpen, toClose) if len(toOpen) == 0 && len(toClose) == 0 { return nil } m, err := machined.machine() if err != nil { return err } machineId := machined.tag.Id() instanceId, err := m.InstanceId() if params.IsCodeNotProvisioned(err) { // Not provisioned yet, so nothing to do for this instance return nil } if err != nil { return err } envInstances, err := fw.environInstances.Instances(fw.cloudCallContext, []instance.Id{instanceId}) if err != nil { return err } fwInstance, ok := envInstances[0].(instances.InstanceFirewaller) if !ok { logger.Infof("flushInstancePorts called on an instance of type %T which doesn't support firewall.", envInstances[0]) return nil } // Open and close the ports. if len(toOpen) > 0 { if err := fwInstance.OpenPorts(fw.cloudCallContext, machineId, toOpen); err != nil { // TODO(mue) Add local retry logic. return err } network.SortIngressRules(toOpen) logger.Infof("opened port ranges %v on %q", toOpen, machined.tag) } if len(toClose) > 0 { if err := fwInstance.ClosePorts(fw.cloudCallContext, machineId, toClose); err != nil { // TODO(mue) Add local retry logic. return err } network.SortIngressRules(toClose) logger.Infof("closed port ranges %v on %q", toClose, machined.tag) } return nil }
go
func (fw *Firewaller) flushInstancePorts(machined *machineData, toOpen, toClose []network.IngressRule) (err error) { defer func() { if params.IsCodeNotFound(err) { err = nil } }() // If there's nothing to do, do nothing. // This is important because when a machine is first created, // it will have no instance id but also no open ports - // InstanceId will fail but we don't care. logger.Debugf("flush instance ports: to open %v, to close %v", toOpen, toClose) if len(toOpen) == 0 && len(toClose) == 0 { return nil } m, err := machined.machine() if err != nil { return err } machineId := machined.tag.Id() instanceId, err := m.InstanceId() if params.IsCodeNotProvisioned(err) { // Not provisioned yet, so nothing to do for this instance return nil } if err != nil { return err } envInstances, err := fw.environInstances.Instances(fw.cloudCallContext, []instance.Id{instanceId}) if err != nil { return err } fwInstance, ok := envInstances[0].(instances.InstanceFirewaller) if !ok { logger.Infof("flushInstancePorts called on an instance of type %T which doesn't support firewall.", envInstances[0]) return nil } // Open and close the ports. if len(toOpen) > 0 { if err := fwInstance.OpenPorts(fw.cloudCallContext, machineId, toOpen); err != nil { // TODO(mue) Add local retry logic. return err } network.SortIngressRules(toOpen) logger.Infof("opened port ranges %v on %q", toOpen, machined.tag) } if len(toClose) > 0 { if err := fwInstance.ClosePorts(fw.cloudCallContext, machineId, toClose); err != nil { // TODO(mue) Add local retry logic. return err } network.SortIngressRules(toClose) logger.Infof("closed port ranges %v on %q", toClose, machined.tag) } return nil }
[ "func", "(", "fw", "*", "Firewaller", ")", "flushInstancePorts", "(", "machined", "*", "machineData", ",", "toOpen", ",", "toClose", "[", "]", "network", ".", "IngressRule", ")", "(", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "params", ".", "IsCodeNotFound", "(", "err", ")", "{", "err", "=", "nil", "\n", "}", "\n", "}", "(", ")", "\n\n", "// If there's nothing to do, do nothing.", "// This is important because when a machine is first created,", "// it will have no instance id but also no open ports -", "// InstanceId will fail but we don't care.", "logger", ".", "Debugf", "(", "\"", "\"", ",", "toOpen", ",", "toClose", ")", "\n", "if", "len", "(", "toOpen", ")", "==", "0", "&&", "len", "(", "toClose", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "m", ",", "err", ":=", "machined", ".", "machine", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "machineId", ":=", "machined", ".", "tag", ".", "Id", "(", ")", "\n", "instanceId", ",", "err", ":=", "m", ".", "InstanceId", "(", ")", "\n", "if", "params", ".", "IsCodeNotProvisioned", "(", "err", ")", "{", "// Not provisioned yet, so nothing to do for this instance", "return", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "envInstances", ",", "err", ":=", "fw", ".", "environInstances", ".", "Instances", "(", "fw", ".", "cloudCallContext", ",", "[", "]", "instance", ".", "Id", "{", "instanceId", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "fwInstance", ",", "ok", ":=", "envInstances", "[", "0", "]", ".", "(", "instances", ".", "InstanceFirewaller", ")", "\n", "if", "!", "ok", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "envInstances", "[", "0", "]", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// Open and close the ports.", "if", "len", "(", "toOpen", ")", ">", "0", "{", "if", "err", ":=", "fwInstance", ".", "OpenPorts", "(", "fw", ".", "cloudCallContext", ",", "machineId", ",", "toOpen", ")", ";", "err", "!=", "nil", "{", "// TODO(mue) Add local retry logic.", "return", "err", "\n", "}", "\n", "network", ".", "SortIngressRules", "(", "toOpen", ")", "\n", "logger", ".", "Infof", "(", "\"", "\"", ",", "toOpen", ",", "machined", ".", "tag", ")", "\n", "}", "\n", "if", "len", "(", "toClose", ")", ">", "0", "{", "if", "err", ":=", "fwInstance", ".", "ClosePorts", "(", "fw", ".", "cloudCallContext", ",", "machineId", ",", "toClose", ")", ";", "err", "!=", "nil", "{", "// TODO(mue) Add local retry logic.", "return", "err", "\n", "}", "\n", "network", ".", "SortIngressRules", "(", "toClose", ")", "\n", "logger", ".", "Infof", "(", "\"", "\"", ",", "toClose", ",", "machined", ".", "tag", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// flushInstancePorts opens and closes ports global on the machine.
[ "flushInstancePorts", "opens", "and", "closes", "ports", "global", "on", "the", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L888-L944
156,437
juju/juju
worker/firewaller/firewaller.go
machineLifeChanged
func (fw *Firewaller) machineLifeChanged(tag names.MachineTag) error { m, err := fw.firewallerApi.Machine(tag) found := !params.IsCodeNotFound(err) if found && err != nil { return err } dead := !found || m.Life() == params.Dead machined, known := fw.machineds[tag] if known && dead { return fw.forgetMachine(machined) } if !known && !dead { err := fw.startMachine(tag) if err != nil { return err } } return nil }
go
func (fw *Firewaller) machineLifeChanged(tag names.MachineTag) error { m, err := fw.firewallerApi.Machine(tag) found := !params.IsCodeNotFound(err) if found && err != nil { return err } dead := !found || m.Life() == params.Dead machined, known := fw.machineds[tag] if known && dead { return fw.forgetMachine(machined) } if !known && !dead { err := fw.startMachine(tag) if err != nil { return err } } return nil }
[ "func", "(", "fw", "*", "Firewaller", ")", "machineLifeChanged", "(", "tag", "names", ".", "MachineTag", ")", "error", "{", "m", ",", "err", ":=", "fw", ".", "firewallerApi", ".", "Machine", "(", "tag", ")", "\n", "found", ":=", "!", "params", ".", "IsCodeNotFound", "(", "err", ")", "\n", "if", "found", "&&", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "dead", ":=", "!", "found", "||", "m", ".", "Life", "(", ")", "==", "params", ".", "Dead", "\n", "machined", ",", "known", ":=", "fw", ".", "machineds", "[", "tag", "]", "\n", "if", "known", "&&", "dead", "{", "return", "fw", ".", "forgetMachine", "(", "machined", ")", "\n", "}", "\n", "if", "!", "known", "&&", "!", "dead", "{", "err", ":=", "fw", ".", "startMachine", "(", "tag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// machineLifeChanged starts watching new machines when the firewaller // is starting, or when new machines come to life, and stops watching // machines that are dying.
[ "machineLifeChanged", "starts", "watching", "new", "machines", "when", "the", "firewaller", "is", "starting", "or", "when", "new", "machines", "come", "to", "life", "and", "stops", "watching", "machines", "that", "are", "dying", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L949-L967
156,438
juju/juju
worker/firewaller/firewaller.go
forgetMachine
func (fw *Firewaller) forgetMachine(machined *machineData) error { for _, unitd := range machined.unitds { fw.forgetUnit(unitd) } if err := fw.flushMachine(machined); err != nil { return errors.Trace(err) } // Unusually, it's fine to ignore this error, because we know the machined // is being tracked in fw.catacomb. But we do still want to wait until the // watch loop has stopped before we nuke the last data and return. _ = worker.Stop(machined) delete(fw.machineds, machined.tag) logger.Debugf("stopped watching %q", machined.tag) return nil }
go
func (fw *Firewaller) forgetMachine(machined *machineData) error { for _, unitd := range machined.unitds { fw.forgetUnit(unitd) } if err := fw.flushMachine(machined); err != nil { return errors.Trace(err) } // Unusually, it's fine to ignore this error, because we know the machined // is being tracked in fw.catacomb. But we do still want to wait until the // watch loop has stopped before we nuke the last data and return. _ = worker.Stop(machined) delete(fw.machineds, machined.tag) logger.Debugf("stopped watching %q", machined.tag) return nil }
[ "func", "(", "fw", "*", "Firewaller", ")", "forgetMachine", "(", "machined", "*", "machineData", ")", "error", "{", "for", "_", ",", "unitd", ":=", "range", "machined", ".", "unitds", "{", "fw", ".", "forgetUnit", "(", "unitd", ")", "\n", "}", "\n", "if", "err", ":=", "fw", ".", "flushMachine", "(", "machined", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// Unusually, it's fine to ignore this error, because we know the machined", "// is being tracked in fw.catacomb. But we do still want to wait until the", "// watch loop has stopped before we nuke the last data and return.", "_", "=", "worker", ".", "Stop", "(", "machined", ")", "\n", "delete", "(", "fw", ".", "machineds", ",", "machined", ".", "tag", ")", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "machined", ".", "tag", ")", "\n", "return", "nil", "\n", "}" ]
// forgetMachine cleans the machine data after the machine is removed.
[ "forgetMachine", "cleans", "the", "machine", "data", "after", "the", "machine", "is", "removed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L970-L985
156,439
juju/juju
worker/firewaller/firewaller.go
forgetUnit
func (fw *Firewaller) forgetUnit(unitd *unitData) { applicationd := unitd.applicationd machined := unitd.machined // If it's the last unit in the application, we'll need to stop the applicationd. stoppedApplication := false if len(applicationd.unitds) == 1 { if _, found := applicationd.unitds[unitd.tag]; found { // Unusually, it's fine to ignore this error, because we know the // applicationd is being tracked in fw.catacomb. But we do still want // to wait until the watch loop has stopped before we nuke the last // data and return. _ = worker.Stop(applicationd) stoppedApplication = true } } // Clean up after stopping. delete(fw.unitds, unitd.tag) delete(machined.unitds, unitd.tag) delete(applicationd.unitds, unitd.tag) logger.Debugf("stopped watching %q", unitd.tag) if stoppedApplication { applicationTag := applicationd.application.Tag() delete(fw.applicationids, applicationTag) logger.Debugf("stopped watching %q", applicationTag) } }
go
func (fw *Firewaller) forgetUnit(unitd *unitData) { applicationd := unitd.applicationd machined := unitd.machined // If it's the last unit in the application, we'll need to stop the applicationd. stoppedApplication := false if len(applicationd.unitds) == 1 { if _, found := applicationd.unitds[unitd.tag]; found { // Unusually, it's fine to ignore this error, because we know the // applicationd is being tracked in fw.catacomb. But we do still want // to wait until the watch loop has stopped before we nuke the last // data and return. _ = worker.Stop(applicationd) stoppedApplication = true } } // Clean up after stopping. delete(fw.unitds, unitd.tag) delete(machined.unitds, unitd.tag) delete(applicationd.unitds, unitd.tag) logger.Debugf("stopped watching %q", unitd.tag) if stoppedApplication { applicationTag := applicationd.application.Tag() delete(fw.applicationids, applicationTag) logger.Debugf("stopped watching %q", applicationTag) } }
[ "func", "(", "fw", "*", "Firewaller", ")", "forgetUnit", "(", "unitd", "*", "unitData", ")", "{", "applicationd", ":=", "unitd", ".", "applicationd", "\n", "machined", ":=", "unitd", ".", "machined", "\n\n", "// If it's the last unit in the application, we'll need to stop the applicationd.", "stoppedApplication", ":=", "false", "\n", "if", "len", "(", "applicationd", ".", "unitds", ")", "==", "1", "{", "if", "_", ",", "found", ":=", "applicationd", ".", "unitds", "[", "unitd", ".", "tag", "]", ";", "found", "{", "// Unusually, it's fine to ignore this error, because we know the", "// applicationd is being tracked in fw.catacomb. But we do still want", "// to wait until the watch loop has stopped before we nuke the last", "// data and return.", "_", "=", "worker", ".", "Stop", "(", "applicationd", ")", "\n", "stoppedApplication", "=", "true", "\n", "}", "\n", "}", "\n\n", "// Clean up after stopping.", "delete", "(", "fw", ".", "unitds", ",", "unitd", ".", "tag", ")", "\n", "delete", "(", "machined", ".", "unitds", ",", "unitd", ".", "tag", ")", "\n", "delete", "(", "applicationd", ".", "unitds", ",", "unitd", ".", "tag", ")", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "unitd", ".", "tag", ")", "\n", "if", "stoppedApplication", "{", "applicationTag", ":=", "applicationd", ".", "application", ".", "Tag", "(", ")", "\n", "delete", "(", "fw", ".", "applicationids", ",", "applicationTag", ")", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "applicationTag", ")", "\n", "}", "\n", "}" ]
// forgetUnit cleans the unit data after the unit is removed.
[ "forgetUnit", "cleans", "the", "unit", "data", "after", "the", "unit", "is", "removed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L988-L1015
156,440
juju/juju
worker/firewaller/firewaller.go
watchLoop
func (md *machineData) watchLoop(unitw watcher.StringsWatcher) error { if err := md.catacomb.Add(unitw); err != nil { return errors.Trace(err) } for { select { case <-md.catacomb.Dying(): return md.catacomb.ErrDying() case change, ok := <-unitw.Changes(): if !ok { return errors.New("machine units watcher closed") } select { case <-md.catacomb.Dying(): return md.catacomb.ErrDying() case md.fw.unitsChange <- &unitsChange{md, change}: } } } }
go
func (md *machineData) watchLoop(unitw watcher.StringsWatcher) error { if err := md.catacomb.Add(unitw); err != nil { return errors.Trace(err) } for { select { case <-md.catacomb.Dying(): return md.catacomb.ErrDying() case change, ok := <-unitw.Changes(): if !ok { return errors.New("machine units watcher closed") } select { case <-md.catacomb.Dying(): return md.catacomb.ErrDying() case md.fw.unitsChange <- &unitsChange{md, change}: } } } }
[ "func", "(", "md", "*", "machineData", ")", "watchLoop", "(", "unitw", "watcher", ".", "StringsWatcher", ")", "error", "{", "if", "err", ":=", "md", ".", "catacomb", ".", "Add", "(", "unitw", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "for", "{", "select", "{", "case", "<-", "md", ".", "catacomb", ".", "Dying", "(", ")", ":", "return", "md", ".", "catacomb", ".", "ErrDying", "(", ")", "\n", "case", "change", ",", "ok", ":=", "<-", "unitw", ".", "Changes", "(", ")", ":", "if", "!", "ok", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "select", "{", "case", "<-", "md", ".", "catacomb", ".", "Dying", "(", ")", ":", "return", "md", ".", "catacomb", ".", "ErrDying", "(", ")", "\n", "case", "md", ".", "fw", ".", "unitsChange", "<-", "&", "unitsChange", "{", "md", ",", "change", "}", ":", "}", "\n", "}", "\n", "}", "\n", "}" ]
// watchLoop watches the machine for units added or removed.
[ "watchLoop", "watches", "the", "machine", "for", "units", "added", "or", "removed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L1049-L1068
156,441
juju/juju
worker/firewaller/firewaller.go
watchLoop
func (ad *applicationData) watchLoop(exposed bool) error { appWatcher, err := ad.application.Watch() if err != nil { if params.IsCodeNotFound(err) { return nil } return errors.Trace(err) } if err := ad.catacomb.Add(appWatcher); err != nil { return errors.Trace(err) } for { select { case <-ad.catacomb.Dying(): return ad.catacomb.ErrDying() case _, ok := <-appWatcher.Changes(): if !ok { return errors.New("application watcher closed") } change, err := ad.application.IsExposed() if err != nil { if errors.IsNotFound(err) { logger.Debugf("application(%q).IsExposed() returned NotFound: %v", ad.application.Name(), err) return nil } return errors.Trace(err) } if change == exposed { logger.Tracef("application(%q).IsExposed() == %v (unchanged)", ad.application.Name(), exposed) continue } logger.Tracef("application(%q).IsExposed() changed %v => %v", ad.application.Name(), exposed, change) exposed = change select { case <-ad.catacomb.Dying(): return ad.catacomb.ErrDying() case ad.fw.exposedChange <- &exposedChange{ad, change}: } } } }
go
func (ad *applicationData) watchLoop(exposed bool) error { appWatcher, err := ad.application.Watch() if err != nil { if params.IsCodeNotFound(err) { return nil } return errors.Trace(err) } if err := ad.catacomb.Add(appWatcher); err != nil { return errors.Trace(err) } for { select { case <-ad.catacomb.Dying(): return ad.catacomb.ErrDying() case _, ok := <-appWatcher.Changes(): if !ok { return errors.New("application watcher closed") } change, err := ad.application.IsExposed() if err != nil { if errors.IsNotFound(err) { logger.Debugf("application(%q).IsExposed() returned NotFound: %v", ad.application.Name(), err) return nil } return errors.Trace(err) } if change == exposed { logger.Tracef("application(%q).IsExposed() == %v (unchanged)", ad.application.Name(), exposed) continue } logger.Tracef("application(%q).IsExposed() changed %v => %v", ad.application.Name(), exposed, change) exposed = change select { case <-ad.catacomb.Dying(): return ad.catacomb.ErrDying() case ad.fw.exposedChange <- &exposedChange{ad, change}: } } } }
[ "func", "(", "ad", "*", "applicationData", ")", "watchLoop", "(", "exposed", "bool", ")", "error", "{", "appWatcher", ",", "err", ":=", "ad", ".", "application", ".", "Watch", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "params", ".", "IsCodeNotFound", "(", "err", ")", "{", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "ad", ".", "catacomb", ".", "Add", "(", "appWatcher", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "for", "{", "select", "{", "case", "<-", "ad", ".", "catacomb", ".", "Dying", "(", ")", ":", "return", "ad", ".", "catacomb", ".", "ErrDying", "(", ")", "\n", "case", "_", ",", "ok", ":=", "<-", "appWatcher", ".", "Changes", "(", ")", ":", "if", "!", "ok", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "change", ",", "err", ":=", "ad", ".", "application", ".", "IsExposed", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "ad", ".", "application", ".", "Name", "(", ")", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "change", "==", "exposed", "{", "logger", ".", "Tracef", "(", "\"", "\"", ",", "ad", ".", "application", ".", "Name", "(", ")", ",", "exposed", ")", "\n", "continue", "\n", "}", "\n", "logger", ".", "Tracef", "(", "\"", "\"", ",", "ad", ".", "application", ".", "Name", "(", ")", ",", "exposed", ",", "change", ")", "\n\n", "exposed", "=", "change", "\n", "select", "{", "case", "<-", "ad", ".", "catacomb", ".", "Dying", "(", ")", ":", "return", "ad", ".", "catacomb", ".", "ErrDying", "(", ")", "\n", "case", "ad", ".", "fw", ".", "exposedChange", "<-", "&", "exposedChange", "{", "ad", ",", "change", "}", ":", "}", "\n", "}", "\n", "}", "\n", "}" ]
// watchLoop watches the application's exposed flag for changes.
[ "watchLoop", "watches", "the", "application", "s", "exposed", "flag", "for", "changes", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L1105-L1146
156,442
juju/juju
worker/firewaller/firewaller.go
relationLifeChanged
func (fw *Firewaller) relationLifeChanged(tag names.RelationTag) error { results, err := fw.remoteRelationsApi.Relations([]string{tag.Id()}) if err != nil { return errors.Trace(err) } relErr := results[0].Error notfound := relErr != nil && params.IsCodeNotFound(relErr) if relErr != nil && !notfound { return err } rel := results[0].Result gone := notfound || rel.Life == params.Dead || rel.Suspended data, known := fw.relationIngress[tag] if known && gone { logger.Debugf("relation %v was known but has died or been suspended", tag.Id()) // If relation is suspended, shut off ingress immediately. // Units will also eventually leave scope which would cause // ingress to be shut off, but best to do it up front. if rel != nil && rel.Suspended { change := &remoteRelationNetworkChange{ relationTag: tag, localApplicationTag: data.localApplicationTag, ingressRequired: false, } if err := fw.relationIngressChanged(change); err != nil { return errors.Trace(err) } } return fw.forgetRelation(data) } if !known && !gone { err := fw.startRelation(rel, rel.Endpoint.Role) if err != nil { return err } } return nil }
go
func (fw *Firewaller) relationLifeChanged(tag names.RelationTag) error { results, err := fw.remoteRelationsApi.Relations([]string{tag.Id()}) if err != nil { return errors.Trace(err) } relErr := results[0].Error notfound := relErr != nil && params.IsCodeNotFound(relErr) if relErr != nil && !notfound { return err } rel := results[0].Result gone := notfound || rel.Life == params.Dead || rel.Suspended data, known := fw.relationIngress[tag] if known && gone { logger.Debugf("relation %v was known but has died or been suspended", tag.Id()) // If relation is suspended, shut off ingress immediately. // Units will also eventually leave scope which would cause // ingress to be shut off, but best to do it up front. if rel != nil && rel.Suspended { change := &remoteRelationNetworkChange{ relationTag: tag, localApplicationTag: data.localApplicationTag, ingressRequired: false, } if err := fw.relationIngressChanged(change); err != nil { return errors.Trace(err) } } return fw.forgetRelation(data) } if !known && !gone { err := fw.startRelation(rel, rel.Endpoint.Role) if err != nil { return err } } return nil }
[ "func", "(", "fw", "*", "Firewaller", ")", "relationLifeChanged", "(", "tag", "names", ".", "RelationTag", ")", "error", "{", "results", ",", "err", ":=", "fw", ".", "remoteRelationsApi", ".", "Relations", "(", "[", "]", "string", "{", "tag", ".", "Id", "(", ")", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "relErr", ":=", "results", "[", "0", "]", ".", "Error", "\n", "notfound", ":=", "relErr", "!=", "nil", "&&", "params", ".", "IsCodeNotFound", "(", "relErr", ")", "\n", "if", "relErr", "!=", "nil", "&&", "!", "notfound", "{", "return", "err", "\n", "}", "\n", "rel", ":=", "results", "[", "0", "]", ".", "Result", "\n\n", "gone", ":=", "notfound", "||", "rel", ".", "Life", "==", "params", ".", "Dead", "||", "rel", ".", "Suspended", "\n", "data", ",", "known", ":=", "fw", ".", "relationIngress", "[", "tag", "]", "\n", "if", "known", "&&", "gone", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "tag", ".", "Id", "(", ")", ")", "\n", "// If relation is suspended, shut off ingress immediately.", "// Units will also eventually leave scope which would cause", "// ingress to be shut off, but best to do it up front.", "if", "rel", "!=", "nil", "&&", "rel", ".", "Suspended", "{", "change", ":=", "&", "remoteRelationNetworkChange", "{", "relationTag", ":", "tag", ",", "localApplicationTag", ":", "data", ".", "localApplicationTag", ",", "ingressRequired", ":", "false", ",", "}", "\n", "if", "err", ":=", "fw", ".", "relationIngressChanged", "(", "change", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "fw", ".", "forgetRelation", "(", "data", ")", "\n", "}", "\n", "if", "!", "known", "&&", "!", "gone", "{", "err", ":=", "fw", ".", "startRelation", "(", "rel", ",", "rel", ".", "Endpoint", ".", "Role", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// relationLifeChanged manages the workers to process ingress changes for // the specified relation.
[ "relationLifeChanged", "manages", "the", "workers", "to", "process", "ingress", "changes", "for", "the", "specified", "relation", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L1236-L1274
156,443
juju/juju
worker/firewaller/firewaller.go
startRelation
func (fw *Firewaller) startRelation(rel *params.RemoteRelation, role charm.RelationRole) error { remoteApps, err := fw.remoteRelationsApi.RemoteApplications([]string{rel.RemoteApplicationName}) if err != nil { return errors.Trace(err) } remoteAppResult := remoteApps[0] if remoteAppResult.Error != nil { return errors.Trace(err) } tag := names.NewRelationTag(rel.Key) data := &remoteRelationData{ fw: fw, tag: tag, remoteModelUUID: rel.SourceModelUUID, localApplicationTag: names.NewApplicationTag(rel.ApplicationName), endpointRole: role, relationReady: make(chan remoteRelationInfo), } // Start the worker which will watch the remote relation for things like new networks. if err := fw.relationWorkerRunner.StartWorker(tag.Id(), func() (worker.Worker, error) { if err := catacomb.Invoke(catacomb.Plan{ Site: &data.catacomb, Work: data.watchLoop, }); err != nil { return nil, errors.Trace(err) } return data, nil }); err != nil { return errors.Annotate(err, "error starting remote relation worker") } fw.relationIngress[tag] = data data.isOffer = remoteAppResult.Result.IsConsumerProxy return fw.startRelationPoller(rel.Key, rel.RemoteApplicationName, data.relationReady) }
go
func (fw *Firewaller) startRelation(rel *params.RemoteRelation, role charm.RelationRole) error { remoteApps, err := fw.remoteRelationsApi.RemoteApplications([]string{rel.RemoteApplicationName}) if err != nil { return errors.Trace(err) } remoteAppResult := remoteApps[0] if remoteAppResult.Error != nil { return errors.Trace(err) } tag := names.NewRelationTag(rel.Key) data := &remoteRelationData{ fw: fw, tag: tag, remoteModelUUID: rel.SourceModelUUID, localApplicationTag: names.NewApplicationTag(rel.ApplicationName), endpointRole: role, relationReady: make(chan remoteRelationInfo), } // Start the worker which will watch the remote relation for things like new networks. if err := fw.relationWorkerRunner.StartWorker(tag.Id(), func() (worker.Worker, error) { if err := catacomb.Invoke(catacomb.Plan{ Site: &data.catacomb, Work: data.watchLoop, }); err != nil { return nil, errors.Trace(err) } return data, nil }); err != nil { return errors.Annotate(err, "error starting remote relation worker") } fw.relationIngress[tag] = data data.isOffer = remoteAppResult.Result.IsConsumerProxy return fw.startRelationPoller(rel.Key, rel.RemoteApplicationName, data.relationReady) }
[ "func", "(", "fw", "*", "Firewaller", ")", "startRelation", "(", "rel", "*", "params", ".", "RemoteRelation", ",", "role", "charm", ".", "RelationRole", ")", "error", "{", "remoteApps", ",", "err", ":=", "fw", ".", "remoteRelationsApi", ".", "RemoteApplications", "(", "[", "]", "string", "{", "rel", ".", "RemoteApplicationName", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "remoteAppResult", ":=", "remoteApps", "[", "0", "]", "\n", "if", "remoteAppResult", ".", "Error", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "tag", ":=", "names", ".", "NewRelationTag", "(", "rel", ".", "Key", ")", "\n", "data", ":=", "&", "remoteRelationData", "{", "fw", ":", "fw", ",", "tag", ":", "tag", ",", "remoteModelUUID", ":", "rel", ".", "SourceModelUUID", ",", "localApplicationTag", ":", "names", ".", "NewApplicationTag", "(", "rel", ".", "ApplicationName", ")", ",", "endpointRole", ":", "role", ",", "relationReady", ":", "make", "(", "chan", "remoteRelationInfo", ")", ",", "}", "\n\n", "// Start the worker which will watch the remote relation for things like new networks.", "if", "err", ":=", "fw", ".", "relationWorkerRunner", ".", "StartWorker", "(", "tag", ".", "Id", "(", ")", ",", "func", "(", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "if", "err", ":=", "catacomb", ".", "Invoke", "(", "catacomb", ".", "Plan", "{", "Site", ":", "&", "data", ".", "catacomb", ",", "Work", ":", "data", ".", "watchLoop", ",", "}", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "data", ",", "nil", "\n", "}", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "fw", ".", "relationIngress", "[", "tag", "]", "=", "data", "\n\n", "data", ".", "isOffer", "=", "remoteAppResult", ".", "Result", ".", "IsConsumerProxy", "\n", "return", "fw", ".", "startRelationPoller", "(", "rel", ".", "Key", ",", "rel", ".", "RemoteApplicationName", ",", "data", ".", "relationReady", ")", "\n", "}" ]
// startRelation creates a new data value for tracking details of the // relation and starts watching the related models for subnets added or removed.
[ "startRelation", "creates", "a", "new", "data", "value", "for", "tracking", "details", "of", "the", "relation", "and", "starts", "watching", "the", "related", "models", "for", "subnets", "added", "or", "removed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L1304-L1340
156,444
juju/juju
worker/firewaller/firewaller.go
watchLoop
func (rd *remoteRelationData) watchLoop() error { defer func() { if rd.crossModelFirewallerFacade != nil { rd.crossModelFirewallerFacade.Close() } }() // First, wait for relation to become ready. for rd.relationToken == "" { select { case <-rd.catacomb.Dying(): return rd.catacomb.ErrDying() case remoteRelationInfo := <-rd.relationReady: rd.relationToken = remoteRelationInfo.relationToken rd.applicationToken = remoteRelationInfo.applicationToken logger.Debugf( "relation %v for remote app %v in model %v is ready", rd.relationToken, rd.applicationToken, rd.remoteModelUUID) } } if rd.endpointRole == charm.RoleRequirer { return rd.requirerEndpointLoop() } return rd.providerEndpointLoop() }
go
func (rd *remoteRelationData) watchLoop() error { defer func() { if rd.crossModelFirewallerFacade != nil { rd.crossModelFirewallerFacade.Close() } }() // First, wait for relation to become ready. for rd.relationToken == "" { select { case <-rd.catacomb.Dying(): return rd.catacomb.ErrDying() case remoteRelationInfo := <-rd.relationReady: rd.relationToken = remoteRelationInfo.relationToken rd.applicationToken = remoteRelationInfo.applicationToken logger.Debugf( "relation %v for remote app %v in model %v is ready", rd.relationToken, rd.applicationToken, rd.remoteModelUUID) } } if rd.endpointRole == charm.RoleRequirer { return rd.requirerEndpointLoop() } return rd.providerEndpointLoop() }
[ "func", "(", "rd", "*", "remoteRelationData", ")", "watchLoop", "(", ")", "error", "{", "defer", "func", "(", ")", "{", "if", "rd", ".", "crossModelFirewallerFacade", "!=", "nil", "{", "rd", ".", "crossModelFirewallerFacade", ".", "Close", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "// First, wait for relation to become ready.", "for", "rd", ".", "relationToken", "==", "\"", "\"", "{", "select", "{", "case", "<-", "rd", ".", "catacomb", ".", "Dying", "(", ")", ":", "return", "rd", ".", "catacomb", ".", "ErrDying", "(", ")", "\n", "case", "remoteRelationInfo", ":=", "<-", "rd", ".", "relationReady", ":", "rd", ".", "relationToken", "=", "remoteRelationInfo", ".", "relationToken", "\n", "rd", ".", "applicationToken", "=", "remoteRelationInfo", ".", "applicationToken", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "rd", ".", "relationToken", ",", "rd", ".", "applicationToken", ",", "rd", ".", "remoteModelUUID", ")", "\n", "}", "\n", "}", "\n\n", "if", "rd", ".", "endpointRole", "==", "charm", ".", "RoleRequirer", "{", "return", "rd", ".", "requirerEndpointLoop", "(", ")", "\n", "}", "\n", "return", "rd", ".", "providerEndpointLoop", "(", ")", "\n", "}" ]
// watchLoop watches the relation for networks added or removed.
[ "watchLoop", "watches", "the", "relation", "for", "networks", "added", "or", "removed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L1343-L1368
156,445
juju/juju
worker/firewaller/firewaller.go
updateProviderModel
func (rd *remoteRelationData) updateProviderModel(cidrs []string) error { logger.Debugf("ingress cidrs for %v: %+v", rd.tag, cidrs) change := &remoteRelationNetworkChange{ relationTag: rd.tag, localApplicationTag: rd.localApplicationTag, networks: set.NewStrings(cidrs...), ingressRequired: len(cidrs) > 0, } apiInfo, err := rd.fw.firewallerApi.ControllerAPIInfoForModel(rd.remoteModelUUID) if err != nil { return errors.Annotatef(err, "cannot get api info for model %v", rd.remoteModelUUID) } mac, err := rd.fw.firewallerApi.MacaroonForRelation(rd.tag.Id()) if params.IsCodeNotFound(err) { // Relation has gone, nothing to do. return nil } if err != nil { return errors.Annotatef(err, "cannot get macaroon for %v", rd.tag.Id()) } remoteModelAPI, err := rd.fw.newRemoteFirewallerAPIFunc(apiInfo) if err != nil { return errors.Annotate(err, "cannot open facade to remote model to publish network change") } defer remoteModelAPI.Close() event := params.IngressNetworksChangeEvent{ RelationToken: rd.relationToken, ApplicationToken: rd.applicationToken, Networks: change.networks.Values(), IngressRequired: change.ingressRequired, Macaroons: macaroon.Slice{mac}, } err = remoteModelAPI.PublishIngressNetworkChange(event) if errors.IsNotFound(err) { logger.Debugf("relation id not found publishing %+v", event) return nil } // If the requested ingress is not permitted on the offering side, // mark the relation as in error. It's not an error that requires a // worker restart though. if params.IsCodeForbidden(err) { return rd.fw.firewallerApi.SetRelationStatus(rd.tag.Id(), relation.Error, err.Error()) } return errors.Annotate(err, "cannot publish ingress network change") }
go
func (rd *remoteRelationData) updateProviderModel(cidrs []string) error { logger.Debugf("ingress cidrs for %v: %+v", rd.tag, cidrs) change := &remoteRelationNetworkChange{ relationTag: rd.tag, localApplicationTag: rd.localApplicationTag, networks: set.NewStrings(cidrs...), ingressRequired: len(cidrs) > 0, } apiInfo, err := rd.fw.firewallerApi.ControllerAPIInfoForModel(rd.remoteModelUUID) if err != nil { return errors.Annotatef(err, "cannot get api info for model %v", rd.remoteModelUUID) } mac, err := rd.fw.firewallerApi.MacaroonForRelation(rd.tag.Id()) if params.IsCodeNotFound(err) { // Relation has gone, nothing to do. return nil } if err != nil { return errors.Annotatef(err, "cannot get macaroon for %v", rd.tag.Id()) } remoteModelAPI, err := rd.fw.newRemoteFirewallerAPIFunc(apiInfo) if err != nil { return errors.Annotate(err, "cannot open facade to remote model to publish network change") } defer remoteModelAPI.Close() event := params.IngressNetworksChangeEvent{ RelationToken: rd.relationToken, ApplicationToken: rd.applicationToken, Networks: change.networks.Values(), IngressRequired: change.ingressRequired, Macaroons: macaroon.Slice{mac}, } err = remoteModelAPI.PublishIngressNetworkChange(event) if errors.IsNotFound(err) { logger.Debugf("relation id not found publishing %+v", event) return nil } // If the requested ingress is not permitted on the offering side, // mark the relation as in error. It's not an error that requires a // worker restart though. if params.IsCodeForbidden(err) { return rd.fw.firewallerApi.SetRelationStatus(rd.tag.Id(), relation.Error, err.Error()) } return errors.Annotate(err, "cannot publish ingress network change") }
[ "func", "(", "rd", "*", "remoteRelationData", ")", "updateProviderModel", "(", "cidrs", "[", "]", "string", ")", "error", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "rd", ".", "tag", ",", "cidrs", ")", "\n", "change", ":=", "&", "remoteRelationNetworkChange", "{", "relationTag", ":", "rd", ".", "tag", ",", "localApplicationTag", ":", "rd", ".", "localApplicationTag", ",", "networks", ":", "set", ".", "NewStrings", "(", "cidrs", "...", ")", ",", "ingressRequired", ":", "len", "(", "cidrs", ")", ">", "0", ",", "}", "\n\n", "apiInfo", ",", "err", ":=", "rd", ".", "fw", ".", "firewallerApi", ".", "ControllerAPIInfoForModel", "(", "rd", ".", "remoteModelUUID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "rd", ".", "remoteModelUUID", ")", "\n", "}", "\n", "mac", ",", "err", ":=", "rd", ".", "fw", ".", "firewallerApi", ".", "MacaroonForRelation", "(", "rd", ".", "tag", ".", "Id", "(", ")", ")", "\n", "if", "params", ".", "IsCodeNotFound", "(", "err", ")", "{", "// Relation has gone, nothing to do.", "return", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "rd", ".", "tag", ".", "Id", "(", ")", ")", "\n", "}", "\n", "remoteModelAPI", ",", "err", ":=", "rd", ".", "fw", ".", "newRemoteFirewallerAPIFunc", "(", "apiInfo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "defer", "remoteModelAPI", ".", "Close", "(", ")", "\n", "event", ":=", "params", ".", "IngressNetworksChangeEvent", "{", "RelationToken", ":", "rd", ".", "relationToken", ",", "ApplicationToken", ":", "rd", ".", "applicationToken", ",", "Networks", ":", "change", ".", "networks", ".", "Values", "(", ")", ",", "IngressRequired", ":", "change", ".", "ingressRequired", ",", "Macaroons", ":", "macaroon", ".", "Slice", "{", "mac", "}", ",", "}", "\n", "err", "=", "remoteModelAPI", ".", "PublishIngressNetworkChange", "(", "event", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "event", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// If the requested ingress is not permitted on the offering side,", "// mark the relation as in error. It's not an error that requires a", "// worker restart though.", "if", "params", ".", "IsCodeForbidden", "(", "err", ")", "{", "return", "rd", ".", "fw", ".", "firewallerApi", ".", "SetRelationStatus", "(", "rd", ".", "tag", ".", "Id", "(", ")", ",", "relation", ".", "Error", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}" ]
// updateProviderModel gathers the ingress CIDRs for the relation and notifies // that a change has occurred.
[ "updateProviderModel", "gathers", "the", "ingress", "CIDRs", "for", "the", "relation", "and", "notifies", "that", "a", "change", "has", "occurred", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L1473-L1519
156,446
juju/juju
worker/firewaller/firewaller.go
updateIngressNetworks
func (rd *remoteRelationData) updateIngressNetworks(cidrs []string) error { logger.Debugf("ingress cidrs for %v: %+v", rd.tag, cidrs) change := &remoteRelationNetworkChange{ relationTag: rd.tag, localApplicationTag: rd.localApplicationTag, networks: set.NewStrings(cidrs...), ingressRequired: len(cidrs) > 0, } select { case <-rd.catacomb.Dying(): return rd.catacomb.ErrDying() case rd.fw.localRelationsChange <- change: } return nil }
go
func (rd *remoteRelationData) updateIngressNetworks(cidrs []string) error { logger.Debugf("ingress cidrs for %v: %+v", rd.tag, cidrs) change := &remoteRelationNetworkChange{ relationTag: rd.tag, localApplicationTag: rd.localApplicationTag, networks: set.NewStrings(cidrs...), ingressRequired: len(cidrs) > 0, } select { case <-rd.catacomb.Dying(): return rd.catacomb.ErrDying() case rd.fw.localRelationsChange <- change: } return nil }
[ "func", "(", "rd", "*", "remoteRelationData", ")", "updateIngressNetworks", "(", "cidrs", "[", "]", "string", ")", "error", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "rd", ".", "tag", ",", "cidrs", ")", "\n", "change", ":=", "&", "remoteRelationNetworkChange", "{", "relationTag", ":", "rd", ".", "tag", ",", "localApplicationTag", ":", "rd", ".", "localApplicationTag", ",", "networks", ":", "set", ".", "NewStrings", "(", "cidrs", "...", ")", ",", "ingressRequired", ":", "len", "(", "cidrs", ")", ">", "0", ",", "}", "\n", "select", "{", "case", "<-", "rd", ".", "catacomb", ".", "Dying", "(", ")", ":", "return", "rd", ".", "catacomb", ".", "ErrDying", "(", ")", "\n", "case", "rd", ".", "fw", ".", "localRelationsChange", "<-", "change", ":", "}", "\n", "return", "nil", "\n", "}" ]
// updateIngressNetworks processes the changed ingress networks on the relation.
[ "updateIngressNetworks", "processes", "the", "changed", "ingress", "networks", "on", "the", "relation", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L1522-L1536
156,447
juju/juju
worker/firewaller/firewaller.go
forgetRelation
func (fw *Firewaller) forgetRelation(data *remoteRelationData) error { logger.Debugf("forget relation %v", data.tag.Id()) delete(fw.relationIngress, data.tag) // There's not much we can do if there's an error stopping the remote // relation worker, so just log it. if err := fw.relationWorkerRunner.StopWorker(data.tag.Id()); err != nil { logger.Errorf("error stopping remote relation worker for %s: %v", data.tag, err) } logger.Debugf("stopped watching %q", data.tag) return nil }
go
func (fw *Firewaller) forgetRelation(data *remoteRelationData) error { logger.Debugf("forget relation %v", data.tag.Id()) delete(fw.relationIngress, data.tag) // There's not much we can do if there's an error stopping the remote // relation worker, so just log it. if err := fw.relationWorkerRunner.StopWorker(data.tag.Id()); err != nil { logger.Errorf("error stopping remote relation worker for %s: %v", data.tag, err) } logger.Debugf("stopped watching %q", data.tag) return nil }
[ "func", "(", "fw", "*", "Firewaller", ")", "forgetRelation", "(", "data", "*", "remoteRelationData", ")", "error", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "data", ".", "tag", ".", "Id", "(", ")", ")", "\n", "delete", "(", "fw", ".", "relationIngress", ",", "data", ".", "tag", ")", "\n", "// There's not much we can do if there's an error stopping the remote", "// relation worker, so just log it.", "if", "err", ":=", "fw", ".", "relationWorkerRunner", ".", "StopWorker", "(", "data", ".", "tag", ".", "Id", "(", ")", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "data", ".", "tag", ",", "err", ")", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "data", ".", "tag", ")", "\n", "return", "nil", "\n", "}" ]
// forgetRelation cleans the relation data after the relation is removed.
[ "forgetRelation", "cleans", "the", "relation", "data", "after", "the", "relation", "is", "removed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L1549-L1559
156,448
juju/juju
worker/firewaller/firewaller.go
startRelationPoller
func (fw *Firewaller) startRelationPoller(relationKey, remoteAppName string, relationReady chan remoteRelationInfo) error { poller := &remoteRelationPoller{ fw: fw, relationTag: names.NewRelationTag(relationKey), applicationTag: names.NewApplicationTag(remoteAppName), relationReady: relationReady, } err := catacomb.Invoke(catacomb.Plan{ Site: &poller.catacomb, Work: poller.pollLoop, }) if err != nil { return errors.Trace(err) } // register poller with the firewaller's catacomb. return fw.catacomb.Add(poller) }
go
func (fw *Firewaller) startRelationPoller(relationKey, remoteAppName string, relationReady chan remoteRelationInfo) error { poller := &remoteRelationPoller{ fw: fw, relationTag: names.NewRelationTag(relationKey), applicationTag: names.NewApplicationTag(remoteAppName), relationReady: relationReady, } err := catacomb.Invoke(catacomb.Plan{ Site: &poller.catacomb, Work: poller.pollLoop, }) if err != nil { return errors.Trace(err) } // register poller with the firewaller's catacomb. return fw.catacomb.Add(poller) }
[ "func", "(", "fw", "*", "Firewaller", ")", "startRelationPoller", "(", "relationKey", ",", "remoteAppName", "string", ",", "relationReady", "chan", "remoteRelationInfo", ")", "error", "{", "poller", ":=", "&", "remoteRelationPoller", "{", "fw", ":", "fw", ",", "relationTag", ":", "names", ".", "NewRelationTag", "(", "relationKey", ")", ",", "applicationTag", ":", "names", ".", "NewApplicationTag", "(", "remoteAppName", ")", ",", "relationReady", ":", "relationReady", ",", "}", "\n\n", "err", ":=", "catacomb", ".", "Invoke", "(", "catacomb", ".", "Plan", "{", "Site", ":", "&", "poller", ".", "catacomb", ",", "Work", ":", "poller", ".", "pollLoop", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// register poller with the firewaller's catacomb.", "return", "fw", ".", "catacomb", ".", "Add", "(", "poller", ")", "\n", "}" ]
// startRelationPoller creates a new worker which waits until a remote // relation is registered in both models.
[ "startRelationPoller", "creates", "a", "new", "worker", "which", "waits", "until", "a", "remote", "relation", "is", "registered", "in", "both", "models", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L1571-L1589
156,449
juju/juju
worker/firewaller/firewaller.go
pollLoop
func (p *remoteRelationPoller) pollLoop() error { logger.Debugf("polling for relation %v on %v to be ready", p.relationTag, p.applicationTag) for { select { case <-p.catacomb.Dying(): return p.catacomb.ErrDying() case <-p.fw.pollClock.After(3 * time.Second): // Relation is exported with the consuming model UUID. relToken, err := p.fw.remoteRelationsApi.GetToken(p.relationTag) if err != nil { continue } logger.Debugf("token %v for relation id: %v in model %v", relToken, p.relationTag.Id(), p.fw.modelUUID) // Application is exported with the offering model UUID. appToken, err := p.fw.remoteRelationsApi.GetToken(p.applicationTag) if err != nil { continue } logger.Debugf("token %v for application id: %v", appToken, p.applicationTag.Id()) // relation and application are ready. relationInfo := remoteRelationInfo{ relationToken: relToken, applicationToken: appToken, } select { case <-p.catacomb.Dying(): return p.catacomb.ErrDying() case p.relationReady <- relationInfo: } return nil } } }
go
func (p *remoteRelationPoller) pollLoop() error { logger.Debugf("polling for relation %v on %v to be ready", p.relationTag, p.applicationTag) for { select { case <-p.catacomb.Dying(): return p.catacomb.ErrDying() case <-p.fw.pollClock.After(3 * time.Second): // Relation is exported with the consuming model UUID. relToken, err := p.fw.remoteRelationsApi.GetToken(p.relationTag) if err != nil { continue } logger.Debugf("token %v for relation id: %v in model %v", relToken, p.relationTag.Id(), p.fw.modelUUID) // Application is exported with the offering model UUID. appToken, err := p.fw.remoteRelationsApi.GetToken(p.applicationTag) if err != nil { continue } logger.Debugf("token %v for application id: %v", appToken, p.applicationTag.Id()) // relation and application are ready. relationInfo := remoteRelationInfo{ relationToken: relToken, applicationToken: appToken, } select { case <-p.catacomb.Dying(): return p.catacomb.ErrDying() case p.relationReady <- relationInfo: } return nil } } }
[ "func", "(", "p", "*", "remoteRelationPoller", ")", "pollLoop", "(", ")", "error", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "p", ".", "relationTag", ",", "p", ".", "applicationTag", ")", "\n", "for", "{", "select", "{", "case", "<-", "p", ".", "catacomb", ".", "Dying", "(", ")", ":", "return", "p", ".", "catacomb", ".", "ErrDying", "(", ")", "\n", "case", "<-", "p", ".", "fw", ".", "pollClock", ".", "After", "(", "3", "*", "time", ".", "Second", ")", ":", "// Relation is exported with the consuming model UUID.", "relToken", ",", "err", ":=", "p", ".", "fw", ".", "remoteRelationsApi", ".", "GetToken", "(", "p", ".", "relationTag", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "relToken", ",", "p", ".", "relationTag", ".", "Id", "(", ")", ",", "p", ".", "fw", ".", "modelUUID", ")", "\n\n", "// Application is exported with the offering model UUID.", "appToken", ",", "err", ":=", "p", ".", "fw", ".", "remoteRelationsApi", ".", "GetToken", "(", "p", ".", "applicationTag", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "appToken", ",", "p", ".", "applicationTag", ".", "Id", "(", ")", ")", "\n\n", "// relation and application are ready.", "relationInfo", ":=", "remoteRelationInfo", "{", "relationToken", ":", "relToken", ",", "applicationToken", ":", "appToken", ",", "}", "\n", "select", "{", "case", "<-", "p", ".", "catacomb", ".", "Dying", "(", ")", ":", "return", "p", ".", "catacomb", ".", "ErrDying", "(", ")", "\n", "case", "p", ".", "relationReady", "<-", "relationInfo", ":", "}", "\n", "return", "nil", "\n", "}", "\n", "}", "\n", "}" ]
// pollLoop waits for a remote relation to be registered. // It does this by waiting for the relation and app tokens to be created.
[ "pollLoop", "waits", "for", "a", "remote", "relation", "to", "be", "registered", ".", "It", "does", "this", "by", "waiting", "for", "the", "relation", "and", "app", "tokens", "to", "be", "created", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/firewaller/firewaller.go#L1593-L1627
156,450
juju/juju
cmd/juju/application/bundle.go
composeBundle
func composeBundle(data *charm.BundleData, ctx *cmd.Context, bundleDir string, overlayFileNames []string) error { if err := processBundleOverlay(data, overlayFileNames...); err != nil { return errors.Annotate(err, "unable to process overlays") } if bundleDir == "" { bundleDir = ctx.Dir } if err := processBundleIncludes(bundleDir, data); err != nil { return errors.Annotate(err, "unable to process includes") } return nil }
go
func composeBundle(data *charm.BundleData, ctx *cmd.Context, bundleDir string, overlayFileNames []string) error { if err := processBundleOverlay(data, overlayFileNames...); err != nil { return errors.Annotate(err, "unable to process overlays") } if bundleDir == "" { bundleDir = ctx.Dir } if err := processBundleIncludes(bundleDir, data); err != nil { return errors.Annotate(err, "unable to process includes") } return nil }
[ "func", "composeBundle", "(", "data", "*", "charm", ".", "BundleData", ",", "ctx", "*", "cmd", ".", "Context", ",", "bundleDir", "string", ",", "overlayFileNames", "[", "]", "string", ")", "error", "{", "if", "err", ":=", "processBundleOverlay", "(", "data", ",", "overlayFileNames", "...", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "bundleDir", "==", "\"", "\"", "{", "bundleDir", "=", "ctx", ".", "Dir", "\n", "}", "\n", "if", "err", ":=", "processBundleIncludes", "(", "bundleDir", ",", "data", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// composeBundle adds the overlays and bundle includes into the passed bundle // data struct.
[ "composeBundle", "adds", "the", "overlays", "and", "bundle", "includes", "into", "the", "passed", "bundle", "data", "struct", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/bundle.go#L64-L75
156,451
juju/juju
cmd/juju/application/bundle.go
deployBundle
func deployBundle( bundleDir string, data *charm.BundleData, bundleURL *charm.URL, bundleOverlayFile []string, channel csparams.Channel, apiRoot DeployAPI, ctx *cmd.Context, bundleStorage map[string]map[string]storage.Constraints, bundleDevices map[string]map[string]devices.Constraints, dryRun bool, useExistingMachines bool, bundleMachines map[string]string, ) (map[*charm.URL]*macaroon.Macaroon, error) { if err := composeBundle(data, ctx, bundleDir, bundleOverlayFile); err != nil { return nil, errors.Trace(err) } if err := verifyBundle(data, bundleDir); err != nil { return nil, errors.Trace(err) } // TODO: move bundle parsing and checking into the handler. h := makeBundleHandler(dryRun, bundleDir, channel, apiRoot, ctx, data, bundleURL, bundleStorage, bundleDevices) if err := h.makeModel(useExistingMachines, bundleMachines); err != nil { return nil, errors.Trace(err) } if err := h.resolveCharmsAndEndpoints(); err != nil { return nil, errors.Trace(err) } if err := h.getChanges(); err != nil { return nil, errors.Trace(err) } if err := h.handleChanges(); err != nil { return nil, errors.Trace(err) } return h.macaroons, nil }
go
func deployBundle( bundleDir string, data *charm.BundleData, bundleURL *charm.URL, bundleOverlayFile []string, channel csparams.Channel, apiRoot DeployAPI, ctx *cmd.Context, bundleStorage map[string]map[string]storage.Constraints, bundleDevices map[string]map[string]devices.Constraints, dryRun bool, useExistingMachines bool, bundleMachines map[string]string, ) (map[*charm.URL]*macaroon.Macaroon, error) { if err := composeBundle(data, ctx, bundleDir, bundleOverlayFile); err != nil { return nil, errors.Trace(err) } if err := verifyBundle(data, bundleDir); err != nil { return nil, errors.Trace(err) } // TODO: move bundle parsing and checking into the handler. h := makeBundleHandler(dryRun, bundleDir, channel, apiRoot, ctx, data, bundleURL, bundleStorage, bundleDevices) if err := h.makeModel(useExistingMachines, bundleMachines); err != nil { return nil, errors.Trace(err) } if err := h.resolveCharmsAndEndpoints(); err != nil { return nil, errors.Trace(err) } if err := h.getChanges(); err != nil { return nil, errors.Trace(err) } if err := h.handleChanges(); err != nil { return nil, errors.Trace(err) } return h.macaroons, nil }
[ "func", "deployBundle", "(", "bundleDir", "string", ",", "data", "*", "charm", ".", "BundleData", ",", "bundleURL", "*", "charm", ".", "URL", ",", "bundleOverlayFile", "[", "]", "string", ",", "channel", "csparams", ".", "Channel", ",", "apiRoot", "DeployAPI", ",", "ctx", "*", "cmd", ".", "Context", ",", "bundleStorage", "map", "[", "string", "]", "map", "[", "string", "]", "storage", ".", "Constraints", ",", "bundleDevices", "map", "[", "string", "]", "map", "[", "string", "]", "devices", ".", "Constraints", ",", "dryRun", "bool", ",", "useExistingMachines", "bool", ",", "bundleMachines", "map", "[", "string", "]", "string", ",", ")", "(", "map", "[", "*", "charm", ".", "URL", "]", "*", "macaroon", ".", "Macaroon", ",", "error", ")", "{", "if", "err", ":=", "composeBundle", "(", "data", ",", "ctx", ",", "bundleDir", ",", "bundleOverlayFile", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "verifyBundle", "(", "data", ",", "bundleDir", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// TODO: move bundle parsing and checking into the handler.", "h", ":=", "makeBundleHandler", "(", "dryRun", ",", "bundleDir", ",", "channel", ",", "apiRoot", ",", "ctx", ",", "data", ",", "bundleURL", ",", "bundleStorage", ",", "bundleDevices", ")", "\n", "if", "err", ":=", "h", ".", "makeModel", "(", "useExistingMachines", ",", "bundleMachines", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "h", ".", "resolveCharmsAndEndpoints", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "h", ".", "getChanges", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "h", ".", "handleChanges", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "h", ".", "macaroons", ",", "nil", "\n\n", "}" ]
// deployBundle deploys the given bundle data using the given API client and // charm store client. The deployment is not transactional, and its progress is // notified using the given deployment logger.
[ "deployBundle", "deploys", "the", "given", "bundle", "data", "using", "the", "given", "API", "client", "and", "charm", "store", "client", ".", "The", "deployment", "is", "not", "transactional", "and", "its", "progress", "is", "notified", "using", "the", "given", "deployment", "logger", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/bundle.go#L110-L148
156,452
juju/juju
cmd/juju/application/bundle.go
addCharm
func (h *bundleHandler) addCharm(change *bundlechanges.AddCharmChange) error { if h.dryRun { return nil } id := change.Id() p := change.Params // First attempt to interpret as a local path. if h.isLocalCharm(p.Charm) { charmPath := p.Charm if !filepath.IsAbs(charmPath) { charmPath = filepath.Join(h.bundleDir, charmPath) } series := p.Series if series == "" { series = h.data.Series } ch, curl, err := charmrepo.NewCharmAtPath(charmPath, series) if err != nil && !os.IsNotExist(err) { return errors.Annotatef(err, "cannot deploy local charm at %q", charmPath) } if err == nil { if err := lxdprofile.ValidateLXDProfile(lxdCharmProfiler{ Charm: ch, }); err != nil { return errors.Annotatef(err, "cannot deploy local charm at %q", charmPath) } if curl, err = h.api.AddLocalCharm(curl, ch, false); err != nil { return err } logger.Debugf("added charm %s", curl) h.results[id] = curl.String() return nil } } // Not a local charm, so grab from the store. ch, err := charm.ParseURL(p.Charm) if err != nil { return errors.Trace(err) } url, channel, _, err := resolveCharm(h.api.ResolveWithChannel, ch) if err != nil { return errors.Annotatef(err, "cannot resolve URL %q", p.Charm) } if url.Series == "bundle" { return errors.Errorf("expected charm URL, got bundle URL %q", p.Charm) } var macaroon *macaroon.Macaroon url, macaroon, err = addCharmFromURL(h.api, url, channel, false) if err != nil { return errors.Annotatef(err, "cannot add charm %q", p.Charm) } logger.Debugf("added charm %s", url) h.results[id] = url.String() h.macaroons[url] = macaroon h.channels[url] = channel return nil }
go
func (h *bundleHandler) addCharm(change *bundlechanges.AddCharmChange) error { if h.dryRun { return nil } id := change.Id() p := change.Params // First attempt to interpret as a local path. if h.isLocalCharm(p.Charm) { charmPath := p.Charm if !filepath.IsAbs(charmPath) { charmPath = filepath.Join(h.bundleDir, charmPath) } series := p.Series if series == "" { series = h.data.Series } ch, curl, err := charmrepo.NewCharmAtPath(charmPath, series) if err != nil && !os.IsNotExist(err) { return errors.Annotatef(err, "cannot deploy local charm at %q", charmPath) } if err == nil { if err := lxdprofile.ValidateLXDProfile(lxdCharmProfiler{ Charm: ch, }); err != nil { return errors.Annotatef(err, "cannot deploy local charm at %q", charmPath) } if curl, err = h.api.AddLocalCharm(curl, ch, false); err != nil { return err } logger.Debugf("added charm %s", curl) h.results[id] = curl.String() return nil } } // Not a local charm, so grab from the store. ch, err := charm.ParseURL(p.Charm) if err != nil { return errors.Trace(err) } url, channel, _, err := resolveCharm(h.api.ResolveWithChannel, ch) if err != nil { return errors.Annotatef(err, "cannot resolve URL %q", p.Charm) } if url.Series == "bundle" { return errors.Errorf("expected charm URL, got bundle URL %q", p.Charm) } var macaroon *macaroon.Macaroon url, macaroon, err = addCharmFromURL(h.api, url, channel, false) if err != nil { return errors.Annotatef(err, "cannot add charm %q", p.Charm) } logger.Debugf("added charm %s", url) h.results[id] = url.String() h.macaroons[url] = macaroon h.channels[url] = channel return nil }
[ "func", "(", "h", "*", "bundleHandler", ")", "addCharm", "(", "change", "*", "bundlechanges", ".", "AddCharmChange", ")", "error", "{", "if", "h", ".", "dryRun", "{", "return", "nil", "\n", "}", "\n", "id", ":=", "change", ".", "Id", "(", ")", "\n", "p", ":=", "change", ".", "Params", "\n", "// First attempt to interpret as a local path.", "if", "h", ".", "isLocalCharm", "(", "p", ".", "Charm", ")", "{", "charmPath", ":=", "p", ".", "Charm", "\n", "if", "!", "filepath", ".", "IsAbs", "(", "charmPath", ")", "{", "charmPath", "=", "filepath", ".", "Join", "(", "h", ".", "bundleDir", ",", "charmPath", ")", "\n", "}", "\n\n", "series", ":=", "p", ".", "Series", "\n", "if", "series", "==", "\"", "\"", "{", "series", "=", "h", ".", "data", ".", "Series", "\n", "}", "\n", "ch", ",", "curl", ",", "err", ":=", "charmrepo", ".", "NewCharmAtPath", "(", "charmPath", ",", "series", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "charmPath", ")", "\n", "}", "\n", "if", "err", "==", "nil", "{", "if", "err", ":=", "lxdprofile", ".", "ValidateLXDProfile", "(", "lxdCharmProfiler", "{", "Charm", ":", "ch", ",", "}", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "charmPath", ")", "\n", "}", "\n", "if", "curl", ",", "err", "=", "h", ".", "api", ".", "AddLocalCharm", "(", "curl", ",", "ch", ",", "false", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "curl", ")", "\n", "h", ".", "results", "[", "id", "]", "=", "curl", ".", "String", "(", ")", "\n", "return", "nil", "\n", "}", "\n", "}", "\n\n", "// Not a local charm, so grab from the store.", "ch", ",", "err", ":=", "charm", ".", "ParseURL", "(", "p", ".", "Charm", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "url", ",", "channel", ",", "_", ",", "err", ":=", "resolveCharm", "(", "h", ".", "api", ".", "ResolveWithChannel", ",", "ch", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "p", ".", "Charm", ")", "\n", "}", "\n", "if", "url", ".", "Series", "==", "\"", "\"", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "p", ".", "Charm", ")", "\n", "}", "\n", "var", "macaroon", "*", "macaroon", ".", "Macaroon", "\n", "url", ",", "macaroon", ",", "err", "=", "addCharmFromURL", "(", "h", ".", "api", ",", "url", ",", "channel", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "p", ".", "Charm", ")", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "url", ")", "\n", "h", ".", "results", "[", "id", "]", "=", "url", ".", "String", "(", ")", "\n", "h", ".", "macaroons", "[", "url", "]", "=", "macaroon", "\n", "h", ".", "channels", "[", "url", "]", "=", "channel", "\n", "return", "nil", "\n", "}" ]
// addCharm adds a charm to the environment.
[ "addCharm", "adds", "a", "charm", "to", "the", "environment", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/bundle.go#L439-L498
156,453
juju/juju
cmd/juju/application/bundle.go
scaleApplication
func (h *bundleHandler) scaleApplication(change *bundlechanges.ScaleChange) error { if h.dryRun { return nil } p := change.Params result, err := h.api.ScaleApplication(application.ScaleApplicationParams{ ApplicationName: p.Application, Scale: p.Scale, }) if err == nil && result.Error != nil { err = result.Error } if err != nil { return errors.Annotatef(err, "cannot scale application %q", p.Application) } return nil }
go
func (h *bundleHandler) scaleApplication(change *bundlechanges.ScaleChange) error { if h.dryRun { return nil } p := change.Params result, err := h.api.ScaleApplication(application.ScaleApplicationParams{ ApplicationName: p.Application, Scale: p.Scale, }) if err == nil && result.Error != nil { err = result.Error } if err != nil { return errors.Annotatef(err, "cannot scale application %q", p.Application) } return nil }
[ "func", "(", "h", "*", "bundleHandler", ")", "scaleApplication", "(", "change", "*", "bundlechanges", ".", "ScaleChange", ")", "error", "{", "if", "h", ".", "dryRun", "{", "return", "nil", "\n", "}", "\n\n", "p", ":=", "change", ".", "Params", "\n\n", "result", ",", "err", ":=", "h", ".", "api", ".", "ScaleApplication", "(", "application", ".", "ScaleApplicationParams", "{", "ApplicationName", ":", "p", ".", "Application", ",", "Scale", ":", "p", ".", "Scale", ",", "}", ")", "\n", "if", "err", "==", "nil", "&&", "result", ".", "Error", "!=", "nil", "{", "err", "=", "result", ".", "Error", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "p", ".", "Application", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// scaleApplication updates the number of units for an application.
[ "scaleApplication", "updates", "the", "number", "of", "units", "for", "an", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/bundle.go#L675-L693
156,454
juju/juju
cmd/juju/application/bundle.go
addRelation
func (h *bundleHandler) addRelation(change *bundlechanges.AddRelationChange) error { if h.dryRun { return nil } p := change.Params ep1 := resolveRelation(p.Endpoint1, h.results) ep2 := resolveRelation(p.Endpoint2, h.results) // TODO(wallyworld) - CMR support in bundles _, err := h.api.AddRelation([]string{ep1, ep2}, nil) if err != nil { // TODO(thumper): remove this error check when we add resolving // implicit relations. if params.IsCodeAlreadyExists(err) { return nil } return errors.Annotatef(err, "cannot add relation between %q and %q", ep1, ep2) } return nil }
go
func (h *bundleHandler) addRelation(change *bundlechanges.AddRelationChange) error { if h.dryRun { return nil } p := change.Params ep1 := resolveRelation(p.Endpoint1, h.results) ep2 := resolveRelation(p.Endpoint2, h.results) // TODO(wallyworld) - CMR support in bundles _, err := h.api.AddRelation([]string{ep1, ep2}, nil) if err != nil { // TODO(thumper): remove this error check when we add resolving // implicit relations. if params.IsCodeAlreadyExists(err) { return nil } return errors.Annotatef(err, "cannot add relation between %q and %q", ep1, ep2) } return nil }
[ "func", "(", "h", "*", "bundleHandler", ")", "addRelation", "(", "change", "*", "bundlechanges", ".", "AddRelationChange", ")", "error", "{", "if", "h", ".", "dryRun", "{", "return", "nil", "\n", "}", "\n", "p", ":=", "change", ".", "Params", "\n", "ep1", ":=", "resolveRelation", "(", "p", ".", "Endpoint1", ",", "h", ".", "results", ")", "\n", "ep2", ":=", "resolveRelation", "(", "p", ".", "Endpoint2", ",", "h", ".", "results", ")", "\n", "// TODO(wallyworld) - CMR support in bundles", "_", ",", "err", ":=", "h", ".", "api", ".", "AddRelation", "(", "[", "]", "string", "{", "ep1", ",", "ep2", "}", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "// TODO(thumper): remove this error check when we add resolving", "// implicit relations.", "if", "params", ".", "IsCodeAlreadyExists", "(", "err", ")", "{", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "ep1", ",", "ep2", ")", "\n\n", "}", "\n", "return", "nil", "\n", "}" ]
// addRelation creates a relationship between two applications.
[ "addRelation", "creates", "a", "relationship", "between", "two", "applications", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/bundle.go#L787-L806
156,455
juju/juju
cmd/juju/application/bundle.go
addUnit
func (h *bundleHandler) addUnit(change *bundlechanges.AddUnitChange) error { if h.dryRun { return nil } p := change.Params applicationName := resolve(p.Application, h.results) var err error var placementArg []*instance.Placement targetMachine := p.To if targetMachine != "" { logger.Debugf("addUnit: placement %q", targetMachine) // The placement maybe "container:machine" container := "" if parts := strings.Split(targetMachine, ":"); len(parts) > 1 { container = parts[0] targetMachine = parts[1] } targetMachine, err = h.resolveMachine(targetMachine) if err != nil { // Should never happen. return errors.Annotatef(err, "cannot retrieve placement for %q unit", applicationName) } directive := targetMachine if container != "" { directive = container + ":" + directive } placement, err := parsePlacement(directive) if err != nil { return errors.Errorf("invalid --to parameter %q", directive) } logger.Debugf(" resolved: placement %q", directive) placementArg = append(placementArg, placement) } r, err := h.api.AddUnits(application.AddUnitsParams{ ApplicationName: applicationName, NumUnits: 1, Placement: placementArg, }) if err != nil { return errors.Annotatef(err, "cannot add unit for application %q", applicationName) } unit := r[0] if targetMachine == "" { logger.Debugf("added %s unit to new machine", unit) // In this case, the unit name is stored in results instead of the // machine id, which is lazily evaluated later only if required. // This way we avoid waiting for watcher updates. h.results[change.Id()] = unit } else { logger.Debugf("added %s unit to new machine", unit) h.results[change.Id()] = targetMachine } // Note that the targetMachine can be empty for now, resulting in a partially // incomplete unit status. That's ok as the missing info is provided later // when it is required. h.unitStatus[unit] = targetMachine return nil }
go
func (h *bundleHandler) addUnit(change *bundlechanges.AddUnitChange) error { if h.dryRun { return nil } p := change.Params applicationName := resolve(p.Application, h.results) var err error var placementArg []*instance.Placement targetMachine := p.To if targetMachine != "" { logger.Debugf("addUnit: placement %q", targetMachine) // The placement maybe "container:machine" container := "" if parts := strings.Split(targetMachine, ":"); len(parts) > 1 { container = parts[0] targetMachine = parts[1] } targetMachine, err = h.resolveMachine(targetMachine) if err != nil { // Should never happen. return errors.Annotatef(err, "cannot retrieve placement for %q unit", applicationName) } directive := targetMachine if container != "" { directive = container + ":" + directive } placement, err := parsePlacement(directive) if err != nil { return errors.Errorf("invalid --to parameter %q", directive) } logger.Debugf(" resolved: placement %q", directive) placementArg = append(placementArg, placement) } r, err := h.api.AddUnits(application.AddUnitsParams{ ApplicationName: applicationName, NumUnits: 1, Placement: placementArg, }) if err != nil { return errors.Annotatef(err, "cannot add unit for application %q", applicationName) } unit := r[0] if targetMachine == "" { logger.Debugf("added %s unit to new machine", unit) // In this case, the unit name is stored in results instead of the // machine id, which is lazily evaluated later only if required. // This way we avoid waiting for watcher updates. h.results[change.Id()] = unit } else { logger.Debugf("added %s unit to new machine", unit) h.results[change.Id()] = targetMachine } // Note that the targetMachine can be empty for now, resulting in a partially // incomplete unit status. That's ok as the missing info is provided later // when it is required. h.unitStatus[unit] = targetMachine return nil }
[ "func", "(", "h", "*", "bundleHandler", ")", "addUnit", "(", "change", "*", "bundlechanges", ".", "AddUnitChange", ")", "error", "{", "if", "h", ".", "dryRun", "{", "return", "nil", "\n", "}", "\n\n", "p", ":=", "change", ".", "Params", "\n", "applicationName", ":=", "resolve", "(", "p", ".", "Application", ",", "h", ".", "results", ")", "\n", "var", "err", "error", "\n", "var", "placementArg", "[", "]", "*", "instance", ".", "Placement", "\n", "targetMachine", ":=", "p", ".", "To", "\n", "if", "targetMachine", "!=", "\"", "\"", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "targetMachine", ")", "\n", "// The placement maybe \"container:machine\"", "container", ":=", "\"", "\"", "\n", "if", "parts", ":=", "strings", ".", "Split", "(", "targetMachine", ",", "\"", "\"", ")", ";", "len", "(", "parts", ")", ">", "1", "{", "container", "=", "parts", "[", "0", "]", "\n", "targetMachine", "=", "parts", "[", "1", "]", "\n", "}", "\n", "targetMachine", ",", "err", "=", "h", ".", "resolveMachine", "(", "targetMachine", ")", "\n", "if", "err", "!=", "nil", "{", "// Should never happen.", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "applicationName", ")", "\n", "}", "\n", "directive", ":=", "targetMachine", "\n", "if", "container", "!=", "\"", "\"", "{", "directive", "=", "container", "+", "\"", "\"", "+", "directive", "\n", "}", "\n", "placement", ",", "err", ":=", "parsePlacement", "(", "directive", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "directive", ")", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "directive", ")", "\n", "placementArg", "=", "append", "(", "placementArg", ",", "placement", ")", "\n", "}", "\n", "r", ",", "err", ":=", "h", ".", "api", ".", "AddUnits", "(", "application", ".", "AddUnitsParams", "{", "ApplicationName", ":", "applicationName", ",", "NumUnits", ":", "1", ",", "Placement", ":", "placementArg", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "applicationName", ")", "\n", "}", "\n", "unit", ":=", "r", "[", "0", "]", "\n", "if", "targetMachine", "==", "\"", "\"", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "unit", ")", "\n", "// In this case, the unit name is stored in results instead of the", "// machine id, which is lazily evaluated later only if required.", "// This way we avoid waiting for watcher updates.", "h", ".", "results", "[", "change", ".", "Id", "(", ")", "]", "=", "unit", "\n", "}", "else", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "unit", ")", "\n", "h", ".", "results", "[", "change", ".", "Id", "(", ")", "]", "=", "targetMachine", "\n", "}", "\n\n", "// Note that the targetMachine can be empty for now, resulting in a partially", "// incomplete unit status. That's ok as the missing info is provided later", "// when it is required.", "h", ".", "unitStatus", "[", "unit", "]", "=", "targetMachine", "\n", "return", "nil", "\n", "}" ]
// addUnit adds a single unit to an application already present in the environment.
[ "addUnit", "adds", "a", "single", "unit", "to", "an", "application", "already", "present", "in", "the", "environment", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/bundle.go#L809-L868
156,456
juju/juju
cmd/juju/application/bundle.go
upgradeCharm
func (h *bundleHandler) upgradeCharm(change *bundlechanges.UpgradeCharmChange) error { if h.dryRun { return nil } p := change.Params cURL, err := charm.ParseURL(resolve(p.Charm, h.results)) if err != nil { return errors.Trace(err) } chID := charmstore.CharmID{ URL: cURL, Channel: h.channels[cURL], } macaroon := h.macaroons[cURL] meta, err := getMetaResources(cURL, h.api) if err != nil { return errors.Trace(err) } resources := h.makeResourceMap(meta, p.Resources, p.LocalResources) resourceLister, err := resourceadapters.NewAPIClient(h.api) if err != nil { return errors.Trace(err) } filtered, err := getUpgradeResources(resourceLister, p.Application, resources, meta) if err != nil { return errors.Trace(err) } var resNames2IDs map[string]string if len(filtered) != 0 { resNames2IDs, err = resourceadapters.DeployResources( p.Application, chID, macaroon, resources, filtered, h.api, ) if err != nil { return errors.Trace(err) } } cfg := application.SetCharmConfig{ ApplicationName: p.Application, CharmID: chID, ResourceIDs: resNames2IDs, } // Bundles only ever deal with the current generation. if err := h.api.SetCharm(model.GenerationMaster, cfg); err != nil { return errors.Trace(err) } h.writeAddedResources(resNames2IDs) return nil }
go
func (h *bundleHandler) upgradeCharm(change *bundlechanges.UpgradeCharmChange) error { if h.dryRun { return nil } p := change.Params cURL, err := charm.ParseURL(resolve(p.Charm, h.results)) if err != nil { return errors.Trace(err) } chID := charmstore.CharmID{ URL: cURL, Channel: h.channels[cURL], } macaroon := h.macaroons[cURL] meta, err := getMetaResources(cURL, h.api) if err != nil { return errors.Trace(err) } resources := h.makeResourceMap(meta, p.Resources, p.LocalResources) resourceLister, err := resourceadapters.NewAPIClient(h.api) if err != nil { return errors.Trace(err) } filtered, err := getUpgradeResources(resourceLister, p.Application, resources, meta) if err != nil { return errors.Trace(err) } var resNames2IDs map[string]string if len(filtered) != 0 { resNames2IDs, err = resourceadapters.DeployResources( p.Application, chID, macaroon, resources, filtered, h.api, ) if err != nil { return errors.Trace(err) } } cfg := application.SetCharmConfig{ ApplicationName: p.Application, CharmID: chID, ResourceIDs: resNames2IDs, } // Bundles only ever deal with the current generation. if err := h.api.SetCharm(model.GenerationMaster, cfg); err != nil { return errors.Trace(err) } h.writeAddedResources(resNames2IDs) return nil }
[ "func", "(", "h", "*", "bundleHandler", ")", "upgradeCharm", "(", "change", "*", "bundlechanges", ".", "UpgradeCharmChange", ")", "error", "{", "if", "h", ".", "dryRun", "{", "return", "nil", "\n", "}", "\n\n", "p", ":=", "change", ".", "Params", "\n", "cURL", ",", "err", ":=", "charm", ".", "ParseURL", "(", "resolve", "(", "p", ".", "Charm", ",", "h", ".", "results", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "chID", ":=", "charmstore", ".", "CharmID", "{", "URL", ":", "cURL", ",", "Channel", ":", "h", ".", "channels", "[", "cURL", "]", ",", "}", "\n", "macaroon", ":=", "h", ".", "macaroons", "[", "cURL", "]", "\n\n", "meta", ",", "err", ":=", "getMetaResources", "(", "cURL", ",", "h", ".", "api", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "resources", ":=", "h", ".", "makeResourceMap", "(", "meta", ",", "p", ".", "Resources", ",", "p", ".", "LocalResources", ")", "\n\n", "resourceLister", ",", "err", ":=", "resourceadapters", ".", "NewAPIClient", "(", "h", ".", "api", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "filtered", ",", "err", ":=", "getUpgradeResources", "(", "resourceLister", ",", "p", ".", "Application", ",", "resources", ",", "meta", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "var", "resNames2IDs", "map", "[", "string", "]", "string", "\n", "if", "len", "(", "filtered", ")", "!=", "0", "{", "resNames2IDs", ",", "err", "=", "resourceadapters", ".", "DeployResources", "(", "p", ".", "Application", ",", "chID", ",", "macaroon", ",", "resources", ",", "filtered", ",", "h", ".", "api", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "cfg", ":=", "application", ".", "SetCharmConfig", "{", "ApplicationName", ":", "p", ".", "Application", ",", "CharmID", ":", "chID", ",", "ResourceIDs", ":", "resNames2IDs", ",", "}", "\n", "// Bundles only ever deal with the current generation.", "if", "err", ":=", "h", ".", "api", ".", "SetCharm", "(", "model", ".", "GenerationMaster", ",", "cfg", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "h", ".", "writeAddedResources", "(", "resNames2IDs", ")", "\n\n", "return", "nil", "\n", "}" ]
// upgradeCharm will get the application to use the new charm.
[ "upgradeCharm", "will", "get", "the", "application", "to", "use", "the", "new", "charm", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/bundle.go#L871-L929
156,457
juju/juju
cmd/juju/application/bundle.go
setOptions
func (h *bundleHandler) setOptions(change *bundlechanges.SetOptionsChange) error { p := change.Params h.ctx.Verbosef(" setting options:") for key, value := range p.Options { switch value.(type) { case string: h.ctx.Verbosef(" %s: %q", key, value) default: h.ctx.Verbosef(" %s: %v", key, value) } } if h.dryRun { return nil } // We know that there wouldn't be any setOptions if there were no options. cfg, err := yaml.Marshal(map[string]map[string]interface{}{p.Application: p.Options}) if err != nil { return errors.Annotatef(err, "cannot marshal options for application %q", p.Application) } if err := h.api.Update(params.ApplicationUpdate{ ApplicationName: p.Application, SettingsYAML: string(cfg), Generation: model.GenerationMaster, }); err != nil { return errors.Annotatef(err, "cannot update options for application %q", p.Application) } return nil }
go
func (h *bundleHandler) setOptions(change *bundlechanges.SetOptionsChange) error { p := change.Params h.ctx.Verbosef(" setting options:") for key, value := range p.Options { switch value.(type) { case string: h.ctx.Verbosef(" %s: %q", key, value) default: h.ctx.Verbosef(" %s: %v", key, value) } } if h.dryRun { return nil } // We know that there wouldn't be any setOptions if there were no options. cfg, err := yaml.Marshal(map[string]map[string]interface{}{p.Application: p.Options}) if err != nil { return errors.Annotatef(err, "cannot marshal options for application %q", p.Application) } if err := h.api.Update(params.ApplicationUpdate{ ApplicationName: p.Application, SettingsYAML: string(cfg), Generation: model.GenerationMaster, }); err != nil { return errors.Annotatef(err, "cannot update options for application %q", p.Application) } return nil }
[ "func", "(", "h", "*", "bundleHandler", ")", "setOptions", "(", "change", "*", "bundlechanges", ".", "SetOptionsChange", ")", "error", "{", "p", ":=", "change", ".", "Params", "\n", "h", ".", "ctx", ".", "Verbosef", "(", "\"", "\"", ")", "\n", "for", "key", ",", "value", ":=", "range", "p", ".", "Options", "{", "switch", "value", ".", "(", "type", ")", "{", "case", "string", ":", "h", ".", "ctx", ".", "Verbosef", "(", "\"", "\"", ",", "key", ",", "value", ")", "\n", "default", ":", "h", ".", "ctx", ".", "Verbosef", "(", "\"", "\"", ",", "key", ",", "value", ")", "\n", "}", "\n", "}", "\n", "if", "h", ".", "dryRun", "{", "return", "nil", "\n", "}", "\n\n", "// We know that there wouldn't be any setOptions if there were no options.", "cfg", ",", "err", ":=", "yaml", ".", "Marshal", "(", "map", "[", "string", "]", "map", "[", "string", "]", "interface", "{", "}", "{", "p", ".", "Application", ":", "p", ".", "Options", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "p", ".", "Application", ")", "\n", "}", "\n\n", "if", "err", ":=", "h", ".", "api", ".", "Update", "(", "params", ".", "ApplicationUpdate", "{", "ApplicationName", ":", "p", ".", "Application", ",", "SettingsYAML", ":", "string", "(", "cfg", ")", ",", "Generation", ":", "model", ".", "GenerationMaster", ",", "}", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "p", ".", "Application", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// setOptions updates application configuration settings.
[ "setOptions", "updates", "application", "configuration", "settings", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/bundle.go#L932-L962
156,458
juju/juju
cmd/juju/application/bundle.go
setConstraints
func (h *bundleHandler) setConstraints(change *bundlechanges.SetConstraintsChange) error { if h.dryRun { return nil } p := change.Params // We know that p.Constraints is a valid constraints type due to the validation. cons, _ := constraints.Parse(p.Constraints) if err := h.api.SetConstraints(p.Application, cons); err != nil { // This should never happen, as the bundle is already verified. return errors.Annotatef(err, "cannot update constraints for application %q", p.Application) } return nil }
go
func (h *bundleHandler) setConstraints(change *bundlechanges.SetConstraintsChange) error { if h.dryRun { return nil } p := change.Params // We know that p.Constraints is a valid constraints type due to the validation. cons, _ := constraints.Parse(p.Constraints) if err := h.api.SetConstraints(p.Application, cons); err != nil { // This should never happen, as the bundle is already verified. return errors.Annotatef(err, "cannot update constraints for application %q", p.Application) } return nil }
[ "func", "(", "h", "*", "bundleHandler", ")", "setConstraints", "(", "change", "*", "bundlechanges", ".", "SetConstraintsChange", ")", "error", "{", "if", "h", ".", "dryRun", "{", "return", "nil", "\n", "}", "\n", "p", ":=", "change", ".", "Params", "\n", "// We know that p.Constraints is a valid constraints type due to the validation.", "cons", ",", "_", ":=", "constraints", ".", "Parse", "(", "p", ".", "Constraints", ")", "\n", "if", "err", ":=", "h", ".", "api", ".", "SetConstraints", "(", "p", ".", "Application", ",", "cons", ")", ";", "err", "!=", "nil", "{", "// This should never happen, as the bundle is already verified.", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "p", ".", "Application", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// setConstraints updates application constraints.
[ "setConstraints", "updates", "application", "constraints", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/bundle.go#L965-L978
156,459
juju/juju
cmd/juju/application/bundle.go
exposeApplication
func (h *bundleHandler) exposeApplication(change *bundlechanges.ExposeChange) error { if h.dryRun { return nil } application := resolve(change.Params.Application, h.results) if err := h.api.Expose(application); err != nil { return errors.Annotatef(err, "cannot expose application %s", application) } return nil }
go
func (h *bundleHandler) exposeApplication(change *bundlechanges.ExposeChange) error { if h.dryRun { return nil } application := resolve(change.Params.Application, h.results) if err := h.api.Expose(application); err != nil { return errors.Annotatef(err, "cannot expose application %s", application) } return nil }
[ "func", "(", "h", "*", "bundleHandler", ")", "exposeApplication", "(", "change", "*", "bundlechanges", ".", "ExposeChange", ")", "error", "{", "if", "h", ".", "dryRun", "{", "return", "nil", "\n", "}", "\n\n", "application", ":=", "resolve", "(", "change", ".", "Params", ".", "Application", ",", "h", ".", "results", ")", "\n", "if", "err", ":=", "h", ".", "api", ".", "Expose", "(", "application", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "application", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// exposeApplication exposes an application.
[ "exposeApplication", "exposes", "an", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/bundle.go#L981-L991
156,460
juju/juju
cmd/juju/application/bundle.go
setAnnotations
func (h *bundleHandler) setAnnotations(change *bundlechanges.SetAnnotationsChange) error { p := change.Params h.ctx.Verbosef(" setting annotations:") for key, value := range p.Annotations { h.ctx.Verbosef(" %s: %q", key, value) } if h.dryRun { return nil } eid := resolve(p.Id, h.results) var tag string switch p.EntityType { case bundlechanges.MachineType: tag = names.NewMachineTag(eid).String() case bundlechanges.ApplicationType: tag = names.NewApplicationTag(eid).String() default: return errors.Errorf("unexpected annotation entity type %q", p.EntityType) } result, err := h.api.SetAnnotation(map[string]map[string]string{tag: p.Annotations}) if err == nil && len(result) > 0 { err = result[0].Error } if err != nil { return errors.Annotatef(err, "cannot set annotations for %s %q", p.EntityType, eid) } return nil }
go
func (h *bundleHandler) setAnnotations(change *bundlechanges.SetAnnotationsChange) error { p := change.Params h.ctx.Verbosef(" setting annotations:") for key, value := range p.Annotations { h.ctx.Verbosef(" %s: %q", key, value) } if h.dryRun { return nil } eid := resolve(p.Id, h.results) var tag string switch p.EntityType { case bundlechanges.MachineType: tag = names.NewMachineTag(eid).String() case bundlechanges.ApplicationType: tag = names.NewApplicationTag(eid).String() default: return errors.Errorf("unexpected annotation entity type %q", p.EntityType) } result, err := h.api.SetAnnotation(map[string]map[string]string{tag: p.Annotations}) if err == nil && len(result) > 0 { err = result[0].Error } if err != nil { return errors.Annotatef(err, "cannot set annotations for %s %q", p.EntityType, eid) } return nil }
[ "func", "(", "h", "*", "bundleHandler", ")", "setAnnotations", "(", "change", "*", "bundlechanges", ".", "SetAnnotationsChange", ")", "error", "{", "p", ":=", "change", ".", "Params", "\n", "h", ".", "ctx", ".", "Verbosef", "(", "\"", "\"", ")", "\n", "for", "key", ",", "value", ":=", "range", "p", ".", "Annotations", "{", "h", ".", "ctx", ".", "Verbosef", "(", "\"", "\"", ",", "key", ",", "value", ")", "\n", "}", "\n", "if", "h", ".", "dryRun", "{", "return", "nil", "\n", "}", "\n", "eid", ":=", "resolve", "(", "p", ".", "Id", ",", "h", ".", "results", ")", "\n", "var", "tag", "string", "\n", "switch", "p", ".", "EntityType", "{", "case", "bundlechanges", ".", "MachineType", ":", "tag", "=", "names", ".", "NewMachineTag", "(", "eid", ")", ".", "String", "(", ")", "\n", "case", "bundlechanges", ".", "ApplicationType", ":", "tag", "=", "names", ".", "NewApplicationTag", "(", "eid", ")", ".", "String", "(", ")", "\n", "default", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "p", ".", "EntityType", ")", "\n", "}", "\n", "result", ",", "err", ":=", "h", ".", "api", ".", "SetAnnotation", "(", "map", "[", "string", "]", "map", "[", "string", "]", "string", "{", "tag", ":", "p", ".", "Annotations", "}", ")", "\n", "if", "err", "==", "nil", "&&", "len", "(", "result", ")", ">", "0", "{", "err", "=", "result", "[", "0", "]", ".", "Error", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "p", ".", "EntityType", ",", "eid", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// setAnnotations sets annotations for an application or a machine.
[ "setAnnotations", "sets", "annotations", "for", "an", "application", "or", "a", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/bundle.go#L994-L1021
156,461
juju/juju
cmd/juju/application/bundle.go
applicationsForMachineChange
func (h *bundleHandler) applicationsForMachineChange(changeId string) []string { applications := set.NewStrings() mainloop: for _, change := range h.changes { for _, required := range change.Requires() { if required != changeId { continue } switch change := change.(type) { case *bundlechanges.AddMachineChange: // The original machine is a container, and its parent is // another "addMachines" change. Search again using the // parent id. for _, application := range h.applicationsForMachineChange(change.Id()) { applications.Add(application) } continue mainloop case *bundlechanges.AddUnitChange: // We have found the "addUnit" change, which refers to a // application: now resolve the application holding the unit. application := resolve(change.Params.Application, h.results) applications.Add(application) continue mainloop case *bundlechanges.SetAnnotationsChange: // A machine change is always required to set machine // annotations, but this isn't the interesting change here. continue mainloop default: // Should never happen. panic(fmt.Sprintf("unexpected change %T", change)) } } } return applications.SortedValues() }
go
func (h *bundleHandler) applicationsForMachineChange(changeId string) []string { applications := set.NewStrings() mainloop: for _, change := range h.changes { for _, required := range change.Requires() { if required != changeId { continue } switch change := change.(type) { case *bundlechanges.AddMachineChange: // The original machine is a container, and its parent is // another "addMachines" change. Search again using the // parent id. for _, application := range h.applicationsForMachineChange(change.Id()) { applications.Add(application) } continue mainloop case *bundlechanges.AddUnitChange: // We have found the "addUnit" change, which refers to a // application: now resolve the application holding the unit. application := resolve(change.Params.Application, h.results) applications.Add(application) continue mainloop case *bundlechanges.SetAnnotationsChange: // A machine change is always required to set machine // annotations, but this isn't the interesting change here. continue mainloop default: // Should never happen. panic(fmt.Sprintf("unexpected change %T", change)) } } } return applications.SortedValues() }
[ "func", "(", "h", "*", "bundleHandler", ")", "applicationsForMachineChange", "(", "changeId", "string", ")", "[", "]", "string", "{", "applications", ":=", "set", ".", "NewStrings", "(", ")", "\n", "mainloop", ":", "for", "_", ",", "change", ":=", "range", "h", ".", "changes", "{", "for", "_", ",", "required", ":=", "range", "change", ".", "Requires", "(", ")", "{", "if", "required", "!=", "changeId", "{", "continue", "\n", "}", "\n", "switch", "change", ":=", "change", ".", "(", "type", ")", "{", "case", "*", "bundlechanges", ".", "AddMachineChange", ":", "// The original machine is a container, and its parent is", "// another \"addMachines\" change. Search again using the", "// parent id.", "for", "_", ",", "application", ":=", "range", "h", ".", "applicationsForMachineChange", "(", "change", ".", "Id", "(", ")", ")", "{", "applications", ".", "Add", "(", "application", ")", "\n", "}", "\n", "continue", "mainloop", "\n", "case", "*", "bundlechanges", ".", "AddUnitChange", ":", "// We have found the \"addUnit\" change, which refers to a", "// application: now resolve the application holding the unit.", "application", ":=", "resolve", "(", "change", ".", "Params", ".", "Application", ",", "h", ".", "results", ")", "\n", "applications", ".", "Add", "(", "application", ")", "\n", "continue", "mainloop", "\n", "case", "*", "bundlechanges", ".", "SetAnnotationsChange", ":", "// A machine change is always required to set machine", "// annotations, but this isn't the interesting change here.", "continue", "mainloop", "\n", "default", ":", "// Should never happen.", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "change", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "applications", ".", "SortedValues", "(", ")", "\n", "}" ]
// applicationsForMachineChange returns the names of the applications for which an // "addMachine" change is required, as adding machines is required to place // units, and units belong to applications. // Receive the id of the "addMachine" change.
[ "applicationsForMachineChange", "returns", "the", "names", "of", "the", "applications", "for", "which", "an", "addMachine", "change", "is", "required", "as", "adding", "machines", "is", "required", "to", "place", "units", "and", "units", "belong", "to", "applications", ".", "Receive", "the", "id", "of", "the", "addMachine", "change", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/bundle.go#L1027-L1061
156,462
juju/juju
cmd/juju/application/bundle.go
resolveMachine
func (h *bundleHandler) resolveMachine(placeholder string) (string, error) { logger.Debugf("resolveMachine(%q)", placeholder) machineOrUnit := resolve(placeholder, h.results) if !names.IsValidUnit(machineOrUnit) { return machineOrUnit, nil } for h.unitStatus[machineOrUnit] == "" { if err := h.updateUnitStatus(); err != nil { return "", errors.Annotate(err, "cannot resolve machine") } } return h.unitStatus[machineOrUnit], nil }
go
func (h *bundleHandler) resolveMachine(placeholder string) (string, error) { logger.Debugf("resolveMachine(%q)", placeholder) machineOrUnit := resolve(placeholder, h.results) if !names.IsValidUnit(machineOrUnit) { return machineOrUnit, nil } for h.unitStatus[machineOrUnit] == "" { if err := h.updateUnitStatus(); err != nil { return "", errors.Annotate(err, "cannot resolve machine") } } return h.unitStatus[machineOrUnit], nil }
[ "func", "(", "h", "*", "bundleHandler", ")", "resolveMachine", "(", "placeholder", "string", ")", "(", "string", ",", "error", ")", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "placeholder", ")", "\n", "machineOrUnit", ":=", "resolve", "(", "placeholder", ",", "h", ".", "results", ")", "\n", "if", "!", "names", ".", "IsValidUnit", "(", "machineOrUnit", ")", "{", "return", "machineOrUnit", ",", "nil", "\n", "}", "\n", "for", "h", ".", "unitStatus", "[", "machineOrUnit", "]", "==", "\"", "\"", "{", "if", "err", ":=", "h", ".", "updateUnitStatus", "(", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "h", ".", "unitStatus", "[", "machineOrUnit", "]", ",", "nil", "\n", "}" ]
// resolveMachine returns the machine id resolving the given unit or machine // placeholder.
[ "resolveMachine", "returns", "the", "machine", "id", "resolving", "the", "given", "unit", "or", "machine", "placeholder", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/bundle.go#L1100-L1112
156,463
juju/juju
cmd/juju/application/bundle.go
resolveRelation
func resolveRelation(e string, results map[string]string) string { parts := strings.SplitN(e, ":", 2) application := resolve(parts[0], results) if len(parts) == 1 { return application } return fmt.Sprintf("%s:%s", application, parts[1]) }
go
func resolveRelation(e string, results map[string]string) string { parts := strings.SplitN(e, ":", 2) application := resolve(parts[0], results) if len(parts) == 1 { return application } return fmt.Sprintf("%s:%s", application, parts[1]) }
[ "func", "resolveRelation", "(", "e", "string", ",", "results", "map", "[", "string", "]", "string", ")", "string", "{", "parts", ":=", "strings", ".", "SplitN", "(", "e", ",", "\"", "\"", ",", "2", ")", "\n", "application", ":=", "resolve", "(", "parts", "[", "0", "]", ",", "results", ")", "\n", "if", "len", "(", "parts", ")", "==", "1", "{", "return", "application", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "application", ",", "parts", "[", "1", "]", ")", "\n", "}" ]
// resolveRelation returns the relation name resolving the included application // placeholder.
[ "resolveRelation", "returns", "the", "relation", "name", "resolving", "the", "included", "application", "placeholder", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/bundle.go#L1124-L1131
156,464
juju/juju
cmd/juju/application/bundle.go
removeRelations
func removeRelations(data [][]string, appName string) [][]string { var result [][]string for _, relation := range data { // Keep the dud relation in the set, it will be caught by the bundle // verify code. if len(relation) == 2 { left, right := relation[0], relation[1] if left == appName || strings.HasPrefix(left, appName+":") || right == appName || strings.HasPrefix(right, appName+":") { continue } } result = append(result, relation) } return result }
go
func removeRelations(data [][]string, appName string) [][]string { var result [][]string for _, relation := range data { // Keep the dud relation in the set, it will be caught by the bundle // verify code. if len(relation) == 2 { left, right := relation[0], relation[1] if left == appName || strings.HasPrefix(left, appName+":") || right == appName || strings.HasPrefix(right, appName+":") { continue } } result = append(result, relation) } return result }
[ "func", "removeRelations", "(", "data", "[", "]", "[", "]", "string", ",", "appName", "string", ")", "[", "]", "[", "]", "string", "{", "var", "result", "[", "]", "[", "]", "string", "\n", "for", "_", ",", "relation", ":=", "range", "data", "{", "// Keep the dud relation in the set, it will be caught by the bundle", "// verify code.", "if", "len", "(", "relation", ")", "==", "2", "{", "left", ",", "right", ":=", "relation", "[", "0", "]", ",", "relation", "[", "1", "]", "\n", "if", "left", "==", "appName", "||", "strings", ".", "HasPrefix", "(", "left", ",", "appName", "+", "\"", "\"", ")", "||", "right", "==", "appName", "||", "strings", ".", "HasPrefix", "(", "right", ",", "appName", "+", "\"", "\"", ")", "{", "continue", "\n", "}", "\n", "}", "\n", "result", "=", "append", "(", "result", ",", "relation", ")", "\n", "}", "\n", "return", "result", "\n", "}" ]
// removeRelations removes any relation defined in data that references // the application appName.
[ "removeRelations", "removes", "any", "relation", "defined", "in", "data", "that", "references", "the", "application", "appName", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/bundle.go#L1424-L1439
156,465
juju/juju
cmd/juju/application/bundle.go
applicationConfigValue
func applicationConfigValue(key string, valueMap interface{}) (interface{}, error) { vm, ok := valueMap.(map[string]interface{}) if !ok { return nil, errors.Errorf("unexpected application config value type %T for key %q", valueMap, key) } source, found := vm["source"] if !found { return nil, errors.Errorf("missing application config value 'source' for key %q", key) } if source != "user" { return nil, nil } value, found := vm["value"] if !found { return nil, errors.Errorf("missing application config value 'value'") } return value, nil }
go
func applicationConfigValue(key string, valueMap interface{}) (interface{}, error) { vm, ok := valueMap.(map[string]interface{}) if !ok { return nil, errors.Errorf("unexpected application config value type %T for key %q", valueMap, key) } source, found := vm["source"] if !found { return nil, errors.Errorf("missing application config value 'source' for key %q", key) } if source != "user" { return nil, nil } value, found := vm["value"] if !found { return nil, errors.Errorf("missing application config value 'value'") } return value, nil }
[ "func", "applicationConfigValue", "(", "key", "string", ",", "valueMap", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "vm", ",", "ok", ":=", "valueMap", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "valueMap", ",", "key", ")", "\n", "}", "\n", "source", ",", "found", ":=", "vm", "[", "\"", "\"", "]", "\n", "if", "!", "found", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "key", ")", "\n", "}", "\n", "if", "source", "!=", "\"", "\"", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "value", ",", "found", ":=", "vm", "[", "\"", "\"", "]", "\n", "if", "!", "found", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "value", ",", "nil", "\n", "}" ]
// applicationConfigValue returns the value if it is not a default value. // If the value is a default value, nil is returned. // If there was issue determining the type or value, an error is returned.
[ "applicationConfigValue", "returns", "the", "value", "if", "it", "is", "not", "a", "default", "value", ".", "If", "the", "value", "is", "a", "default", "value", "nil", "is", "returned", ".", "If", "there", "was", "issue", "determining", "the", "type", "or", "value", "an", "error", "is", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/application/bundle.go#L1601-L1618
156,466
juju/juju
worker/storageprovisioner/volume_ops.go
attachVolumes
func attachVolumes(ctx *context, ops map[params.MachineStorageId]*attachVolumeOp) error { volumeAttachmentParams := make([]storage.VolumeAttachmentParams, 0, len(ops)) for _, op := range ops { volumeAttachmentParams = append(volumeAttachmentParams, op.args) } paramsBySource, volumeSources, err := volumeAttachmentParamsBySource( ctx.config.StorageDir, volumeAttachmentParams, ctx.config.Registry, ) if err != nil { return errors.Trace(err) } var reschedule []scheduleOp var volumeAttachments []storage.VolumeAttachment var statuses []params.EntityStatusArgs for sourceName, volumeAttachmentParams := range paramsBySource { logger.Debugf("attaching volumes: %+v", volumeAttachmentParams) volumeSource := volumeSources[sourceName] if volumeSource == nil { // The storage provider does not support dynamic // storage, there's nothing for the provisioner // to do here. continue } results, err := volumeSource.AttachVolumes(ctx.config.CloudCallContext, volumeAttachmentParams) if err != nil { return errors.Annotatef(err, "attaching volumes from source %q", sourceName) } for i, result := range results { p := volumeAttachmentParams[i] statuses = append(statuses, params.EntityStatusArgs{ Tag: p.Volume.String(), Status: status.Attached.String(), }) entityStatus := &statuses[len(statuses)-1] if result.Error != nil { // Reschedule the volume attachment. id := params.MachineStorageId{ MachineTag: p.Machine.String(), AttachmentTag: p.Volume.String(), } reschedule = append(reschedule, ops[id]) // Note: we keep the status as "attaching" to // indicate that we will retry. When we distinguish // between transient and permanent errors, we will // set the status to "error" for permanent errors. entityStatus.Status = status.Attaching.String() entityStatus.Info = result.Error.Error() logger.Debugf( "failed to attach %s to %s: %v", names.ReadableString(p.Volume), names.ReadableString(p.Machine), result.Error, ) continue } volumeAttachments = append(volumeAttachments, *result.VolumeAttachment) } } scheduleOperations(ctx, reschedule...) setStatus(ctx, statuses) if err := createVolumeAttachmentPlans(ctx, volumeAttachments); err != nil { return errors.Trace(err) } if err := setVolumeAttachmentInfo(ctx, volumeAttachments); err != nil { return errors.Trace(err) } return nil }
go
func attachVolumes(ctx *context, ops map[params.MachineStorageId]*attachVolumeOp) error { volumeAttachmentParams := make([]storage.VolumeAttachmentParams, 0, len(ops)) for _, op := range ops { volumeAttachmentParams = append(volumeAttachmentParams, op.args) } paramsBySource, volumeSources, err := volumeAttachmentParamsBySource( ctx.config.StorageDir, volumeAttachmentParams, ctx.config.Registry, ) if err != nil { return errors.Trace(err) } var reschedule []scheduleOp var volumeAttachments []storage.VolumeAttachment var statuses []params.EntityStatusArgs for sourceName, volumeAttachmentParams := range paramsBySource { logger.Debugf("attaching volumes: %+v", volumeAttachmentParams) volumeSource := volumeSources[sourceName] if volumeSource == nil { // The storage provider does not support dynamic // storage, there's nothing for the provisioner // to do here. continue } results, err := volumeSource.AttachVolumes(ctx.config.CloudCallContext, volumeAttachmentParams) if err != nil { return errors.Annotatef(err, "attaching volumes from source %q", sourceName) } for i, result := range results { p := volumeAttachmentParams[i] statuses = append(statuses, params.EntityStatusArgs{ Tag: p.Volume.String(), Status: status.Attached.String(), }) entityStatus := &statuses[len(statuses)-1] if result.Error != nil { // Reschedule the volume attachment. id := params.MachineStorageId{ MachineTag: p.Machine.String(), AttachmentTag: p.Volume.String(), } reschedule = append(reschedule, ops[id]) // Note: we keep the status as "attaching" to // indicate that we will retry. When we distinguish // between transient and permanent errors, we will // set the status to "error" for permanent errors. entityStatus.Status = status.Attaching.String() entityStatus.Info = result.Error.Error() logger.Debugf( "failed to attach %s to %s: %v", names.ReadableString(p.Volume), names.ReadableString(p.Machine), result.Error, ) continue } volumeAttachments = append(volumeAttachments, *result.VolumeAttachment) } } scheduleOperations(ctx, reschedule...) setStatus(ctx, statuses) if err := createVolumeAttachmentPlans(ctx, volumeAttachments); err != nil { return errors.Trace(err) } if err := setVolumeAttachmentInfo(ctx, volumeAttachments); err != nil { return errors.Trace(err) } return nil }
[ "func", "attachVolumes", "(", "ctx", "*", "context", ",", "ops", "map", "[", "params", ".", "MachineStorageId", "]", "*", "attachVolumeOp", ")", "error", "{", "volumeAttachmentParams", ":=", "make", "(", "[", "]", "storage", ".", "VolumeAttachmentParams", ",", "0", ",", "len", "(", "ops", ")", ")", "\n", "for", "_", ",", "op", ":=", "range", "ops", "{", "volumeAttachmentParams", "=", "append", "(", "volumeAttachmentParams", ",", "op", ".", "args", ")", "\n", "}", "\n", "paramsBySource", ",", "volumeSources", ",", "err", ":=", "volumeAttachmentParamsBySource", "(", "ctx", ".", "config", ".", "StorageDir", ",", "volumeAttachmentParams", ",", "ctx", ".", "config", ".", "Registry", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "var", "reschedule", "[", "]", "scheduleOp", "\n", "var", "volumeAttachments", "[", "]", "storage", ".", "VolumeAttachment", "\n", "var", "statuses", "[", "]", "params", ".", "EntityStatusArgs", "\n", "for", "sourceName", ",", "volumeAttachmentParams", ":=", "range", "paramsBySource", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "volumeAttachmentParams", ")", "\n", "volumeSource", ":=", "volumeSources", "[", "sourceName", "]", "\n", "if", "volumeSource", "==", "nil", "{", "// The storage provider does not support dynamic", "// storage, there's nothing for the provisioner", "// to do here.", "continue", "\n", "}", "\n", "results", ",", "err", ":=", "volumeSource", ".", "AttachVolumes", "(", "ctx", ".", "config", ".", "CloudCallContext", ",", "volumeAttachmentParams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "sourceName", ")", "\n", "}", "\n\n", "for", "i", ",", "result", ":=", "range", "results", "{", "p", ":=", "volumeAttachmentParams", "[", "i", "]", "\n", "statuses", "=", "append", "(", "statuses", ",", "params", ".", "EntityStatusArgs", "{", "Tag", ":", "p", ".", "Volume", ".", "String", "(", ")", ",", "Status", ":", "status", ".", "Attached", ".", "String", "(", ")", ",", "}", ")", "\n", "entityStatus", ":=", "&", "statuses", "[", "len", "(", "statuses", ")", "-", "1", "]", "\n", "if", "result", ".", "Error", "!=", "nil", "{", "// Reschedule the volume attachment.", "id", ":=", "params", ".", "MachineStorageId", "{", "MachineTag", ":", "p", ".", "Machine", ".", "String", "(", ")", ",", "AttachmentTag", ":", "p", ".", "Volume", ".", "String", "(", ")", ",", "}", "\n", "reschedule", "=", "append", "(", "reschedule", ",", "ops", "[", "id", "]", ")", "\n\n", "// Note: we keep the status as \"attaching\" to", "// indicate that we will retry. When we distinguish", "// between transient and permanent errors, we will", "// set the status to \"error\" for permanent errors.", "entityStatus", ".", "Status", "=", "status", ".", "Attaching", ".", "String", "(", ")", "\n", "entityStatus", ".", "Info", "=", "result", ".", "Error", ".", "Error", "(", ")", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "names", ".", "ReadableString", "(", "p", ".", "Volume", ")", ",", "names", ".", "ReadableString", "(", "p", ".", "Machine", ")", ",", "result", ".", "Error", ",", ")", "\n", "continue", "\n", "}", "\n", "volumeAttachments", "=", "append", "(", "volumeAttachments", ",", "*", "result", ".", "VolumeAttachment", ")", "\n", "}", "\n", "}", "\n", "scheduleOperations", "(", "ctx", ",", "reschedule", "...", ")", "\n", "setStatus", "(", "ctx", ",", "statuses", ")", "\n", "if", "err", ":=", "createVolumeAttachmentPlans", "(", "ctx", ",", "volumeAttachments", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "setVolumeAttachmentInfo", "(", "ctx", ",", "volumeAttachments", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// attachVolumes creates volume attachments with the specified parameters.
[ "attachVolumes", "creates", "volume", "attachments", "with", "the", "specified", "parameters", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/volume_ops.go#L126-L196
156,467
juju/juju
worker/storageprovisioner/volume_ops.go
createVolumeAttachmentPlans
func createVolumeAttachmentPlans(ctx *context, volumeAttachments []storage.VolumeAttachment) error { // NOTE(gsamfira): should we merge this with setVolumeInfo? if len(volumeAttachments) == 0 { return nil } volumeAttachmentPlans := make([]params.VolumeAttachmentPlan, len(volumeAttachments)) for i, val := range volumeAttachments { volumeAttachmentPlans[i] = volumeAttachmentPlanFromAttachment(val) } errorResults, err := ctx.config.Volumes.CreateVolumeAttachmentPlans(volumeAttachmentPlans) if err != nil { return errors.Annotatef(err, "creating volume plans") } for i, result := range errorResults { if result.Error != nil { return errors.Annotatef( result.Error, "creating volume plan of %s to %s to state", names.ReadableString(volumeAttachments[i].Volume), names.ReadableString(volumeAttachments[i].Machine), ) } // Record the volume attachment in the context. id := params.MachineStorageId{ MachineTag: volumeAttachmentPlans[i].MachineTag, AttachmentTag: volumeAttachmentPlans[i].VolumeTag, } ctx.volumeAttachments[id] = volumeAttachments[i] // removePendingVolumeAttachment(ctx, id) } return nil }
go
func createVolumeAttachmentPlans(ctx *context, volumeAttachments []storage.VolumeAttachment) error { // NOTE(gsamfira): should we merge this with setVolumeInfo? if len(volumeAttachments) == 0 { return nil } volumeAttachmentPlans := make([]params.VolumeAttachmentPlan, len(volumeAttachments)) for i, val := range volumeAttachments { volumeAttachmentPlans[i] = volumeAttachmentPlanFromAttachment(val) } errorResults, err := ctx.config.Volumes.CreateVolumeAttachmentPlans(volumeAttachmentPlans) if err != nil { return errors.Annotatef(err, "creating volume plans") } for i, result := range errorResults { if result.Error != nil { return errors.Annotatef( result.Error, "creating volume plan of %s to %s to state", names.ReadableString(volumeAttachments[i].Volume), names.ReadableString(volumeAttachments[i].Machine), ) } // Record the volume attachment in the context. id := params.MachineStorageId{ MachineTag: volumeAttachmentPlans[i].MachineTag, AttachmentTag: volumeAttachmentPlans[i].VolumeTag, } ctx.volumeAttachments[id] = volumeAttachments[i] // removePendingVolumeAttachment(ctx, id) } return nil }
[ "func", "createVolumeAttachmentPlans", "(", "ctx", "*", "context", ",", "volumeAttachments", "[", "]", "storage", ".", "VolumeAttachment", ")", "error", "{", "// NOTE(gsamfira): should we merge this with setVolumeInfo?", "if", "len", "(", "volumeAttachments", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "volumeAttachmentPlans", ":=", "make", "(", "[", "]", "params", ".", "VolumeAttachmentPlan", ",", "len", "(", "volumeAttachments", ")", ")", "\n", "for", "i", ",", "val", ":=", "range", "volumeAttachments", "{", "volumeAttachmentPlans", "[", "i", "]", "=", "volumeAttachmentPlanFromAttachment", "(", "val", ")", "\n", "}", "\n\n", "errorResults", ",", "err", ":=", "ctx", ".", "config", ".", "Volumes", ".", "CreateVolumeAttachmentPlans", "(", "volumeAttachmentPlans", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "for", "i", ",", "result", ":=", "range", "errorResults", "{", "if", "result", ".", "Error", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "result", ".", "Error", ",", "\"", "\"", ",", "names", ".", "ReadableString", "(", "volumeAttachments", "[", "i", "]", ".", "Volume", ")", ",", "names", ".", "ReadableString", "(", "volumeAttachments", "[", "i", "]", ".", "Machine", ")", ",", ")", "\n", "}", "\n", "// Record the volume attachment in the context.", "id", ":=", "params", ".", "MachineStorageId", "{", "MachineTag", ":", "volumeAttachmentPlans", "[", "i", "]", ".", "MachineTag", ",", "AttachmentTag", ":", "volumeAttachmentPlans", "[", "i", "]", ".", "VolumeTag", ",", "}", "\n", "ctx", ".", "volumeAttachments", "[", "id", "]", "=", "volumeAttachments", "[", "i", "]", "\n", "// removePendingVolumeAttachment(ctx, id)", "}", "\n", "return", "nil", "\n", "}" ]
// createVolumeAttachmentPlans creates a volume info plan in state, which notifies the machine // agent of the target instance that something has been attached to it.
[ "createVolumeAttachmentPlans", "creates", "a", "volume", "info", "plan", "in", "state", "which", "notifies", "the", "machine", "agent", "of", "the", "target", "instance", "that", "something", "has", "been", "attached", "to", "it", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/volume_ops.go#L200-L232
156,468
juju/juju
worker/storageprovisioner/volume_ops.go
detachVolumes
func detachVolumes(ctx *context, ops map[params.MachineStorageId]*detachVolumeOp) error { volumeAttachmentParams := make([]storage.VolumeAttachmentParams, 0, len(ops)) for _, op := range ops { volumeAttachmentParams = append(volumeAttachmentParams, op.args) } paramsBySource, volumeSources, err := volumeAttachmentParamsBySource( ctx.config.StorageDir, volumeAttachmentParams, ctx.config.Registry, ) if err != nil { return errors.Trace(err) } var reschedule []scheduleOp var statuses []params.EntityStatusArgs var remove []params.MachineStorageId for sourceName, volumeAttachmentParams := range paramsBySource { logger.Debugf("detaching volumes: %+v", volumeAttachmentParams) volumeSource := volumeSources[sourceName] if volumeSource == nil { // The storage provider does not support dynamic // storage, there's nothing for the provisioner // to do here. continue } errs, err := volumeSource.DetachVolumes(ctx.config.CloudCallContext, volumeAttachmentParams) if err != nil { return errors.Annotatef(err, "detaching volumes from source %q", sourceName) } for i, err := range errs { p := volumeAttachmentParams[i] statuses = append(statuses, params.EntityStatusArgs{ Tag: p.Volume.String(), // TODO(axw) when we support multiple // attachment, we'll have to check if // there are any other attachments // before saying the status "detached". Status: status.Detached.String(), }) id := params.MachineStorageId{ MachineTag: p.Machine.String(), AttachmentTag: p.Volume.String(), } entityStatus := &statuses[len(statuses)-1] if err != nil { reschedule = append(reschedule, ops[id]) entityStatus.Status = status.Detaching.String() entityStatus.Info = err.Error() logger.Debugf( "failed to detach %s from %s: %v", names.ReadableString(p.Volume), names.ReadableString(p.Machine), err, ) continue } remove = append(remove, id) } } scheduleOperations(ctx, reschedule...) setStatus(ctx, statuses) if err := removeAttachments(ctx, remove); err != nil { return errors.Annotate(err, "removing attachments from state") } for _, id := range remove { delete(ctx.volumeAttachments, id) } return nil }
go
func detachVolumes(ctx *context, ops map[params.MachineStorageId]*detachVolumeOp) error { volumeAttachmentParams := make([]storage.VolumeAttachmentParams, 0, len(ops)) for _, op := range ops { volumeAttachmentParams = append(volumeAttachmentParams, op.args) } paramsBySource, volumeSources, err := volumeAttachmentParamsBySource( ctx.config.StorageDir, volumeAttachmentParams, ctx.config.Registry, ) if err != nil { return errors.Trace(err) } var reschedule []scheduleOp var statuses []params.EntityStatusArgs var remove []params.MachineStorageId for sourceName, volumeAttachmentParams := range paramsBySource { logger.Debugf("detaching volumes: %+v", volumeAttachmentParams) volumeSource := volumeSources[sourceName] if volumeSource == nil { // The storage provider does not support dynamic // storage, there's nothing for the provisioner // to do here. continue } errs, err := volumeSource.DetachVolumes(ctx.config.CloudCallContext, volumeAttachmentParams) if err != nil { return errors.Annotatef(err, "detaching volumes from source %q", sourceName) } for i, err := range errs { p := volumeAttachmentParams[i] statuses = append(statuses, params.EntityStatusArgs{ Tag: p.Volume.String(), // TODO(axw) when we support multiple // attachment, we'll have to check if // there are any other attachments // before saying the status "detached". Status: status.Detached.String(), }) id := params.MachineStorageId{ MachineTag: p.Machine.String(), AttachmentTag: p.Volume.String(), } entityStatus := &statuses[len(statuses)-1] if err != nil { reschedule = append(reschedule, ops[id]) entityStatus.Status = status.Detaching.String() entityStatus.Info = err.Error() logger.Debugf( "failed to detach %s from %s: %v", names.ReadableString(p.Volume), names.ReadableString(p.Machine), err, ) continue } remove = append(remove, id) } } scheduleOperations(ctx, reschedule...) setStatus(ctx, statuses) if err := removeAttachments(ctx, remove); err != nil { return errors.Annotate(err, "removing attachments from state") } for _, id := range remove { delete(ctx.volumeAttachments, id) } return nil }
[ "func", "detachVolumes", "(", "ctx", "*", "context", ",", "ops", "map", "[", "params", ".", "MachineStorageId", "]", "*", "detachVolumeOp", ")", "error", "{", "volumeAttachmentParams", ":=", "make", "(", "[", "]", "storage", ".", "VolumeAttachmentParams", ",", "0", ",", "len", "(", "ops", ")", ")", "\n", "for", "_", ",", "op", ":=", "range", "ops", "{", "volumeAttachmentParams", "=", "append", "(", "volumeAttachmentParams", ",", "op", ".", "args", ")", "\n", "}", "\n", "paramsBySource", ",", "volumeSources", ",", "err", ":=", "volumeAttachmentParamsBySource", "(", "ctx", ".", "config", ".", "StorageDir", ",", "volumeAttachmentParams", ",", "ctx", ".", "config", ".", "Registry", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "var", "reschedule", "[", "]", "scheduleOp", "\n", "var", "statuses", "[", "]", "params", ".", "EntityStatusArgs", "\n", "var", "remove", "[", "]", "params", ".", "MachineStorageId", "\n", "for", "sourceName", ",", "volumeAttachmentParams", ":=", "range", "paramsBySource", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "volumeAttachmentParams", ")", "\n", "volumeSource", ":=", "volumeSources", "[", "sourceName", "]", "\n", "if", "volumeSource", "==", "nil", "{", "// The storage provider does not support dynamic", "// storage, there's nothing for the provisioner", "// to do here.", "continue", "\n", "}", "\n", "errs", ",", "err", ":=", "volumeSource", ".", "DetachVolumes", "(", "ctx", ".", "config", ".", "CloudCallContext", ",", "volumeAttachmentParams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "sourceName", ")", "\n", "}", "\n", "for", "i", ",", "err", ":=", "range", "errs", "{", "p", ":=", "volumeAttachmentParams", "[", "i", "]", "\n", "statuses", "=", "append", "(", "statuses", ",", "params", ".", "EntityStatusArgs", "{", "Tag", ":", "p", ".", "Volume", ".", "String", "(", ")", ",", "// TODO(axw) when we support multiple", "// attachment, we'll have to check if", "// there are any other attachments", "// before saying the status \"detached\".", "Status", ":", "status", ".", "Detached", ".", "String", "(", ")", ",", "}", ")", "\n", "id", ":=", "params", ".", "MachineStorageId", "{", "MachineTag", ":", "p", ".", "Machine", ".", "String", "(", ")", ",", "AttachmentTag", ":", "p", ".", "Volume", ".", "String", "(", ")", ",", "}", "\n", "entityStatus", ":=", "&", "statuses", "[", "len", "(", "statuses", ")", "-", "1", "]", "\n", "if", "err", "!=", "nil", "{", "reschedule", "=", "append", "(", "reschedule", ",", "ops", "[", "id", "]", ")", "\n", "entityStatus", ".", "Status", "=", "status", ".", "Detaching", ".", "String", "(", ")", "\n", "entityStatus", ".", "Info", "=", "err", ".", "Error", "(", ")", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "names", ".", "ReadableString", "(", "p", ".", "Volume", ")", ",", "names", ".", "ReadableString", "(", "p", ".", "Machine", ")", ",", "err", ",", ")", "\n", "continue", "\n", "}", "\n", "remove", "=", "append", "(", "remove", ",", "id", ")", "\n", "}", "\n", "}", "\n", "scheduleOperations", "(", "ctx", ",", "reschedule", "...", ")", "\n", "setStatus", "(", "ctx", ",", "statuses", ")", "\n", "if", "err", ":=", "removeAttachments", "(", "ctx", ",", "remove", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "for", "_", ",", "id", ":=", "range", "remove", "{", "delete", "(", "ctx", ".", "volumeAttachments", ",", "id", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// detachVolumes destroys volume attachments with the specified parameters.
[ "detachVolumes", "destroys", "volume", "attachments", "with", "the", "specified", "parameters", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/volume_ops.go#L349-L415
156,469
juju/juju
worker/storageprovisioner/volume_ops.go
validateVolumeParams
func validateVolumeParams( volumeSource storage.VolumeSource, volumeParams []storage.VolumeParams, ) ([]storage.VolumeParams, []error) { valid := make([]storage.VolumeParams, 0, len(volumeParams)) results := make([]error, len(volumeParams)) for i, params := range volumeParams { err := volumeSource.ValidateVolumeParams(params) if err == nil { valid = append(valid, params) } results[i] = err } return valid, results }
go
func validateVolumeParams( volumeSource storage.VolumeSource, volumeParams []storage.VolumeParams, ) ([]storage.VolumeParams, []error) { valid := make([]storage.VolumeParams, 0, len(volumeParams)) results := make([]error, len(volumeParams)) for i, params := range volumeParams { err := volumeSource.ValidateVolumeParams(params) if err == nil { valid = append(valid, params) } results[i] = err } return valid, results }
[ "func", "validateVolumeParams", "(", "volumeSource", "storage", ".", "VolumeSource", ",", "volumeParams", "[", "]", "storage", ".", "VolumeParams", ",", ")", "(", "[", "]", "storage", ".", "VolumeParams", ",", "[", "]", "error", ")", "{", "valid", ":=", "make", "(", "[", "]", "storage", ".", "VolumeParams", ",", "0", ",", "len", "(", "volumeParams", ")", ")", "\n", "results", ":=", "make", "(", "[", "]", "error", ",", "len", "(", "volumeParams", ")", ")", "\n", "for", "i", ",", "params", ":=", "range", "volumeParams", "{", "err", ":=", "volumeSource", ".", "ValidateVolumeParams", "(", "params", ")", "\n", "if", "err", "==", "nil", "{", "valid", "=", "append", "(", "valid", ",", "params", ")", "\n", "}", "\n", "results", "[", "i", "]", "=", "err", "\n", "}", "\n", "return", "valid", ",", "results", "\n", "}" ]
// validateVolumeParams validates a collection of volume parameters.
[ "validateVolumeParams", "validates", "a", "collection", "of", "volume", "parameters", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/volume_ops.go#L458-L471
156,470
juju/juju
worker/storageprovisioner/volume_ops.go
volumeAttachmentParamsBySource
func volumeAttachmentParamsBySource( baseStorageDir string, params []storage.VolumeAttachmentParams, registry storage.ProviderRegistry, ) (map[string][]storage.VolumeAttachmentParams, map[string]storage.VolumeSource, error) { // TODO(axw) later we may have multiple instantiations (sources) // for a storage provider, e.g. multiple Ceph installations. For // now we assume a single source for each provider type, with no // configuration. volumeSources := make(map[string]storage.VolumeSource) paramsBySource := make(map[string][]storage.VolumeAttachmentParams) for _, params := range params { sourceName := string(params.Provider) paramsBySource[sourceName] = append(paramsBySource[sourceName], params) if _, ok := volumeSources[sourceName]; ok { continue } volumeSource, err := volumeSource( baseStorageDir, sourceName, params.Provider, registry, ) if errors.Cause(err) == errNonDynamic { volumeSource = nil } else if err != nil { return nil, nil, errors.Annotate(err, "getting volume source") } volumeSources[sourceName] = volumeSource } return paramsBySource, volumeSources, nil }
go
func volumeAttachmentParamsBySource( baseStorageDir string, params []storage.VolumeAttachmentParams, registry storage.ProviderRegistry, ) (map[string][]storage.VolumeAttachmentParams, map[string]storage.VolumeSource, error) { // TODO(axw) later we may have multiple instantiations (sources) // for a storage provider, e.g. multiple Ceph installations. For // now we assume a single source for each provider type, with no // configuration. volumeSources := make(map[string]storage.VolumeSource) paramsBySource := make(map[string][]storage.VolumeAttachmentParams) for _, params := range params { sourceName := string(params.Provider) paramsBySource[sourceName] = append(paramsBySource[sourceName], params) if _, ok := volumeSources[sourceName]; ok { continue } volumeSource, err := volumeSource( baseStorageDir, sourceName, params.Provider, registry, ) if errors.Cause(err) == errNonDynamic { volumeSource = nil } else if err != nil { return nil, nil, errors.Annotate(err, "getting volume source") } volumeSources[sourceName] = volumeSource } return paramsBySource, volumeSources, nil }
[ "func", "volumeAttachmentParamsBySource", "(", "baseStorageDir", "string", ",", "params", "[", "]", "storage", ".", "VolumeAttachmentParams", ",", "registry", "storage", ".", "ProviderRegistry", ",", ")", "(", "map", "[", "string", "]", "[", "]", "storage", ".", "VolumeAttachmentParams", ",", "map", "[", "string", "]", "storage", ".", "VolumeSource", ",", "error", ")", "{", "// TODO(axw) later we may have multiple instantiations (sources)", "// for a storage provider, e.g. multiple Ceph installations. For", "// now we assume a single source for each provider type, with no", "// configuration.", "volumeSources", ":=", "make", "(", "map", "[", "string", "]", "storage", ".", "VolumeSource", ")", "\n", "paramsBySource", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "storage", ".", "VolumeAttachmentParams", ")", "\n", "for", "_", ",", "params", ":=", "range", "params", "{", "sourceName", ":=", "string", "(", "params", ".", "Provider", ")", "\n", "paramsBySource", "[", "sourceName", "]", "=", "append", "(", "paramsBySource", "[", "sourceName", "]", ",", "params", ")", "\n", "if", "_", ",", "ok", ":=", "volumeSources", "[", "sourceName", "]", ";", "ok", "{", "continue", "\n", "}", "\n", "volumeSource", ",", "err", ":=", "volumeSource", "(", "baseStorageDir", ",", "sourceName", ",", "params", ".", "Provider", ",", "registry", ",", ")", "\n", "if", "errors", ".", "Cause", "(", "err", ")", "==", "errNonDynamic", "{", "volumeSource", "=", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "volumeSources", "[", "sourceName", "]", "=", "volumeSource", "\n", "}", "\n", "return", "paramsBySource", ",", "volumeSources", ",", "nil", "\n", "}" ]
// volumeAttachmentParamsBySource separates the volume attachment parameters by volume source.
[ "volumeAttachmentParamsBySource", "separates", "the", "volume", "attachment", "parameters", "by", "volume", "source", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/volume_ops.go#L474-L502
156,471
juju/juju
worker/introspection/socket.go
Validate
func (c *Config) Validate() error { if c.SocketName == "" { return errors.NotValidf("empty SocketName") } if c.PrometheusGatherer == nil { return errors.NotValidf("nil PrometheusGatherer") } return nil }
go
func (c *Config) Validate() error { if c.SocketName == "" { return errors.NotValidf("empty SocketName") } if c.PrometheusGatherer == nil { return errors.NotValidf("nil PrometheusGatherer") } return nil }
[ "func", "(", "c", "*", "Config", ")", "Validate", "(", ")", "error", "{", "if", "c", ".", "SocketName", "==", "\"", "\"", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "PrometheusGatherer", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate checks the config values to assert they are valid to create the worker.
[ "Validate", "checks", "the", "config", "values", "to", "assert", "they", "are", "valid", "to", "create", "the", "worker", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/introspection/socket.go#L54-L62
156,472
juju/juju
worker/introspection/socket.go
NewWorker
func NewWorker(config Config) (worker.Worker, error) { if err := config.Validate(); err != nil { return nil, errors.Trace(err) } if runtime.GOOS != "linux" { return nil, errors.NotSupportedf("os %q", runtime.GOOS) } path := "@" + config.SocketName addr, err := net.ResolveUnixAddr("unix", path) if err != nil { return nil, errors.Annotate(err, "unable to resolve unix socket") } l, err := net.ListenUnix("unix", addr) if err != nil { return nil, errors.Annotate(err, "unable to listen on unix socket") } logger.Debugf("introspection worker listening on %q", path) w := &socketListener{ listener: l, depEngine: config.DepEngine, statePool: config.StatePool, pubsub: config.PubSub, machineLock: config.MachineLock, prometheusGatherer: config.PrometheusGatherer, presence: config.Presence, done: make(chan struct{}), } go w.serve() w.tomb.Go(w.run) return w, nil }
go
func NewWorker(config Config) (worker.Worker, error) { if err := config.Validate(); err != nil { return nil, errors.Trace(err) } if runtime.GOOS != "linux" { return nil, errors.NotSupportedf("os %q", runtime.GOOS) } path := "@" + config.SocketName addr, err := net.ResolveUnixAddr("unix", path) if err != nil { return nil, errors.Annotate(err, "unable to resolve unix socket") } l, err := net.ListenUnix("unix", addr) if err != nil { return nil, errors.Annotate(err, "unable to listen on unix socket") } logger.Debugf("introspection worker listening on %q", path) w := &socketListener{ listener: l, depEngine: config.DepEngine, statePool: config.StatePool, pubsub: config.PubSub, machineLock: config.MachineLock, prometheusGatherer: config.PrometheusGatherer, presence: config.Presence, done: make(chan struct{}), } go w.serve() w.tomb.Go(w.run) return w, nil }
[ "func", "NewWorker", "(", "config", "Config", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "if", "err", ":=", "config", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "runtime", ".", "GOOS", "!=", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "NotSupportedf", "(", "\"", "\"", ",", "runtime", ".", "GOOS", ")", "\n", "}", "\n\n", "path", ":=", "\"", "\"", "+", "config", ".", "SocketName", "\n", "addr", ",", "err", ":=", "net", ".", "ResolveUnixAddr", "(", "\"", "\"", ",", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "l", ",", "err", ":=", "net", ".", "ListenUnix", "(", "\"", "\"", ",", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "path", ")", "\n\n", "w", ":=", "&", "socketListener", "{", "listener", ":", "l", ",", "depEngine", ":", "config", ".", "DepEngine", ",", "statePool", ":", "config", ".", "StatePool", ",", "pubsub", ":", "config", ".", "PubSub", ",", "machineLock", ":", "config", ".", "MachineLock", ",", "prometheusGatherer", ":", "config", ".", "PrometheusGatherer", ",", "presence", ":", "config", ".", "Presence", ",", "done", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "go", "w", ".", "serve", "(", ")", "\n", "w", ".", "tomb", ".", "Go", "(", "w", ".", "run", ")", "\n", "return", "w", ",", "nil", "\n", "}" ]
// NewWorker starts an http server listening on an abstract domain socket // which will be created with the specified name.
[ "NewWorker", "starts", "an", "http", "server", "listening", "on", "an", "abstract", "domain", "socket", "which", "will", "be", "created", "with", "the", "specified", "name", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/introspection/socket.go#L79-L112
156,473
juju/juju
worker/introspection/socket.go
RegisterHTTPHandlers
func RegisterHTTPHandlers( sources ReportSources, handle func(path string, h http.Handler), ) { handle("/debug/pprof/", http.HandlerFunc(pprof.Index)) handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline)) handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile)) handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol)) handle("/debug/pprof/trace", http.HandlerFunc(pprof.Trace)) handle("/depengine", depengineHandler{sources.DependencyEngine}) handle("/statepool", introspectionReporterHandler{ name: "State Pool Report", reporter: sources.StatePool, }) handle("/pubsub", introspectionReporterHandler{ name: "PubSub Report", reporter: sources.PubSub, }) handle("/metrics/", promhttp.HandlerFor(sources.PrometheusGatherer, promhttp.HandlerOpts{})) // Unit agents don't have a presence recorder to pass in. if sources.Presence != nil { handle("/presence/", presenceHandler{sources.Presence}) } handle("/machinelock/", machineLockHandler{sources.MachineLock}) }
go
func RegisterHTTPHandlers( sources ReportSources, handle func(path string, h http.Handler), ) { handle("/debug/pprof/", http.HandlerFunc(pprof.Index)) handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline)) handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile)) handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol)) handle("/debug/pprof/trace", http.HandlerFunc(pprof.Trace)) handle("/depengine", depengineHandler{sources.DependencyEngine}) handle("/statepool", introspectionReporterHandler{ name: "State Pool Report", reporter: sources.StatePool, }) handle("/pubsub", introspectionReporterHandler{ name: "PubSub Report", reporter: sources.PubSub, }) handle("/metrics/", promhttp.HandlerFor(sources.PrometheusGatherer, promhttp.HandlerOpts{})) // Unit agents don't have a presence recorder to pass in. if sources.Presence != nil { handle("/presence/", presenceHandler{sources.Presence}) } handle("/machinelock/", machineLockHandler{sources.MachineLock}) }
[ "func", "RegisterHTTPHandlers", "(", "sources", "ReportSources", ",", "handle", "func", "(", "path", "string", ",", "h", "http", ".", "Handler", ")", ",", ")", "{", "handle", "(", "\"", "\"", ",", "http", ".", "HandlerFunc", "(", "pprof", ".", "Index", ")", ")", "\n", "handle", "(", "\"", "\"", ",", "http", ".", "HandlerFunc", "(", "pprof", ".", "Cmdline", ")", ")", "\n", "handle", "(", "\"", "\"", ",", "http", ".", "HandlerFunc", "(", "pprof", ".", "Profile", ")", ")", "\n", "handle", "(", "\"", "\"", ",", "http", ".", "HandlerFunc", "(", "pprof", ".", "Symbol", ")", ")", "\n", "handle", "(", "\"", "\"", ",", "http", ".", "HandlerFunc", "(", "pprof", ".", "Trace", ")", ")", "\n", "handle", "(", "\"", "\"", ",", "depengineHandler", "{", "sources", ".", "DependencyEngine", "}", ")", "\n", "handle", "(", "\"", "\"", ",", "introspectionReporterHandler", "{", "name", ":", "\"", "\"", ",", "reporter", ":", "sources", ".", "StatePool", ",", "}", ")", "\n", "handle", "(", "\"", "\"", ",", "introspectionReporterHandler", "{", "name", ":", "\"", "\"", ",", "reporter", ":", "sources", ".", "PubSub", ",", "}", ")", "\n", "handle", "(", "\"", "\"", ",", "promhttp", ".", "HandlerFor", "(", "sources", ".", "PrometheusGatherer", ",", "promhttp", ".", "HandlerOpts", "{", "}", ")", ")", "\n", "// Unit agents don't have a presence recorder to pass in.", "if", "sources", ".", "Presence", "!=", "nil", "{", "handle", "(", "\"", "\"", ",", "presenceHandler", "{", "sources", ".", "Presence", "}", ")", "\n", "}", "\n", "handle", "(", "\"", "\"", ",", "machineLockHandler", "{", "sources", ".", "MachineLock", "}", ")", "\n", "}" ]
// AddHandlers calls the given function with http.Handlers // that serve agent introspection requests. The function will // be called with a path; the function may alter the path // as it sees fit.
[ "AddHandlers", "calls", "the", "given", "function", "with", "http", ".", "Handlers", "that", "serve", "agent", "introspection", "requests", ".", "The", "function", "will", "be", "called", "with", "a", "path", ";", "the", "function", "may", "alter", "the", "path", "as", "it", "sees", "fit", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/introspection/socket.go#L168-L192
156,474
juju/juju
apiserver/facades/agent/storageprovisioner/internal/filesystemwatcher/watchers.go
WatchModelManagedFilesystems
func (fw Watchers) WatchModelManagedFilesystems() state.StringsWatcher { return newFilteredStringsWatcher(fw.Backend.WatchModelFilesystems(), func(id string) (bool, error) { f, err := fw.Backend.Filesystem(names.NewFilesystemTag(id)) if errors.IsNotFound(err) { return false, nil } else if err != nil { return false, errors.Trace(err) } _, err = f.Volume() return err == state.ErrNoBackingVolume, nil }) }
go
func (fw Watchers) WatchModelManagedFilesystems() state.StringsWatcher { return newFilteredStringsWatcher(fw.Backend.WatchModelFilesystems(), func(id string) (bool, error) { f, err := fw.Backend.Filesystem(names.NewFilesystemTag(id)) if errors.IsNotFound(err) { return false, nil } else if err != nil { return false, errors.Trace(err) } _, err = f.Volume() return err == state.ErrNoBackingVolume, nil }) }
[ "func", "(", "fw", "Watchers", ")", "WatchModelManagedFilesystems", "(", ")", "state", ".", "StringsWatcher", "{", "return", "newFilteredStringsWatcher", "(", "fw", ".", "Backend", ".", "WatchModelFilesystems", "(", ")", ",", "func", "(", "id", "string", ")", "(", "bool", ",", "error", ")", "{", "f", ",", "err", ":=", "fw", ".", "Backend", ".", "Filesystem", "(", "names", ".", "NewFilesystemTag", "(", "id", ")", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "false", ",", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "_", ",", "err", "=", "f", ".", "Volume", "(", ")", "\n", "return", "err", "==", "state", ".", "ErrNoBackingVolume", ",", "nil", "\n", "}", ")", "\n", "}" ]
// WatchModelManagedFilesystems returns a strings watcher that reports // model-scoped filesystems that have no backing volume. Volume-backed // filesystems are always managed by the host to which they are attached.
[ "WatchModelManagedFilesystems", "returns", "a", "strings", "watcher", "that", "reports", "model", "-", "scoped", "filesystems", "that", "have", "no", "backing", "volume", ".", "Volume", "-", "backed", "filesystems", "are", "always", "managed", "by", "the", "host", "to", "which", "they", "are", "attached", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/storageprovisioner/internal/filesystemwatcher/watchers.go#L29-L40
156,475
juju/juju
apiserver/facades/agent/storageprovisioner/internal/filesystemwatcher/watchers.go
WatchUnitManagedFilesystems
func (fw Watchers) WatchUnitManagedFilesystems(app names.ApplicationTag) state.StringsWatcher { w := &hostFilesystemsWatcher{ stringsWatcherBase: stringsWatcherBase{out: make(chan []string)}, backend: fw.Backend, changes: set.NewStrings(), hostFilesystems: fw.Backend.WatchUnitFilesystems(app), modelFilesystems: fw.Backend.WatchModelFilesystems(), modelVolumeAttachments: fw.Backend.WatchModelVolumeAttachments(), modelVolumesAttached: names.NewSet(), modelVolumeFilesystems: make(map[names.VolumeTag]names.FilesystemTag), hostMatch: func(tag names.Tag) (bool, error) { entity, err := names.UnitApplication(tag.Id()) if err != nil { return false, errors.Trace(err) } return app.Id() == entity, nil }, } w.tomb.Go(func() error { defer watcher.Stop(w.hostFilesystems, &w.tomb) defer watcher.Stop(w.modelFilesystems, &w.tomb) defer watcher.Stop(w.modelVolumeAttachments, &w.tomb) return w.loop() }) return w }
go
func (fw Watchers) WatchUnitManagedFilesystems(app names.ApplicationTag) state.StringsWatcher { w := &hostFilesystemsWatcher{ stringsWatcherBase: stringsWatcherBase{out: make(chan []string)}, backend: fw.Backend, changes: set.NewStrings(), hostFilesystems: fw.Backend.WatchUnitFilesystems(app), modelFilesystems: fw.Backend.WatchModelFilesystems(), modelVolumeAttachments: fw.Backend.WatchModelVolumeAttachments(), modelVolumesAttached: names.NewSet(), modelVolumeFilesystems: make(map[names.VolumeTag]names.FilesystemTag), hostMatch: func(tag names.Tag) (bool, error) { entity, err := names.UnitApplication(tag.Id()) if err != nil { return false, errors.Trace(err) } return app.Id() == entity, nil }, } w.tomb.Go(func() error { defer watcher.Stop(w.hostFilesystems, &w.tomb) defer watcher.Stop(w.modelFilesystems, &w.tomb) defer watcher.Stop(w.modelVolumeAttachments, &w.tomb) return w.loop() }) return w }
[ "func", "(", "fw", "Watchers", ")", "WatchUnitManagedFilesystems", "(", "app", "names", ".", "ApplicationTag", ")", "state", ".", "StringsWatcher", "{", "w", ":=", "&", "hostFilesystemsWatcher", "{", "stringsWatcherBase", ":", "stringsWatcherBase", "{", "out", ":", "make", "(", "chan", "[", "]", "string", ")", "}", ",", "backend", ":", "fw", ".", "Backend", ",", "changes", ":", "set", ".", "NewStrings", "(", ")", ",", "hostFilesystems", ":", "fw", ".", "Backend", ".", "WatchUnitFilesystems", "(", "app", ")", ",", "modelFilesystems", ":", "fw", ".", "Backend", ".", "WatchModelFilesystems", "(", ")", ",", "modelVolumeAttachments", ":", "fw", ".", "Backend", ".", "WatchModelVolumeAttachments", "(", ")", ",", "modelVolumesAttached", ":", "names", ".", "NewSet", "(", ")", ",", "modelVolumeFilesystems", ":", "make", "(", "map", "[", "names", ".", "VolumeTag", "]", "names", ".", "FilesystemTag", ")", ",", "hostMatch", ":", "func", "(", "tag", "names", ".", "Tag", ")", "(", "bool", ",", "error", ")", "{", "entity", ",", "err", ":=", "names", ".", "UnitApplication", "(", "tag", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "app", ".", "Id", "(", ")", "==", "entity", ",", "nil", "\n", "}", ",", "}", "\n", "w", ".", "tomb", ".", "Go", "(", "func", "(", ")", "error", "{", "defer", "watcher", ".", "Stop", "(", "w", ".", "hostFilesystems", ",", "&", "w", ".", "tomb", ")", "\n", "defer", "watcher", ".", "Stop", "(", "w", ".", "modelFilesystems", ",", "&", "w", ".", "tomb", ")", "\n", "defer", "watcher", ".", "Stop", "(", "w", ".", "modelVolumeAttachments", ",", "&", "w", ".", "tomb", ")", "\n", "return", "w", ".", "loop", "(", ")", "\n", "}", ")", "\n", "return", "w", "\n", "}" ]
// WatchUnitManagedFilesystems returns a strings watcher that reports both // unit-scoped filesystems, and model-scoped, volume-backed filesystems // that are attached to units of the specified application.
[ "WatchUnitManagedFilesystems", "returns", "a", "strings", "watcher", "that", "reports", "both", "unit", "-", "scoped", "filesystems", "and", "model", "-", "scoped", "volume", "-", "backed", "filesystems", "that", "are", "attached", "to", "units", "of", "the", "specified", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/storageprovisioner/internal/filesystemwatcher/watchers.go#L45-L70
156,476
juju/juju
apiserver/facades/agent/storageprovisioner/internal/filesystemwatcher/watchers.go
WatchMachineManagedFilesystems
func (fw Watchers) WatchMachineManagedFilesystems(m names.MachineTag) state.StringsWatcher { w := &hostFilesystemsWatcher{ stringsWatcherBase: stringsWatcherBase{out: make(chan []string)}, backend: fw.Backend, changes: set.NewStrings(), hostFilesystems: fw.Backend.WatchMachineFilesystems(m), modelFilesystems: fw.Backend.WatchModelFilesystems(), modelVolumeAttachments: fw.Backend.WatchModelVolumeAttachments(), modelVolumesAttached: names.NewSet(), modelVolumeFilesystems: make(map[names.VolumeTag]names.FilesystemTag), hostMatch: func(tag names.Tag) (bool, error) { return tag == m, nil }, } w.tomb.Go(func() error { defer watcher.Stop(w.hostFilesystems, &w.tomb) defer watcher.Stop(w.modelFilesystems, &w.tomb) defer watcher.Stop(w.modelVolumeAttachments, &w.tomb) return w.loop() }) return w }
go
func (fw Watchers) WatchMachineManagedFilesystems(m names.MachineTag) state.StringsWatcher { w := &hostFilesystemsWatcher{ stringsWatcherBase: stringsWatcherBase{out: make(chan []string)}, backend: fw.Backend, changes: set.NewStrings(), hostFilesystems: fw.Backend.WatchMachineFilesystems(m), modelFilesystems: fw.Backend.WatchModelFilesystems(), modelVolumeAttachments: fw.Backend.WatchModelVolumeAttachments(), modelVolumesAttached: names.NewSet(), modelVolumeFilesystems: make(map[names.VolumeTag]names.FilesystemTag), hostMatch: func(tag names.Tag) (bool, error) { return tag == m, nil }, } w.tomb.Go(func() error { defer watcher.Stop(w.hostFilesystems, &w.tomb) defer watcher.Stop(w.modelFilesystems, &w.tomb) defer watcher.Stop(w.modelVolumeAttachments, &w.tomb) return w.loop() }) return w }
[ "func", "(", "fw", "Watchers", ")", "WatchMachineManagedFilesystems", "(", "m", "names", ".", "MachineTag", ")", "state", ".", "StringsWatcher", "{", "w", ":=", "&", "hostFilesystemsWatcher", "{", "stringsWatcherBase", ":", "stringsWatcherBase", "{", "out", ":", "make", "(", "chan", "[", "]", "string", ")", "}", ",", "backend", ":", "fw", ".", "Backend", ",", "changes", ":", "set", ".", "NewStrings", "(", ")", ",", "hostFilesystems", ":", "fw", ".", "Backend", ".", "WatchMachineFilesystems", "(", "m", ")", ",", "modelFilesystems", ":", "fw", ".", "Backend", ".", "WatchModelFilesystems", "(", ")", ",", "modelVolumeAttachments", ":", "fw", ".", "Backend", ".", "WatchModelVolumeAttachments", "(", ")", ",", "modelVolumesAttached", ":", "names", ".", "NewSet", "(", ")", ",", "modelVolumeFilesystems", ":", "make", "(", "map", "[", "names", ".", "VolumeTag", "]", "names", ".", "FilesystemTag", ")", ",", "hostMatch", ":", "func", "(", "tag", "names", ".", "Tag", ")", "(", "bool", ",", "error", ")", "{", "return", "tag", "==", "m", ",", "nil", "\n", "}", ",", "}", "\n", "w", ".", "tomb", ".", "Go", "(", "func", "(", ")", "error", "{", "defer", "watcher", ".", "Stop", "(", "w", ".", "hostFilesystems", ",", "&", "w", ".", "tomb", ")", "\n", "defer", "watcher", ".", "Stop", "(", "w", ".", "modelFilesystems", ",", "&", "w", ".", "tomb", ")", "\n", "defer", "watcher", ".", "Stop", "(", "w", ".", "modelVolumeAttachments", ",", "&", "w", ".", "tomb", ")", "\n", "return", "w", ".", "loop", "(", ")", "\n", "}", ")", "\n", "return", "w", "\n", "}" ]
// WatchMachineManagedFilesystems returns a strings watcher that reports both // machine-scoped filesystems, and model-scoped, volume-backed filesystems // that are attached to the specified machine.
[ "WatchMachineManagedFilesystems", "returns", "a", "strings", "watcher", "that", "reports", "both", "machine", "-", "scoped", "filesystems", "and", "model", "-", "scoped", "volume", "-", "backed", "filesystems", "that", "are", "attached", "to", "the", "specified", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/storageprovisioner/internal/filesystemwatcher/watchers.go#L75-L96
156,477
juju/juju
apiserver/facades/agent/storageprovisioner/internal/filesystemwatcher/watchers.go
WatchModelManagedFilesystemAttachments
func (fw Watchers) WatchModelManagedFilesystemAttachments() state.StringsWatcher { return newFilteredStringsWatcher(fw.Backend.WatchModelFilesystemAttachments(), func(id string) (bool, error) { _, filesystemTag, err := state.ParseFilesystemAttachmentId(id) if err != nil { return false, errors.Annotate(err, "parsing filesystem attachment ID") } f, err := fw.Backend.Filesystem(filesystemTag) if errors.IsNotFound(err) { return false, nil } else if err != nil { return false, errors.Trace(err) } _, err = f.Volume() return err == state.ErrNoBackingVolume, nil }) }
go
func (fw Watchers) WatchModelManagedFilesystemAttachments() state.StringsWatcher { return newFilteredStringsWatcher(fw.Backend.WatchModelFilesystemAttachments(), func(id string) (bool, error) { _, filesystemTag, err := state.ParseFilesystemAttachmentId(id) if err != nil { return false, errors.Annotate(err, "parsing filesystem attachment ID") } f, err := fw.Backend.Filesystem(filesystemTag) if errors.IsNotFound(err) { return false, nil } else if err != nil { return false, errors.Trace(err) } _, err = f.Volume() return err == state.ErrNoBackingVolume, nil }) }
[ "func", "(", "fw", "Watchers", ")", "WatchModelManagedFilesystemAttachments", "(", ")", "state", ".", "StringsWatcher", "{", "return", "newFilteredStringsWatcher", "(", "fw", ".", "Backend", ".", "WatchModelFilesystemAttachments", "(", ")", ",", "func", "(", "id", "string", ")", "(", "bool", ",", "error", ")", "{", "_", ",", "filesystemTag", ",", "err", ":=", "state", ".", "ParseFilesystemAttachmentId", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "f", ",", "err", ":=", "fw", ".", "Backend", ".", "Filesystem", "(", "filesystemTag", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "false", ",", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "_", ",", "err", "=", "f", ".", "Volume", "(", ")", "\n", "return", "err", "==", "state", ".", "ErrNoBackingVolume", ",", "nil", "\n", "}", ")", "\n", "}" ]
// WatchModelManagedFilesystemAttachments returns a strings watcher that // reports lifecycle changes to attachments of model-scoped filesystem that // have no backing volume. Volume-backed filesystems are always managed by // the host to which they are attached.
[ "WatchModelManagedFilesystemAttachments", "returns", "a", "strings", "watcher", "that", "reports", "lifecycle", "changes", "to", "attachments", "of", "model", "-", "scoped", "filesystem", "that", "have", "no", "backing", "volume", ".", "Volume", "-", "backed", "filesystems", "are", "always", "managed", "by", "the", "host", "to", "which", "they", "are", "attached", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/storageprovisioner/internal/filesystemwatcher/watchers.go#L237-L252
156,478
juju/juju
apiserver/facades/agent/storageprovisioner/internal/filesystemwatcher/watchers.go
WatchMachineManagedFilesystemAttachments
func (fw Watchers) WatchMachineManagedFilesystemAttachments(m names.MachineTag) state.StringsWatcher { w := &hostFilesystemAttachmentsWatcher{ stringsWatcherBase: stringsWatcherBase{out: make(chan []string)}, backend: fw.Backend, changes: set.NewStrings(), hostFilesystemAttachments: fw.Backend.WatchMachineFilesystemAttachments(m), modelFilesystemAttachments: fw.Backend.WatchModelFilesystemAttachments(), modelVolumeAttachments: fw.Backend.WatchModelVolumeAttachments(), modelVolumesAttached: names.NewSet(), modelVolumeFilesystemAttachments: make(map[names.VolumeTag]string), hostMatch: func(tag names.Tag) (bool, error) { return tag == m, nil }, } w.tomb.Go(func() error { defer watcher.Stop(w.hostFilesystemAttachments, &w.tomb) defer watcher.Stop(w.modelFilesystemAttachments, &w.tomb) defer watcher.Stop(w.modelVolumeAttachments, &w.tomb) return w.loop() }) return w }
go
func (fw Watchers) WatchMachineManagedFilesystemAttachments(m names.MachineTag) state.StringsWatcher { w := &hostFilesystemAttachmentsWatcher{ stringsWatcherBase: stringsWatcherBase{out: make(chan []string)}, backend: fw.Backend, changes: set.NewStrings(), hostFilesystemAttachments: fw.Backend.WatchMachineFilesystemAttachments(m), modelFilesystemAttachments: fw.Backend.WatchModelFilesystemAttachments(), modelVolumeAttachments: fw.Backend.WatchModelVolumeAttachments(), modelVolumesAttached: names.NewSet(), modelVolumeFilesystemAttachments: make(map[names.VolumeTag]string), hostMatch: func(tag names.Tag) (bool, error) { return tag == m, nil }, } w.tomb.Go(func() error { defer watcher.Stop(w.hostFilesystemAttachments, &w.tomb) defer watcher.Stop(w.modelFilesystemAttachments, &w.tomb) defer watcher.Stop(w.modelVolumeAttachments, &w.tomb) return w.loop() }) return w }
[ "func", "(", "fw", "Watchers", ")", "WatchMachineManagedFilesystemAttachments", "(", "m", "names", ".", "MachineTag", ")", "state", ".", "StringsWatcher", "{", "w", ":=", "&", "hostFilesystemAttachmentsWatcher", "{", "stringsWatcherBase", ":", "stringsWatcherBase", "{", "out", ":", "make", "(", "chan", "[", "]", "string", ")", "}", ",", "backend", ":", "fw", ".", "Backend", ",", "changes", ":", "set", ".", "NewStrings", "(", ")", ",", "hostFilesystemAttachments", ":", "fw", ".", "Backend", ".", "WatchMachineFilesystemAttachments", "(", "m", ")", ",", "modelFilesystemAttachments", ":", "fw", ".", "Backend", ".", "WatchModelFilesystemAttachments", "(", ")", ",", "modelVolumeAttachments", ":", "fw", ".", "Backend", ".", "WatchModelVolumeAttachments", "(", ")", ",", "modelVolumesAttached", ":", "names", ".", "NewSet", "(", ")", ",", "modelVolumeFilesystemAttachments", ":", "make", "(", "map", "[", "names", ".", "VolumeTag", "]", "string", ")", ",", "hostMatch", ":", "func", "(", "tag", "names", ".", "Tag", ")", "(", "bool", ",", "error", ")", "{", "return", "tag", "==", "m", ",", "nil", "\n", "}", ",", "}", "\n\n", "w", ".", "tomb", ".", "Go", "(", "func", "(", ")", "error", "{", "defer", "watcher", ".", "Stop", "(", "w", ".", "hostFilesystemAttachments", ",", "&", "w", ".", "tomb", ")", "\n", "defer", "watcher", ".", "Stop", "(", "w", ".", "modelFilesystemAttachments", ",", "&", "w", ".", "tomb", ")", "\n", "defer", "watcher", ".", "Stop", "(", "w", ".", "modelVolumeAttachments", ",", "&", "w", ".", "tomb", ")", "\n", "return", "w", ".", "loop", "(", ")", "\n", "}", ")", "\n", "return", "w", "\n", "}" ]
// WatchMachineManagedFilesystemAttachments returns a strings watcher that // reports lifecycle changes for attachments to both machine-scoped filesystems, // and model-scoped, volume-backed filesystems that are attached to the // specified machine.
[ "WatchMachineManagedFilesystemAttachments", "returns", "a", "strings", "watcher", "that", "reports", "lifecycle", "changes", "for", "attachments", "to", "both", "machine", "-", "scoped", "filesystems", "and", "model", "-", "scoped", "volume", "-", "backed", "filesystems", "that", "are", "attached", "to", "the", "specified", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/storageprovisioner/internal/filesystemwatcher/watchers.go#L258-L280
156,479
juju/juju
apiserver/facades/agent/storageprovisioner/internal/filesystemwatcher/watchers.go
WatchUnitManagedFilesystemAttachments
func (fw Watchers) WatchUnitManagedFilesystemAttachments(app names.ApplicationTag) state.StringsWatcher { w := &hostFilesystemAttachmentsWatcher{ stringsWatcherBase: stringsWatcherBase{out: make(chan []string)}, backend: fw.Backend, changes: set.NewStrings(), hostFilesystemAttachments: fw.Backend.WatchUnitFilesystemAttachments(app), modelFilesystemAttachments: fw.Backend.WatchModelFilesystemAttachments(), modelVolumeAttachments: fw.Backend.WatchModelVolumeAttachments(), modelVolumesAttached: names.NewSet(), modelVolumeFilesystemAttachments: make(map[names.VolumeTag]string), hostMatch: func(tag names.Tag) (bool, error) { unitApp, err := names.UnitApplication(tag.Id()) if err != nil { return false, errors.Trace(err) } return unitApp == app.Id(), nil }, } w.tomb.Go(func() error { defer watcher.Stop(w.hostFilesystemAttachments, &w.tomb) defer watcher.Stop(w.modelFilesystemAttachments, &w.tomb) defer watcher.Stop(w.modelVolumeAttachments, &w.tomb) return w.loop() }) return w }
go
func (fw Watchers) WatchUnitManagedFilesystemAttachments(app names.ApplicationTag) state.StringsWatcher { w := &hostFilesystemAttachmentsWatcher{ stringsWatcherBase: stringsWatcherBase{out: make(chan []string)}, backend: fw.Backend, changes: set.NewStrings(), hostFilesystemAttachments: fw.Backend.WatchUnitFilesystemAttachments(app), modelFilesystemAttachments: fw.Backend.WatchModelFilesystemAttachments(), modelVolumeAttachments: fw.Backend.WatchModelVolumeAttachments(), modelVolumesAttached: names.NewSet(), modelVolumeFilesystemAttachments: make(map[names.VolumeTag]string), hostMatch: func(tag names.Tag) (bool, error) { unitApp, err := names.UnitApplication(tag.Id()) if err != nil { return false, errors.Trace(err) } return unitApp == app.Id(), nil }, } w.tomb.Go(func() error { defer watcher.Stop(w.hostFilesystemAttachments, &w.tomb) defer watcher.Stop(w.modelFilesystemAttachments, &w.tomb) defer watcher.Stop(w.modelVolumeAttachments, &w.tomb) return w.loop() }) return w }
[ "func", "(", "fw", "Watchers", ")", "WatchUnitManagedFilesystemAttachments", "(", "app", "names", ".", "ApplicationTag", ")", "state", ".", "StringsWatcher", "{", "w", ":=", "&", "hostFilesystemAttachmentsWatcher", "{", "stringsWatcherBase", ":", "stringsWatcherBase", "{", "out", ":", "make", "(", "chan", "[", "]", "string", ")", "}", ",", "backend", ":", "fw", ".", "Backend", ",", "changes", ":", "set", ".", "NewStrings", "(", ")", ",", "hostFilesystemAttachments", ":", "fw", ".", "Backend", ".", "WatchUnitFilesystemAttachments", "(", "app", ")", ",", "modelFilesystemAttachments", ":", "fw", ".", "Backend", ".", "WatchModelFilesystemAttachments", "(", ")", ",", "modelVolumeAttachments", ":", "fw", ".", "Backend", ".", "WatchModelVolumeAttachments", "(", ")", ",", "modelVolumesAttached", ":", "names", ".", "NewSet", "(", ")", ",", "modelVolumeFilesystemAttachments", ":", "make", "(", "map", "[", "names", ".", "VolumeTag", "]", "string", ")", ",", "hostMatch", ":", "func", "(", "tag", "names", ".", "Tag", ")", "(", "bool", ",", "error", ")", "{", "unitApp", ",", "err", ":=", "names", ".", "UnitApplication", "(", "tag", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "unitApp", "==", "app", ".", "Id", "(", ")", ",", "nil", "\n", "}", ",", "}", "\n\n", "w", ".", "tomb", ".", "Go", "(", "func", "(", ")", "error", "{", "defer", "watcher", ".", "Stop", "(", "w", ".", "hostFilesystemAttachments", ",", "&", "w", ".", "tomb", ")", "\n", "defer", "watcher", ".", "Stop", "(", "w", ".", "modelFilesystemAttachments", ",", "&", "w", ".", "tomb", ")", "\n", "defer", "watcher", ".", "Stop", "(", "w", ".", "modelVolumeAttachments", ",", "&", "w", ".", "tomb", ")", "\n", "return", "w", ".", "loop", "(", ")", "\n", "}", ")", "\n", "return", "w", "\n", "}" ]
// WatchMachineManagedFilesystemAttachments returns a strings watcher that // reports lifecycle changes for attachments to both unit-scoped filesystems, // and model-scoped, volume-backed filesystems that are attached to units of the // specified application.
[ "WatchMachineManagedFilesystemAttachments", "returns", "a", "strings", "watcher", "that", "reports", "lifecycle", "changes", "for", "attachments", "to", "both", "unit", "-", "scoped", "filesystems", "and", "model", "-", "scoped", "volume", "-", "backed", "filesystems", "that", "are", "attached", "to", "units", "of", "the", "specified", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/storageprovisioner/internal/filesystemwatcher/watchers.go#L286-L312
156,480
juju/juju
worker/charmrevision/charmrevisionmanifold/manifold.go
Manifold
func Manifold(config ManifoldConfig) dependency.Manifold { return dependency.Manifold{ Inputs: []string{ config.APICallerName, config.ClockName, }, Start: func(context dependency.Context) (worker.Worker, error) { var clock clock.Clock if err := context.Get(config.ClockName, &clock); err != nil { return nil, errors.Trace(err) } var apiCaller base.APICaller if err := context.Get(config.APICallerName, &apiCaller); err != nil { return nil, errors.Trace(err) } facade, err := config.NewFacade(apiCaller) if err != nil { return nil, errors.Annotatef(err, "cannot create facade") } worker, err := config.NewWorker(charmrevision.Config{ RevisionUpdater: facade, Clock: clock, Period: config.Period, }) if err != nil { return nil, errors.Annotatef(err, "cannot create worker") } return worker, nil }, } }
go
func Manifold(config ManifoldConfig) dependency.Manifold { return dependency.Manifold{ Inputs: []string{ config.APICallerName, config.ClockName, }, Start: func(context dependency.Context) (worker.Worker, error) { var clock clock.Clock if err := context.Get(config.ClockName, &clock); err != nil { return nil, errors.Trace(err) } var apiCaller base.APICaller if err := context.Get(config.APICallerName, &apiCaller); err != nil { return nil, errors.Trace(err) } facade, err := config.NewFacade(apiCaller) if err != nil { return nil, errors.Annotatef(err, "cannot create facade") } worker, err := config.NewWorker(charmrevision.Config{ RevisionUpdater: facade, Clock: clock, Period: config.Period, }) if err != nil { return nil, errors.Annotatef(err, "cannot create worker") } return worker, nil }, } }
[ "func", "Manifold", "(", "config", "ManifoldConfig", ")", "dependency", ".", "Manifold", "{", "return", "dependency", ".", "Manifold", "{", "Inputs", ":", "[", "]", "string", "{", "config", ".", "APICallerName", ",", "config", ".", "ClockName", ",", "}", ",", "Start", ":", "func", "(", "context", "dependency", ".", "Context", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "var", "clock", "clock", ".", "Clock", "\n", "if", "err", ":=", "context", ".", "Get", "(", "config", ".", "ClockName", ",", "&", "clock", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "var", "apiCaller", "base", ".", "APICaller", "\n", "if", "err", ":=", "context", ".", "Get", "(", "config", ".", "APICallerName", ",", "&", "apiCaller", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "facade", ",", "err", ":=", "config", ".", "NewFacade", "(", "apiCaller", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "worker", ",", "err", ":=", "config", ".", "NewWorker", "(", "charmrevision", ".", "Config", "{", "RevisionUpdater", ":", "facade", ",", "Clock", ":", "clock", ",", "Period", ":", "config", ".", "Period", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "worker", ",", "nil", "\n", "}", ",", "}", "\n", "}" ]
// Manifold returns a dependency.Manifold that runs a charm revision worker // according to the supplied configuration.
[ "Manifold", "returns", "a", "dependency", ".", "Manifold", "that", "runs", "a", "charm", "revision", "worker", "according", "to", "the", "supplied", "configuration", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/charmrevision/charmrevisionmanifold/manifold.go#L38-L69
156,481
juju/juju
worker/charmrevision/charmrevisionmanifold/manifold.go
NewAPIFacade
func NewAPIFacade(apiCaller base.APICaller) (Facade, error) { return charmrevisionupdater.NewState(apiCaller), nil }
go
func NewAPIFacade(apiCaller base.APICaller) (Facade, error) { return charmrevisionupdater.NewState(apiCaller), nil }
[ "func", "NewAPIFacade", "(", "apiCaller", "base", ".", "APICaller", ")", "(", "Facade", ",", "error", ")", "{", "return", "charmrevisionupdater", ".", "NewState", "(", "apiCaller", ")", ",", "nil", "\n", "}" ]
// NewAPIFacade returns a Facade backed by the supplied APICaller.
[ "NewAPIFacade", "returns", "a", "Facade", "backed", "by", "the", "supplied", "APICaller", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/charmrevision/charmrevisionmanifold/manifold.go#L72-L74
156,482
juju/juju
component/all/all.go
markRegistered
func markRegistered(component, part string) bool { parts, ok := registered[component] if !ok { parts = set.NewStrings() registered[component] = parts } if parts.Contains(part) { return false } parts.Add(part) return true }
go
func markRegistered(component, part string) bool { parts, ok := registered[component] if !ok { parts = set.NewStrings() registered[component] = parts } if parts.Contains(part) { return false } parts.Add(part) return true }
[ "func", "markRegistered", "(", "component", ",", "part", "string", ")", "bool", "{", "parts", ",", "ok", ":=", "registered", "[", "component", "]", "\n", "if", "!", "ok", "{", "parts", "=", "set", ".", "NewStrings", "(", ")", "\n", "registered", "[", "component", "]", "=", "parts", "\n", "}", "\n", "if", "parts", ".", "Contains", "(", "part", ")", "{", "return", "false", "\n", "}", "\n", "parts", ".", "Add", "(", "part", ")", "\n", "return", "true", "\n", "}" ]
// markRegistered helps components track which things they've // registered. If the part has already been registered then false is // returned, indicating that marking failed. This way components can // ensure a part is registered only once.
[ "markRegistered", "helps", "components", "track", "which", "things", "they", "ve", "registered", ".", "If", "the", "part", "has", "already", "been", "registered", "then", "false", "is", "returned", "indicating", "that", "marking", "failed", ".", "This", "way", "components", "can", "ensure", "a", "part", "is", "registered", "only", "once", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/component/all/all.go#L57-L68
156,483
juju/juju
provider/oracle/networking.go
DeleteMachineVnicSet
func (o *OracleEnviron) DeleteMachineVnicSet(machineId string) error { if err := o.RemoveACLAndRules(machineId); err != nil { // A method not allowed error denotes that this feature // is not enabled. Probably a trial account, so not really an error if !oci.IsMethodNotAllowed(err) { return errors.Trace(err) } } name := o.client.ComposeName(o.namespace.Value(machineId)) if err := o.client.DeleteVnicSet(name); err != nil { if !oci.IsNotFound(err) && !oci.IsMethodNotAllowed(err) { return err } } return nil }
go
func (o *OracleEnviron) DeleteMachineVnicSet(machineId string) error { if err := o.RemoveACLAndRules(machineId); err != nil { // A method not allowed error denotes that this feature // is not enabled. Probably a trial account, so not really an error if !oci.IsMethodNotAllowed(err) { return errors.Trace(err) } } name := o.client.ComposeName(o.namespace.Value(machineId)) if err := o.client.DeleteVnicSet(name); err != nil { if !oci.IsNotFound(err) && !oci.IsMethodNotAllowed(err) { return err } } return nil }
[ "func", "(", "o", "*", "OracleEnviron", ")", "DeleteMachineVnicSet", "(", "machineId", "string", ")", "error", "{", "if", "err", ":=", "o", ".", "RemoveACLAndRules", "(", "machineId", ")", ";", "err", "!=", "nil", "{", "// A method not allowed error denotes that this feature", "// is not enabled. Probably a trial account, so not really an error", "if", "!", "oci", ".", "IsMethodNotAllowed", "(", "err", ")", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "name", ":=", "o", ".", "client", ".", "ComposeName", "(", "o", ".", "namespace", ".", "Value", "(", "machineId", ")", ")", "\n", "if", "err", ":=", "o", ".", "client", ".", "DeleteVnicSet", "(", "name", ")", ";", "err", "!=", "nil", "{", "if", "!", "oci", ".", "IsNotFound", "(", "err", ")", "&&", "!", "oci", ".", "IsMethodNotAllowed", "(", "err", ")", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DeleteMachineVnicSet will delete the machine vNIC set and any ACLs bound to it.
[ "DeleteMachineVnicSet", "will", "delete", "the", "machine", "vNIC", "set", "and", "any", "ACLs", "bound", "to", "it", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oracle/networking.go#L38-L53
156,484
juju/juju
container/lxd/server.go
HasSupport
func HasSupport() bool { t := os.HostOS() for _, v := range osSupport { if v == t { return true } } return false }
go
func HasSupport() bool { t := os.HostOS() for _, v := range osSupport { if v == t { return true } } return false }
[ "func", "HasSupport", "(", ")", "bool", "{", "t", ":=", "os", ".", "HostOS", "(", ")", "\n", "for", "_", ",", "v", ":=", "range", "osSupport", "{", "if", "v", "==", "t", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// HasSupport returns true if the current OS supports LXD containers by // default
[ "HasSupport", "returns", "true", "if", "the", "current", "OS", "supports", "LXD", "containers", "by", "default" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/server.go#L22-L30
156,485
juju/juju
container/lxd/server.go
MaybeNewLocalServer
func MaybeNewLocalServer() (*Server, error) { if !HasSupport() { return nil, nil } svr, err := NewLocalServer() return svr, errors.Trace(err) }
go
func MaybeNewLocalServer() (*Server, error) { if !HasSupport() { return nil, nil } svr, err := NewLocalServer() return svr, errors.Trace(err) }
[ "func", "MaybeNewLocalServer", "(", ")", "(", "*", "Server", ",", "error", ")", "{", "if", "!", "HasSupport", "(", ")", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "svr", ",", "err", ":=", "NewLocalServer", "(", ")", "\n", "return", "svr", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// MaybeNewLocalServer returns a Server based on a local socket connection, // if running on an OS supporting LXD containers by default. // Otherwise a nil server is returned.
[ "MaybeNewLocalServer", "returns", "a", "Server", "based", "on", "a", "local", "socket", "connection", "if", "running", "on", "an", "OS", "supporting", "LXD", "containers", "by", "default", ".", "Otherwise", "a", "nil", "server", "is", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/server.go#L56-L62
156,486
juju/juju
container/lxd/server.go
NewLocalServer
func NewLocalServer() (*Server, error) { cSvr, err := ConnectLocal() if err != nil { return nil, errors.Trace(err) } svr, err := NewServer(cSvr) return svr, errors.Trace(err) }
go
func NewLocalServer() (*Server, error) { cSvr, err := ConnectLocal() if err != nil { return nil, errors.Trace(err) } svr, err := NewServer(cSvr) return svr, errors.Trace(err) }
[ "func", "NewLocalServer", "(", ")", "(", "*", "Server", ",", "error", ")", "{", "cSvr", ",", "err", ":=", "ConnectLocal", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "svr", ",", "err", ":=", "NewServer", "(", "cSvr", ")", "\n", "return", "svr", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// NewLocalServer returns a Server based on a local socket connection.
[ "NewLocalServer", "returns", "a", "Server", "based", "on", "a", "local", "socket", "connection", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/server.go#L65-L72
156,487
juju/juju
container/lxd/server.go
NewRemoteServer
func NewRemoteServer(spec ServerSpec) (*Server, error) { if err := spec.Validate(); err != nil { return nil, errors.Trace(err) } // Skip the get, because we know that we're going to request it // when calling new server, preventing the double request. spec.connectionArgs.SkipGetServer = true cSvr, err := ConnectRemote(spec) if err != nil { return nil, errors.Trace(err) } svr, err := NewServer(cSvr) return svr, err }
go
func NewRemoteServer(spec ServerSpec) (*Server, error) { if err := spec.Validate(); err != nil { return nil, errors.Trace(err) } // Skip the get, because we know that we're going to request it // when calling new server, preventing the double request. spec.connectionArgs.SkipGetServer = true cSvr, err := ConnectRemote(spec) if err != nil { return nil, errors.Trace(err) } svr, err := NewServer(cSvr) return svr, err }
[ "func", "NewRemoteServer", "(", "spec", "ServerSpec", ")", "(", "*", "Server", ",", "error", ")", "{", "if", "err", ":=", "spec", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// Skip the get, because we know that we're going to request it", "// when calling new server, preventing the double request.", "spec", ".", "connectionArgs", ".", "SkipGetServer", "=", "true", "\n", "cSvr", ",", "err", ":=", "ConnectRemote", "(", "spec", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "svr", ",", "err", ":=", "NewServer", "(", "cSvr", ")", "\n", "return", "svr", ",", "err", "\n", "}" ]
// NewRemoteServer returns a Server based on a remote connection.
[ "NewRemoteServer", "returns", "a", "Server", "based", "on", "a", "remote", "connection", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/server.go#L75-L89
156,488
juju/juju
container/lxd/server.go
NewServer
func NewServer(svr lxd.ContainerServer) (*Server, error) { info, _, err := svr.GetServer() if err != nil { return nil, errors.Trace(err) } apiExt := info.APIExtensions name := info.Environment.ServerName clustered := info.Environment.ServerClustered if name == "" && !clustered { // If the name is set to empty and clustering is false, then it's highly // likely that we're on an older version of LXD. So in that case we // need to set the name to something and internally LXD sets this type // of node to "none". // LP:#1786309 name = "none" } serverCertificate := info.Environment.Certificate hostArch := arch.NormaliseArch(info.Environment.KernelArchitecture) return &Server{ ContainerServer: svr, name: name, clustered: clustered, serverCertificate: serverCertificate, hostArch: hostArch, networkAPISupport: shared.StringInSlice("network", apiExt), clusterAPISupport: shared.StringInSlice("clustering", apiExt), storageAPISupport: shared.StringInSlice("storage", apiExt), serverVersion: info.Environment.ServerVersion, clock: clock.WallClock, }, nil }
go
func NewServer(svr lxd.ContainerServer) (*Server, error) { info, _, err := svr.GetServer() if err != nil { return nil, errors.Trace(err) } apiExt := info.APIExtensions name := info.Environment.ServerName clustered := info.Environment.ServerClustered if name == "" && !clustered { // If the name is set to empty and clustering is false, then it's highly // likely that we're on an older version of LXD. So in that case we // need to set the name to something and internally LXD sets this type // of node to "none". // LP:#1786309 name = "none" } serverCertificate := info.Environment.Certificate hostArch := arch.NormaliseArch(info.Environment.KernelArchitecture) return &Server{ ContainerServer: svr, name: name, clustered: clustered, serverCertificate: serverCertificate, hostArch: hostArch, networkAPISupport: shared.StringInSlice("network", apiExt), clusterAPISupport: shared.StringInSlice("clustering", apiExt), storageAPISupport: shared.StringInSlice("storage", apiExt), serverVersion: info.Environment.ServerVersion, clock: clock.WallClock, }, nil }
[ "func", "NewServer", "(", "svr", "lxd", ".", "ContainerServer", ")", "(", "*", "Server", ",", "error", ")", "{", "info", ",", "_", ",", "err", ":=", "svr", ".", "GetServer", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "apiExt", ":=", "info", ".", "APIExtensions", "\n\n", "name", ":=", "info", ".", "Environment", ".", "ServerName", "\n", "clustered", ":=", "info", ".", "Environment", ".", "ServerClustered", "\n", "if", "name", "==", "\"", "\"", "&&", "!", "clustered", "{", "// If the name is set to empty and clustering is false, then it's highly", "// likely that we're on an older version of LXD. So in that case we", "// need to set the name to something and internally LXD sets this type", "// of node to \"none\".", "// LP:#1786309", "name", "=", "\"", "\"", "\n", "}", "\n", "serverCertificate", ":=", "info", ".", "Environment", ".", "Certificate", "\n", "hostArch", ":=", "arch", ".", "NormaliseArch", "(", "info", ".", "Environment", ".", "KernelArchitecture", ")", "\n\n", "return", "&", "Server", "{", "ContainerServer", ":", "svr", ",", "name", ":", "name", ",", "clustered", ":", "clustered", ",", "serverCertificate", ":", "serverCertificate", ",", "hostArch", ":", "hostArch", ",", "networkAPISupport", ":", "shared", ".", "StringInSlice", "(", "\"", "\"", ",", "apiExt", ")", ",", "clusterAPISupport", ":", "shared", ".", "StringInSlice", "(", "\"", "\"", ",", "apiExt", ")", ",", "storageAPISupport", ":", "shared", ".", "StringInSlice", "(", "\"", "\"", ",", "apiExt", ")", ",", "serverVersion", ":", "info", ".", "Environment", ".", "ServerVersion", ",", "clock", ":", "clock", ".", "WallClock", ",", "}", ",", "nil", "\n", "}" ]
// NewServer builds and returns a Server for high-level interaction with the // input LXD container server.
[ "NewServer", "builds", "and", "returns", "a", "Server", "for", "high", "-", "level", "interaction", "with", "the", "input", "LXD", "container", "server", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/server.go#L93-L126
156,489
juju/juju
container/lxd/server.go
UpdateServerConfig
func (s *Server) UpdateServerConfig(cfg map[string]string) error { svr, eTag, err := s.GetServer() if err != nil { return errors.Trace(err) } if svr.Config == nil { svr.Config = make(map[string]interface{}) } for k, v := range cfg { svr.Config[k] = v } return errors.Trace(s.UpdateServer(svr.Writable(), eTag)) }
go
func (s *Server) UpdateServerConfig(cfg map[string]string) error { svr, eTag, err := s.GetServer() if err != nil { return errors.Trace(err) } if svr.Config == nil { svr.Config = make(map[string]interface{}) } for k, v := range cfg { svr.Config[k] = v } return errors.Trace(s.UpdateServer(svr.Writable(), eTag)) }
[ "func", "(", "s", "*", "Server", ")", "UpdateServerConfig", "(", "cfg", "map", "[", "string", "]", "string", ")", "error", "{", "svr", ",", "eTag", ",", "err", ":=", "s", ".", "GetServer", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "svr", ".", "Config", "==", "nil", "{", "svr", ".", "Config", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "}", "\n", "for", "k", ",", "v", ":=", "range", "cfg", "{", "svr", ".", "Config", "[", "k", "]", "=", "v", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "s", ".", "UpdateServer", "(", "svr", ".", "Writable", "(", ")", ",", "eTag", ")", ")", "\n", "}" ]
// UpdateServerConfig updates the server configuration with the input values.
[ "UpdateServerConfig", "updates", "the", "server", "configuration", "with", "the", "input", "values", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/server.go#L138-L150
156,490
juju/juju
container/lxd/server.go
UpdateContainerConfig
func (s *Server) UpdateContainerConfig(name string, cfg map[string]string) error { container, eTag, err := s.GetContainer(name) if err != nil { return errors.Trace(err) } if container.Config == nil { container.Config = make(map[string]string) } for k, v := range cfg { container.Config[k] = v } resp, err := s.UpdateContainer(name, container.Writable(), eTag) if err != nil { return errors.Trace(err) } return errors.Trace(resp.Wait()) }
go
func (s *Server) UpdateContainerConfig(name string, cfg map[string]string) error { container, eTag, err := s.GetContainer(name) if err != nil { return errors.Trace(err) } if container.Config == nil { container.Config = make(map[string]string) } for k, v := range cfg { container.Config[k] = v } resp, err := s.UpdateContainer(name, container.Writable(), eTag) if err != nil { return errors.Trace(err) } return errors.Trace(resp.Wait()) }
[ "func", "(", "s", "*", "Server", ")", "UpdateContainerConfig", "(", "name", "string", ",", "cfg", "map", "[", "string", "]", "string", ")", "error", "{", "container", ",", "eTag", ",", "err", ":=", "s", ".", "GetContainer", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "container", ".", "Config", "==", "nil", "{", "container", ".", "Config", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "}", "\n", "for", "k", ",", "v", ":=", "range", "cfg", "{", "container", ".", "Config", "[", "k", "]", "=", "v", "\n", "}", "\n\n", "resp", ",", "err", ":=", "s", ".", "UpdateContainer", "(", "name", ",", "container", ".", "Writable", "(", ")", ",", "eTag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "resp", ".", "Wait", "(", ")", ")", "\n", "}" ]
// UpdateContainerConfig updates the configuration for the container with the // input name, using the input values.
[ "UpdateContainerConfig", "updates", "the", "configuration", "for", "the", "container", "with", "the", "input", "name", "using", "the", "input", "values", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/server.go#L154-L171
156,491
juju/juju
container/lxd/server.go
GetContainerProfiles
func (s *Server) GetContainerProfiles(name string) ([]string, error) { container, _, err := s.GetContainer(name) if err != nil { return []string{}, errors.Trace(err) } return container.Profiles, nil }
go
func (s *Server) GetContainerProfiles(name string) ([]string, error) { container, _, err := s.GetContainer(name) if err != nil { return []string{}, errors.Trace(err) } return container.Profiles, nil }
[ "func", "(", "s", "*", "Server", ")", "GetContainerProfiles", "(", "name", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "container", ",", "_", ",", "err", ":=", "s", ".", "GetContainer", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "string", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "container", ".", "Profiles", ",", "nil", "\n", "}" ]
// GetContainerProfiles returns the list of profiles that are assocated with a // container.
[ "GetContainerProfiles", "returns", "the", "list", "of", "profiles", "that", "are", "assocated", "with", "a", "container", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/server.go#L175-L181
156,492
juju/juju
container/lxd/server.go
CreateClientCertificate
func (s *Server) CreateClientCertificate(cert *Certificate) error { req, err := cert.AsCreateRequest() if err != nil { return errors.Trace(err) } return errors.Trace(s.CreateCertificate(req)) }
go
func (s *Server) CreateClientCertificate(cert *Certificate) error { req, err := cert.AsCreateRequest() if err != nil { return errors.Trace(err) } return errors.Trace(s.CreateCertificate(req)) }
[ "func", "(", "s", "*", "Server", ")", "CreateClientCertificate", "(", "cert", "*", "Certificate", ")", "error", "{", "req", ",", "err", ":=", "cert", ".", "AsCreateRequest", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "s", ".", "CreateCertificate", "(", "req", ")", ")", "\n", "}" ]
// CreateClientCertificate adds the input certificate to the server, // indicating that is for use in client communication.
[ "CreateClientCertificate", "adds", "the", "input", "certificate", "to", "the", "server", "indicating", "that", "is", "for", "use", "in", "client", "communication", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/server.go#L254-L260
156,493
juju/juju
container/lxd/server.go
HasProfile
func (s *Server) HasProfile(name string) (bool, error) { profiles, err := s.GetProfileNames() if err != nil { return false, errors.Trace(err) } for _, profile := range profiles { if profile == name { return true, nil } } return false, nil }
go
func (s *Server) HasProfile(name string) (bool, error) { profiles, err := s.GetProfileNames() if err != nil { return false, errors.Trace(err) } for _, profile := range profiles { if profile == name { return true, nil } } return false, nil }
[ "func", "(", "s", "*", "Server", ")", "HasProfile", "(", "name", "string", ")", "(", "bool", ",", "error", ")", "{", "profiles", ",", "err", ":=", "s", ".", "GetProfileNames", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "for", "_", ",", "profile", ":=", "range", "profiles", "{", "if", "profile", "==", "name", "{", "return", "true", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "false", ",", "nil", "\n", "}" ]
// HasProfile interrogates the known profile names and returns a boolean // indicating whether a profile with the input name exists.
[ "HasProfile", "interrogates", "the", "known", "profile", "names", "and", "returns", "a", "boolean", "indicating", "whether", "a", "profile", "with", "the", "input", "name", "exists", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/server.go#L264-L275
156,494
juju/juju
container/lxd/server.go
CreateProfileWithConfig
func (s *Server) CreateProfileWithConfig(name string, cfg map[string]string) error { req := api.ProfilesPost{ Name: name, ProfilePut: api.ProfilePut{ Config: cfg, }, } return errors.Trace(s.CreateProfile(req)) }
go
func (s *Server) CreateProfileWithConfig(name string, cfg map[string]string) error { req := api.ProfilesPost{ Name: name, ProfilePut: api.ProfilePut{ Config: cfg, }, } return errors.Trace(s.CreateProfile(req)) }
[ "func", "(", "s", "*", "Server", ")", "CreateProfileWithConfig", "(", "name", "string", ",", "cfg", "map", "[", "string", "]", "string", ")", "error", "{", "req", ":=", "api", ".", "ProfilesPost", "{", "Name", ":", "name", ",", "ProfilePut", ":", "api", ".", "ProfilePut", "{", "Config", ":", "cfg", ",", "}", ",", "}", "\n", "return", "errors", ".", "Trace", "(", "s", ".", "CreateProfile", "(", "req", ")", ")", "\n", "}" ]
// CreateProfileWithConfig creates a new profile with the input name and config.
[ "CreateProfileWithConfig", "creates", "a", "new", "profile", "with", "the", "input", "name", "and", "config", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/lxd/server.go#L278-L286
156,495
juju/juju
apiserver/facades/client/client/client.go
NewFacadeV1
func NewFacadeV1(ctx facade.Context) (*ClientV1, error) { client, err := newFacade(ctx) if err != nil { return nil, errors.Trace(err) } return &ClientV1{client}, nil }
go
func NewFacadeV1(ctx facade.Context) (*ClientV1, error) { client, err := newFacade(ctx) if err != nil { return nil, errors.Trace(err) } return &ClientV1{client}, nil }
[ "func", "NewFacadeV1", "(", "ctx", "facade", ".", "Context", ")", "(", "*", "ClientV1", ",", "error", ")", "{", "client", ",", "err", ":=", "newFacade", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "&", "ClientV1", "{", "client", "}", ",", "nil", "\n", "}" ]
// NewFacadeV1 creates a version 1 Client facade to handle API requests.
[ "NewFacadeV1", "creates", "a", "version", "1", "Client", "facade", "to", "handle", "API", "requests", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/client.go#L131-L137
156,496
juju/juju
apiserver/facades/client/client/client.go
NewClient
func NewClient( backend Backend, pool Pool, modelConfigAPI *modelconfig.ModelConfigAPIV1, resources facade.Resources, authorizer facade.Authorizer, presence facade.Presence, statusSetter *common.StatusSetter, toolsFinder *common.ToolsFinder, newEnviron func() (environs.BootstrapEnviron, error), blockChecker *common.BlockChecker, callCtx context.ProviderCallContext, leadershipReader leadership.Reader, ) (*Client, error) { if !authorizer.AuthClient() { return nil, common.ErrPerm } client := &Client{ ModelConfigAPIV1: modelConfigAPI, api: &API{ stateAccessor: backend, pool: pool, auth: authorizer, resources: resources, presence: presence, statusSetter: statusSetter, toolsFinder: toolsFinder, leadershipReader: leadershipReader, }, newEnviron: newEnviron, check: blockChecker, callContext: callCtx, } return client, nil }
go
func NewClient( backend Backend, pool Pool, modelConfigAPI *modelconfig.ModelConfigAPIV1, resources facade.Resources, authorizer facade.Authorizer, presence facade.Presence, statusSetter *common.StatusSetter, toolsFinder *common.ToolsFinder, newEnviron func() (environs.BootstrapEnviron, error), blockChecker *common.BlockChecker, callCtx context.ProviderCallContext, leadershipReader leadership.Reader, ) (*Client, error) { if !authorizer.AuthClient() { return nil, common.ErrPerm } client := &Client{ ModelConfigAPIV1: modelConfigAPI, api: &API{ stateAccessor: backend, pool: pool, auth: authorizer, resources: resources, presence: presence, statusSetter: statusSetter, toolsFinder: toolsFinder, leadershipReader: leadershipReader, }, newEnviron: newEnviron, check: blockChecker, callContext: callCtx, } return client, nil }
[ "func", "NewClient", "(", "backend", "Backend", ",", "pool", "Pool", ",", "modelConfigAPI", "*", "modelconfig", ".", "ModelConfigAPIV1", ",", "resources", "facade", ".", "Resources", ",", "authorizer", "facade", ".", "Authorizer", ",", "presence", "facade", ".", "Presence", ",", "statusSetter", "*", "common", ".", "StatusSetter", ",", "toolsFinder", "*", "common", ".", "ToolsFinder", ",", "newEnviron", "func", "(", ")", "(", "environs", ".", "BootstrapEnviron", ",", "error", ")", ",", "blockChecker", "*", "common", ".", "BlockChecker", ",", "callCtx", "context", ".", "ProviderCallContext", ",", "leadershipReader", "leadership", ".", "Reader", ",", ")", "(", "*", "Client", ",", "error", ")", "{", "if", "!", "authorizer", ".", "AuthClient", "(", ")", "{", "return", "nil", ",", "common", ".", "ErrPerm", "\n", "}", "\n", "client", ":=", "&", "Client", "{", "ModelConfigAPIV1", ":", "modelConfigAPI", ",", "api", ":", "&", "API", "{", "stateAccessor", ":", "backend", ",", "pool", ":", "pool", ",", "auth", ":", "authorizer", ",", "resources", ":", "resources", ",", "presence", ":", "presence", ",", "statusSetter", ":", "statusSetter", ",", "toolsFinder", ":", "toolsFinder", ",", "leadershipReader", ":", "leadershipReader", ",", "}", ",", "newEnviron", ":", "newEnviron", ",", "check", ":", "blockChecker", ",", "callContext", ":", "callCtx", ",", "}", "\n", "return", "client", ",", "nil", "\n", "}" ]
// NewClient creates a new instance of the Client Facade.
[ "NewClient", "creates", "a", "new", "instance", "of", "the", "Client", "Facade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/client.go#L196-L230
156,497
juju/juju
apiserver/facades/client/client/client.go
WatchAll
func (c *Client) WatchAll() (params.AllWatcherId, error) { if err := c.checkCanRead(); err != nil { return params.AllWatcherId{}, err } model, err := c.api.stateAccessor.Model() if err != nil { return params.AllWatcherId{}, errors.Trace(err) } // Since we know this is a user tag (because AuthClient is true), // we just do the type assertion to the UserTag. apiUser, _ := c.api.auth.GetAuthTag().(names.UserTag) isAdmin, err := common.HasModelAdmin(c.api.auth, apiUser, c.api.stateAccessor.ControllerTag(), model) if err != nil { return params.AllWatcherId{}, errors.Trace(err) } watchParams := state.WatchParams{IncludeOffers: isAdmin} w := c.api.stateAccessor.Watch(watchParams) return params.AllWatcherId{ AllWatcherId: c.api.resources.Register(w), }, nil }
go
func (c *Client) WatchAll() (params.AllWatcherId, error) { if err := c.checkCanRead(); err != nil { return params.AllWatcherId{}, err } model, err := c.api.stateAccessor.Model() if err != nil { return params.AllWatcherId{}, errors.Trace(err) } // Since we know this is a user tag (because AuthClient is true), // we just do the type assertion to the UserTag. apiUser, _ := c.api.auth.GetAuthTag().(names.UserTag) isAdmin, err := common.HasModelAdmin(c.api.auth, apiUser, c.api.stateAccessor.ControllerTag(), model) if err != nil { return params.AllWatcherId{}, errors.Trace(err) } watchParams := state.WatchParams{IncludeOffers: isAdmin} w := c.api.stateAccessor.Watch(watchParams) return params.AllWatcherId{ AllWatcherId: c.api.resources.Register(w), }, nil }
[ "func", "(", "c", "*", "Client", ")", "WatchAll", "(", ")", "(", "params", ".", "AllWatcherId", ",", "error", ")", "{", "if", "err", ":=", "c", ".", "checkCanRead", "(", ")", ";", "err", "!=", "nil", "{", "return", "params", ".", "AllWatcherId", "{", "}", ",", "err", "\n", "}", "\n", "model", ",", "err", ":=", "c", ".", "api", ".", "stateAccessor", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "AllWatcherId", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// Since we know this is a user tag (because AuthClient is true),", "// we just do the type assertion to the UserTag.", "apiUser", ",", "_", ":=", "c", ".", "api", ".", "auth", ".", "GetAuthTag", "(", ")", ".", "(", "names", ".", "UserTag", ")", "\n", "isAdmin", ",", "err", ":=", "common", ".", "HasModelAdmin", "(", "c", ".", "api", ".", "auth", ",", "apiUser", ",", "c", ".", "api", ".", "stateAccessor", ".", "ControllerTag", "(", ")", ",", "model", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "AllWatcherId", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "watchParams", ":=", "state", ".", "WatchParams", "{", "IncludeOffers", ":", "isAdmin", "}", "\n\n", "w", ":=", "c", ".", "api", ".", "stateAccessor", ".", "Watch", "(", "watchParams", ")", "\n", "return", "params", ".", "AllWatcherId", "{", "AllWatcherId", ":", "c", ".", "api", ".", "resources", ".", "Register", "(", "w", ")", ",", "}", ",", "nil", "\n", "}" ]
// WatchAll initiates a watcher for entities in the connected model.
[ "WatchAll", "initiates", "a", "watcher", "for", "entities", "in", "the", "connected", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/client.go#L233-L255
156,498
juju/juju
apiserver/facades/client/client/client.go
Resolved
func (c *Client) Resolved(p params.Resolved) error { if err := c.checkCanWrite(); err != nil { return err } if err := c.check.ChangeAllowed(); err != nil { return errors.Trace(err) } unit, err := c.api.stateAccessor.Unit(p.UnitName) if err != nil { return err } return unit.Resolve(p.Retry) }
go
func (c *Client) Resolved(p params.Resolved) error { if err := c.checkCanWrite(); err != nil { return err } if err := c.check.ChangeAllowed(); err != nil { return errors.Trace(err) } unit, err := c.api.stateAccessor.Unit(p.UnitName) if err != nil { return err } return unit.Resolve(p.Retry) }
[ "func", "(", "c", "*", "Client", ")", "Resolved", "(", "p", "params", ".", "Resolved", ")", "error", "{", "if", "err", ":=", "c", ".", "checkCanWrite", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "c", ".", "check", ".", "ChangeAllowed", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "unit", ",", "err", ":=", "c", ".", "api", ".", "stateAccessor", ".", "Unit", "(", "p", ".", "UnitName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "unit", ".", "Resolve", "(", "p", ".", "Retry", ")", "\n", "}" ]
// Resolved implements the server side of Client.Resolved.
[ "Resolved", "implements", "the", "server", "side", "of", "Client", ".", "Resolved", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/client.go#L258-L270
156,499
juju/juju
apiserver/facades/client/client/client.go
PublicAddress
func (c *Client) PublicAddress(p params.PublicAddress) (results params.PublicAddressResults, err error) { if err := c.checkCanRead(); err != nil { return params.PublicAddressResults{}, err } switch { case names.IsValidMachine(p.Target): machine, err := c.api.stateAccessor.Machine(p.Target) if err != nil { return results, err } addr, err := machine.PublicAddress() if err != nil { return results, errors.Annotatef(err, "error fetching address for machine %q", machine) } return params.PublicAddressResults{PublicAddress: addr.Value}, nil case names.IsValidUnit(p.Target): unit, err := c.api.stateAccessor.Unit(p.Target) if err != nil { return results, err } addr, err := unit.PublicAddress() if err != nil { return results, errors.Annotatef(err, "error fetching address for unit %q", unit) } return params.PublicAddressResults{PublicAddress: addr.Value}, nil } return results, errors.Errorf("unknown unit or machine %q", p.Target) }
go
func (c *Client) PublicAddress(p params.PublicAddress) (results params.PublicAddressResults, err error) { if err := c.checkCanRead(); err != nil { return params.PublicAddressResults{}, err } switch { case names.IsValidMachine(p.Target): machine, err := c.api.stateAccessor.Machine(p.Target) if err != nil { return results, err } addr, err := machine.PublicAddress() if err != nil { return results, errors.Annotatef(err, "error fetching address for machine %q", machine) } return params.PublicAddressResults{PublicAddress: addr.Value}, nil case names.IsValidUnit(p.Target): unit, err := c.api.stateAccessor.Unit(p.Target) if err != nil { return results, err } addr, err := unit.PublicAddress() if err != nil { return results, errors.Annotatef(err, "error fetching address for unit %q", unit) } return params.PublicAddressResults{PublicAddress: addr.Value}, nil } return results, errors.Errorf("unknown unit or machine %q", p.Target) }
[ "func", "(", "c", "*", "Client", ")", "PublicAddress", "(", "p", "params", ".", "PublicAddress", ")", "(", "results", "params", ".", "PublicAddressResults", ",", "err", "error", ")", "{", "if", "err", ":=", "c", ".", "checkCanRead", "(", ")", ";", "err", "!=", "nil", "{", "return", "params", ".", "PublicAddressResults", "{", "}", ",", "err", "\n", "}", "\n\n", "switch", "{", "case", "names", ".", "IsValidMachine", "(", "p", ".", "Target", ")", ":", "machine", ",", "err", ":=", "c", ".", "api", ".", "stateAccessor", ".", "Machine", "(", "p", ".", "Target", ")", "\n", "if", "err", "!=", "nil", "{", "return", "results", ",", "err", "\n", "}", "\n", "addr", ",", "err", ":=", "machine", ".", "PublicAddress", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "results", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "machine", ")", "\n", "}", "\n", "return", "params", ".", "PublicAddressResults", "{", "PublicAddress", ":", "addr", ".", "Value", "}", ",", "nil", "\n\n", "case", "names", ".", "IsValidUnit", "(", "p", ".", "Target", ")", ":", "unit", ",", "err", ":=", "c", ".", "api", ".", "stateAccessor", ".", "Unit", "(", "p", ".", "Target", ")", "\n", "if", "err", "!=", "nil", "{", "return", "results", ",", "err", "\n", "}", "\n", "addr", ",", "err", ":=", "unit", ".", "PublicAddress", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "results", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "unit", ")", "\n", "}", "\n", "return", "params", ".", "PublicAddressResults", "{", "PublicAddress", ":", "addr", ".", "Value", "}", ",", "nil", "\n", "}", "\n", "return", "results", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "p", ".", "Target", ")", "\n", "}" ]
// PublicAddress implements the server side of Client.PublicAddress.
[ "PublicAddress", "implements", "the", "server", "side", "of", "Client", ".", "PublicAddress", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/client.go#L273-L302