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
155,200
juju/juju
provider/azure/instance.go
Addresses
func (inst *azureInstance) Addresses(ctx context.ProviderCallContext) ([]jujunetwork.Address, error) { addresses := make([]jujunetwork.Address, 0, len(inst.networkInterfaces)+len(inst.publicIPAddresses)) for _, nic := range inst.networkInterfaces { if nic.IPConfigurations == nil { continue } for _, ipConfiguration := range *nic.IPConfigurations { privateIpAddress := ipConfiguration.PrivateIPAddress if privateIpAddress == nil { continue } addresses = append(addresses, jujunetwork.NewScopedAddress( to.String(privateIpAddress), jujunetwork.ScopeCloudLocal, )) } } for _, pip := range inst.publicIPAddresses { if pip.IPAddress == nil { continue } addresses = append(addresses, jujunetwork.NewScopedAddress( to.String(pip.IPAddress), jujunetwork.ScopePublic, )) } return addresses, nil }
go
func (inst *azureInstance) Addresses(ctx context.ProviderCallContext) ([]jujunetwork.Address, error) { addresses := make([]jujunetwork.Address, 0, len(inst.networkInterfaces)+len(inst.publicIPAddresses)) for _, nic := range inst.networkInterfaces { if nic.IPConfigurations == nil { continue } for _, ipConfiguration := range *nic.IPConfigurations { privateIpAddress := ipConfiguration.PrivateIPAddress if privateIpAddress == nil { continue } addresses = append(addresses, jujunetwork.NewScopedAddress( to.String(privateIpAddress), jujunetwork.ScopeCloudLocal, )) } } for _, pip := range inst.publicIPAddresses { if pip.IPAddress == nil { continue } addresses = append(addresses, jujunetwork.NewScopedAddress( to.String(pip.IPAddress), jujunetwork.ScopePublic, )) } return addresses, nil }
[ "func", "(", "inst", "*", "azureInstance", ")", "Addresses", "(", "ctx", "context", ".", "ProviderCallContext", ")", "(", "[", "]", "jujunetwork", ".", "Address", ",", "error", ")", "{", "addresses", ":=", "make", "(", "[", "]", "jujunetwork", ".", "Address", ",", "0", ",", "len", "(", "inst", ".", "networkInterfaces", ")", "+", "len", "(", "inst", ".", "publicIPAddresses", ")", ")", "\n", "for", "_", ",", "nic", ":=", "range", "inst", ".", "networkInterfaces", "{", "if", "nic", ".", "IPConfigurations", "==", "nil", "{", "continue", "\n", "}", "\n", "for", "_", ",", "ipConfiguration", ":=", "range", "*", "nic", ".", "IPConfigurations", "{", "privateIpAddress", ":=", "ipConfiguration", ".", "PrivateIPAddress", "\n", "if", "privateIpAddress", "==", "nil", "{", "continue", "\n", "}", "\n", "addresses", "=", "append", "(", "addresses", ",", "jujunetwork", ".", "NewScopedAddress", "(", "to", ".", "String", "(", "privateIpAddress", ")", ",", "jujunetwork", ".", "ScopeCloudLocal", ",", ")", ")", "\n", "}", "\n", "}", "\n", "for", "_", ",", "pip", ":=", "range", "inst", ".", "publicIPAddresses", "{", "if", "pip", ".", "IPAddress", "==", "nil", "{", "continue", "\n", "}", "\n", "addresses", "=", "append", "(", "addresses", ",", "jujunetwork", ".", "NewScopedAddress", "(", "to", ".", "String", "(", "pip", ".", "IPAddress", ")", ",", "jujunetwork", ".", "ScopePublic", ",", ")", ")", "\n", "}", "\n", "return", "addresses", ",", "nil", "\n", "}" ]
// Addresses is specified in the Instance interface.
[ "Addresses", "is", "specified", "in", "the", "Instance", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/azure/instance.go#L151-L178
155,201
juju/juju
provider/azure/instance.go
primaryNetworkAddress
func (inst *azureInstance) primaryNetworkAddress() (jujunetwork.Address, error) { for _, nic := range inst.networkInterfaces { if nic.IPConfigurations == nil { continue } for _, ipConfiguration := range *nic.IPConfigurations { if ipConfiguration.Subnet == nil { continue } if !to.Bool(ipConfiguration.Primary) { continue } privateIpAddress := ipConfiguration.PrivateIPAddress if privateIpAddress == nil { continue } return jujunetwork.NewScopedAddress( to.String(privateIpAddress), jujunetwork.ScopeCloudLocal, ), nil } } return jujunetwork.Address{}, errors.NotFoundf("internal network address") }
go
func (inst *azureInstance) primaryNetworkAddress() (jujunetwork.Address, error) { for _, nic := range inst.networkInterfaces { if nic.IPConfigurations == nil { continue } for _, ipConfiguration := range *nic.IPConfigurations { if ipConfiguration.Subnet == nil { continue } if !to.Bool(ipConfiguration.Primary) { continue } privateIpAddress := ipConfiguration.PrivateIPAddress if privateIpAddress == nil { continue } return jujunetwork.NewScopedAddress( to.String(privateIpAddress), jujunetwork.ScopeCloudLocal, ), nil } } return jujunetwork.Address{}, errors.NotFoundf("internal network address") }
[ "func", "(", "inst", "*", "azureInstance", ")", "primaryNetworkAddress", "(", ")", "(", "jujunetwork", ".", "Address", ",", "error", ")", "{", "for", "_", ",", "nic", ":=", "range", "inst", ".", "networkInterfaces", "{", "if", "nic", ".", "IPConfigurations", "==", "nil", "{", "continue", "\n", "}", "\n", "for", "_", ",", "ipConfiguration", ":=", "range", "*", "nic", ".", "IPConfigurations", "{", "if", "ipConfiguration", ".", "Subnet", "==", "nil", "{", "continue", "\n", "}", "\n", "if", "!", "to", ".", "Bool", "(", "ipConfiguration", ".", "Primary", ")", "{", "continue", "\n", "}", "\n", "privateIpAddress", ":=", "ipConfiguration", ".", "PrivateIPAddress", "\n", "if", "privateIpAddress", "==", "nil", "{", "continue", "\n", "}", "\n", "return", "jujunetwork", ".", "NewScopedAddress", "(", "to", ".", "String", "(", "privateIpAddress", ")", ",", "jujunetwork", ".", "ScopeCloudLocal", ",", ")", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "jujunetwork", ".", "Address", "{", "}", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ")", "\n", "}" ]
// primaryNetworkAddress returns the instance's primary jujunetwork.Address for // the internal virtual network. This address is used to identify the machine in // network security rules.
[ "primaryNetworkAddress", "returns", "the", "instance", "s", "primary", "jujunetwork", ".", "Address", "for", "the", "internal", "virtual", "network", ".", "This", "address", "is", "used", "to", "identify", "the", "machine", "in", "network", "security", "rules", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/azure/instance.go#L183-L206
155,202
juju/juju
provider/azure/instance.go
ClosePorts
func (inst *azureInstance) ClosePorts(ctx context.ProviderCallContext, machineId string, rules []jujunetwork.IngressRule) error { securityRuleClient := network.SecurityRulesClient{inst.env.network} securityGroupName := internalSecurityGroupName // Delete rules one at a time; this is necessary to avoid trampling // on changes made by the provisioner. vmName := resourceName(names.NewMachineTag(machineId)) prefix := instanceNetworkSecurityRulePrefix(instance.Id(vmName)) sdkCtx := stdcontext.Background() singleSourceIngressRules := explodeIngressRules(rules) for _, rule := range singleSourceIngressRules { ruleName := securityRuleName(prefix, rule) logger.Debugf("deleting security rule %q", ruleName) future, err := securityRuleClient.Delete( stdcontext.Background(), inst.env.resourceGroup, securityGroupName, ruleName, ) if err != nil { if !isNotFoundResponse(future.Response()) { return errors.Annotatef(err, "deleting security rule %q", ruleName) } continue } err = future.WaitForCompletionRef(sdkCtx, securityRuleClient.Client) if err != nil { return errors.Annotatef(err, "deleting security rule %q", ruleName) } result, err := future.Result(securityRuleClient) if err != nil && !isNotFoundResult(result) { return errorutils.HandleCredentialError(errors.Annotatef(err, "deleting security rule %q", ruleName), ctx) } } return nil }
go
func (inst *azureInstance) ClosePorts(ctx context.ProviderCallContext, machineId string, rules []jujunetwork.IngressRule) error { securityRuleClient := network.SecurityRulesClient{inst.env.network} securityGroupName := internalSecurityGroupName // Delete rules one at a time; this is necessary to avoid trampling // on changes made by the provisioner. vmName := resourceName(names.NewMachineTag(machineId)) prefix := instanceNetworkSecurityRulePrefix(instance.Id(vmName)) sdkCtx := stdcontext.Background() singleSourceIngressRules := explodeIngressRules(rules) for _, rule := range singleSourceIngressRules { ruleName := securityRuleName(prefix, rule) logger.Debugf("deleting security rule %q", ruleName) future, err := securityRuleClient.Delete( stdcontext.Background(), inst.env.resourceGroup, securityGroupName, ruleName, ) if err != nil { if !isNotFoundResponse(future.Response()) { return errors.Annotatef(err, "deleting security rule %q", ruleName) } continue } err = future.WaitForCompletionRef(sdkCtx, securityRuleClient.Client) if err != nil { return errors.Annotatef(err, "deleting security rule %q", ruleName) } result, err := future.Result(securityRuleClient) if err != nil && !isNotFoundResult(result) { return errorutils.HandleCredentialError(errors.Annotatef(err, "deleting security rule %q", ruleName), ctx) } } return nil }
[ "func", "(", "inst", "*", "azureInstance", ")", "ClosePorts", "(", "ctx", "context", ".", "ProviderCallContext", ",", "machineId", "string", ",", "rules", "[", "]", "jujunetwork", ".", "IngressRule", ")", "error", "{", "securityRuleClient", ":=", "network", ".", "SecurityRulesClient", "{", "inst", ".", "env", ".", "network", "}", "\n", "securityGroupName", ":=", "internalSecurityGroupName", "\n\n", "// Delete rules one at a time; this is necessary to avoid trampling", "// on changes made by the provisioner.", "vmName", ":=", "resourceName", "(", "names", ".", "NewMachineTag", "(", "machineId", ")", ")", "\n", "prefix", ":=", "instanceNetworkSecurityRulePrefix", "(", "instance", ".", "Id", "(", "vmName", ")", ")", "\n", "sdkCtx", ":=", "stdcontext", ".", "Background", "(", ")", "\n\n", "singleSourceIngressRules", ":=", "explodeIngressRules", "(", "rules", ")", "\n", "for", "_", ",", "rule", ":=", "range", "singleSourceIngressRules", "{", "ruleName", ":=", "securityRuleName", "(", "prefix", ",", "rule", ")", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "ruleName", ")", "\n", "future", ",", "err", ":=", "securityRuleClient", ".", "Delete", "(", "stdcontext", ".", "Background", "(", ")", ",", "inst", ".", "env", ".", "resourceGroup", ",", "securityGroupName", ",", "ruleName", ",", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "isNotFoundResponse", "(", "future", ".", "Response", "(", ")", ")", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "ruleName", ")", "\n", "}", "\n", "continue", "\n", "}", "\n", "err", "=", "future", ".", "WaitForCompletionRef", "(", "sdkCtx", ",", "securityRuleClient", ".", "Client", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "ruleName", ")", "\n", "}", "\n", "result", ",", "err", ":=", "future", ".", "Result", "(", "securityRuleClient", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "isNotFoundResult", "(", "result", ")", "{", "return", "errorutils", ".", "HandleCredentialError", "(", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "ruleName", ")", ",", "ctx", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ClosePorts is specified in the Instance interface.
[ "ClosePorts", "is", "specified", "in", "the", "Instance", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/azure/instance.go#L305-L339
155,203
juju/juju
provider/azure/instance.go
securityRuleName
func securityRuleName(prefix string, rule jujunetwork.IngressRule) string { ruleName := fmt.Sprintf("%s%s-%d", prefix, rule.Protocol, rule.FromPort) if rule.FromPort != rule.ToPort { ruleName += fmt.Sprintf("-%d", rule.ToPort) } // The rule parameter must have a single source cidr. // Ensure the rule name can be a valid URL path component. cidr := rule.SourceCIDRs[0] if cidr != "0.0.0.0/0" && cidr != "*" { cidr = strings.Replace(cidr, ".", "-", -1) cidr = strings.Replace(cidr, "::", "-", -1) cidr = strings.Replace(cidr, "/", "-", -1) ruleName = fmt.Sprintf("%s-cidr-%s", ruleName, cidr) } return ruleName }
go
func securityRuleName(prefix string, rule jujunetwork.IngressRule) string { ruleName := fmt.Sprintf("%s%s-%d", prefix, rule.Protocol, rule.FromPort) if rule.FromPort != rule.ToPort { ruleName += fmt.Sprintf("-%d", rule.ToPort) } // The rule parameter must have a single source cidr. // Ensure the rule name can be a valid URL path component. cidr := rule.SourceCIDRs[0] if cidr != "0.0.0.0/0" && cidr != "*" { cidr = strings.Replace(cidr, ".", "-", -1) cidr = strings.Replace(cidr, "::", "-", -1) cidr = strings.Replace(cidr, "/", "-", -1) ruleName = fmt.Sprintf("%s-cidr-%s", ruleName, cidr) } return ruleName }
[ "func", "securityRuleName", "(", "prefix", "string", ",", "rule", "jujunetwork", ".", "IngressRule", ")", "string", "{", "ruleName", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "prefix", ",", "rule", ".", "Protocol", ",", "rule", ".", "FromPort", ")", "\n", "if", "rule", ".", "FromPort", "!=", "rule", ".", "ToPort", "{", "ruleName", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "rule", ".", "ToPort", ")", "\n", "}", "\n", "// The rule parameter must have a single source cidr.", "// Ensure the rule name can be a valid URL path component.", "cidr", ":=", "rule", ".", "SourceCIDRs", "[", "0", "]", "\n", "if", "cidr", "!=", "\"", "\"", "&&", "cidr", "!=", "\"", "\"", "{", "cidr", "=", "strings", ".", "Replace", "(", "cidr", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "cidr", "=", "strings", ".", "Replace", "(", "cidr", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "cidr", "=", "strings", ".", "Replace", "(", "cidr", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "ruleName", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ruleName", ",", "cidr", ")", "\n", "}", "\n", "return", "ruleName", "\n", "}" ]
// securityRuleName returns the security rule name for the given ingress rule, // and prefix returned by instanceNetworkSecurityRulePrefix.
[ "securityRuleName", "returns", "the", "security", "rule", "name", "for", "the", "given", "ingress", "rule", "and", "prefix", "returned", "by", "instanceNetworkSecurityRulePrefix", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/azure/instance.go#L490-L505
155,204
juju/juju
provider/azure/instance.go
explodeIngressRules
func explodeIngressRules(inRules jujunetwork.IngressRuleSlice) jujunetwork.IngressRuleSlice { // If any rule has an empty source CIDR slice, a default // source value of "*" is used. var singleSourceIngressRules jujunetwork.IngressRuleSlice for _, rule := range inRules { sourceCIDRs := rule.SourceCIDRs if len(sourceCIDRs) == 0 { sourceCIDRs = []string{"*"} } for _, sr := range sourceCIDRs { r := rule r.SourceCIDRs = []string{sr} singleSourceIngressRules = append(singleSourceIngressRules, r) } } return singleSourceIngressRules }
go
func explodeIngressRules(inRules jujunetwork.IngressRuleSlice) jujunetwork.IngressRuleSlice { // If any rule has an empty source CIDR slice, a default // source value of "*" is used. var singleSourceIngressRules jujunetwork.IngressRuleSlice for _, rule := range inRules { sourceCIDRs := rule.SourceCIDRs if len(sourceCIDRs) == 0 { sourceCIDRs = []string{"*"} } for _, sr := range sourceCIDRs { r := rule r.SourceCIDRs = []string{sr} singleSourceIngressRules = append(singleSourceIngressRules, r) } } return singleSourceIngressRules }
[ "func", "explodeIngressRules", "(", "inRules", "jujunetwork", ".", "IngressRuleSlice", ")", "jujunetwork", ".", "IngressRuleSlice", "{", "// If any rule has an empty source CIDR slice, a default", "// source value of \"*\" is used.", "var", "singleSourceIngressRules", "jujunetwork", ".", "IngressRuleSlice", "\n", "for", "_", ",", "rule", ":=", "range", "inRules", "{", "sourceCIDRs", ":=", "rule", ".", "SourceCIDRs", "\n", "if", "len", "(", "sourceCIDRs", ")", "==", "0", "{", "sourceCIDRs", "=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "}", "\n", "for", "_", ",", "sr", ":=", "range", "sourceCIDRs", "{", "r", ":=", "rule", "\n", "r", ".", "SourceCIDRs", "=", "[", "]", "string", "{", "sr", "}", "\n", "singleSourceIngressRules", "=", "append", "(", "singleSourceIngressRules", ",", "r", ")", "\n", "}", "\n", "}", "\n", "return", "singleSourceIngressRules", "\n", "}" ]
// explodeIngressRules creates a slice of ingress rules, each rule in the // result having a single source CIDR. The results contain a copy of each // specified rule with each copy having one of the source CIDR values,
[ "explodeIngressRules", "creates", "a", "slice", "of", "ingress", "rules", "each", "rule", "in", "the", "result", "having", "a", "single", "source", "CIDR", ".", "The", "results", "contain", "a", "copy", "of", "each", "specified", "rule", "with", "each", "copy", "having", "one", "of", "the", "source", "CIDR", "values" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/azure/instance.go#L510-L526
155,205
juju/juju
environs/manual/winrmprovisioner/winrmprovisioner.go
newDetectHardwareScript
func newDetectHardwareScript() (string, error) { tmpl := template.Must(template.New("hc").Parse(detectHardware)) var in bytes.Buffer seriesMap := series.WindowsVersions() if err := tmpl.Execute(&in, seriesMap); err != nil { return "", err } return shell.NewPSEncodedCommand(in.String()) }
go
func newDetectHardwareScript() (string, error) { tmpl := template.Must(template.New("hc").Parse(detectHardware)) var in bytes.Buffer seriesMap := series.WindowsVersions() if err := tmpl.Execute(&in, seriesMap); err != nil { return "", err } return shell.NewPSEncodedCommand(in.String()) }
[ "func", "newDetectHardwareScript", "(", ")", "(", "string", ",", "error", ")", "{", "tmpl", ":=", "template", ".", "Must", "(", "template", ".", "New", "(", "\"", "\"", ")", ".", "Parse", "(", "detectHardware", ")", ")", "\n", "var", "in", "bytes", ".", "Buffer", "\n", "seriesMap", ":=", "series", ".", "WindowsVersions", "(", ")", "\n", "if", "err", ":=", "tmpl", ".", "Execute", "(", "&", "in", ",", "seriesMap", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "shell", ".", "NewPSEncodedCommand", "(", "in", ".", "String", "(", ")", ")", "\n", "}" ]
// newDetectHardwareScript will parse the detectHardware script and add // into the powershell hastable the key,val of the map returned from the // WindowsVersions func from the series pkg. // it will return the script wrapped into a safe powershell base64
[ "newDetectHardwareScript", "will", "parse", "the", "detectHardware", "script", "and", "add", "into", "the", "powershell", "hastable", "the", "key", "val", "of", "the", "map", "returned", "from", "the", "WindowsVersions", "func", "from", "the", "series", "pkg", ".", "it", "will", "return", "the", "script", "wrapped", "into", "a", "safe", "powershell", "base64" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/manual/winrmprovisioner/winrmprovisioner.go#L110-L118
155,206
juju/juju
environs/manual/winrmprovisioner/winrmprovisioner.go
InitAdministratorUser
func InitAdministratorUser(args *manual.ProvisionMachineArgs) error { logger.Infof("Trying https client as user %s on %s", args.Host, args.User) err := args.WinRM.Client.Ping() if err == nil { logger.Infof("Https connection is enabled on the host %s with user %s", args.Host, args.User) return nil } logger.Debugf("Https client authentication is not enabled on the host %s with user %s", args.Host, args.User) if args.WinRM.Client, err = winrm.NewClient(winrm.ClientConfig{ User: args.User, Host: args.Host, Timeout: 25 * time.Second, Password: winrm.TTYGetPasswd, Secure: false, }); err != nil { return errors.Annotatef(err, "cannot create a new http winrm client ") } logger.Infof("Trying http client as user %s on %s", args.Host, args.User) if err = args.WinRM.Client.Ping(); err != nil { logger.Debugf("WinRM unsecure listener is not enabled on %s", args.Host) return errors.Annotatef(err, "cannot provision, because all winrm default connections failed") } defClient := args.WinRM.Client logger.Infof("Trying to enable https client certificate authentication") if args.WinRM.Client, err = enableCertAuth(args); err != nil { logger.Infof("Cannot enable client auth cert authentication for winrm") logger.Infof("Reverting back to usecure client interaction") args.WinRM.Client = defClient return nil } logger.Infof("Client certs are installed and setup on the %s with user %s", args.Host, args.User) err = args.WinRM.Client.Ping() if err == nil { return nil } logger.Infof("Winrm https connection is broken, can't retrive a response") logger.Infof("Reverting back to usecure client interactions") args.WinRM.Client = defClient return nil }
go
func InitAdministratorUser(args *manual.ProvisionMachineArgs) error { logger.Infof("Trying https client as user %s on %s", args.Host, args.User) err := args.WinRM.Client.Ping() if err == nil { logger.Infof("Https connection is enabled on the host %s with user %s", args.Host, args.User) return nil } logger.Debugf("Https client authentication is not enabled on the host %s with user %s", args.Host, args.User) if args.WinRM.Client, err = winrm.NewClient(winrm.ClientConfig{ User: args.User, Host: args.Host, Timeout: 25 * time.Second, Password: winrm.TTYGetPasswd, Secure: false, }); err != nil { return errors.Annotatef(err, "cannot create a new http winrm client ") } logger.Infof("Trying http client as user %s on %s", args.Host, args.User) if err = args.WinRM.Client.Ping(); err != nil { logger.Debugf("WinRM unsecure listener is not enabled on %s", args.Host) return errors.Annotatef(err, "cannot provision, because all winrm default connections failed") } defClient := args.WinRM.Client logger.Infof("Trying to enable https client certificate authentication") if args.WinRM.Client, err = enableCertAuth(args); err != nil { logger.Infof("Cannot enable client auth cert authentication for winrm") logger.Infof("Reverting back to usecure client interaction") args.WinRM.Client = defClient return nil } logger.Infof("Client certs are installed and setup on the %s with user %s", args.Host, args.User) err = args.WinRM.Client.Ping() if err == nil { return nil } logger.Infof("Winrm https connection is broken, can't retrive a response") logger.Infof("Reverting back to usecure client interactions") args.WinRM.Client = defClient return nil }
[ "func", "InitAdministratorUser", "(", "args", "*", "manual", ".", "ProvisionMachineArgs", ")", "error", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "args", ".", "Host", ",", "args", ".", "User", ")", "\n", "err", ":=", "args", ".", "WinRM", ".", "Client", ".", "Ping", "(", ")", "\n", "if", "err", "==", "nil", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "args", ".", "Host", ",", "args", ".", "User", ")", "\n", "return", "nil", "\n", "}", "\n\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "args", ".", "Host", ",", "args", ".", "User", ")", "\n", "if", "args", ".", "WinRM", ".", "Client", ",", "err", "=", "winrm", ".", "NewClient", "(", "winrm", ".", "ClientConfig", "{", "User", ":", "args", ".", "User", ",", "Host", ":", "args", ".", "Host", ",", "Timeout", ":", "25", "*", "time", ".", "Second", ",", "Password", ":", "winrm", ".", "TTYGetPasswd", ",", "Secure", ":", "false", ",", "}", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "logger", ".", "Infof", "(", "\"", "\"", ",", "args", ".", "Host", ",", "args", ".", "User", ")", "\n", "if", "err", "=", "args", ".", "WinRM", ".", "Client", ".", "Ping", "(", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "args", ".", "Host", ")", "\n", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "defClient", ":=", "args", ".", "WinRM", ".", "Client", "\n", "logger", ".", "Infof", "(", "\"", "\"", ")", "\n", "if", "args", ".", "WinRM", ".", "Client", ",", "err", "=", "enableCertAuth", "(", "args", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Infof", "(", "\"", "\"", ")", "\n", "logger", ".", "Infof", "(", "\"", "\"", ")", "\n", "args", ".", "WinRM", ".", "Client", "=", "defClient", "\n", "return", "nil", "\n", "}", "\n\n", "logger", ".", "Infof", "(", "\"", "\"", ",", "args", ".", "Host", ",", "args", ".", "User", ")", "\n", "err", "=", "args", ".", "WinRM", ".", "Client", ".", "Ping", "(", ")", "\n", "if", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "logger", ".", "Infof", "(", "\"", "\"", ")", "\n", "logger", ".", "Infof", "(", "\"", "\"", ")", "\n", "args", ".", "WinRM", ".", "Client", "=", "defClient", "\n\n", "return", "nil", "\n\n", "}" ]
// InitAdministratorUser will initially attempt to login as // the Administrator user using the secure client // only if this is false then this will make a new attempt with the unsecure http client.
[ "InitAdministratorUser", "will", "initially", "attempt", "to", "login", "as", "the", "Administrator", "user", "using", "the", "secure", "client", "only", "if", "this", "is", "false", "then", "this", "will", "make", "a", "new", "attempt", "with", "the", "unsecure", "http", "client", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/manual/winrmprovisioner/winrmprovisioner.go#L123-L169
155,207
juju/juju
environs/manual/winrmprovisioner/winrmprovisioner.go
enableCertAuth
func enableCertAuth(args *manual.ProvisionMachineArgs) (manual.WinrmClientAPI, error) { var stderr bytes.Buffer pass := args.WinRM.Client.Password() scripts, err := bindInitScripts(pass, args.WinRM.Keys) if err != nil { return nil, errors.Trace(err) } for _, script := range scripts { err = args.WinRM.Client.Run(script, args.Stdout, &stderr) if err != nil { return nil, errors.Trace(err) } if stderr.Len() > 0 { return nil, errors.Errorf( "encountered error executing cert auth script: %s", stderr.String(), ) } } cfg := winrm.ClientConfig{ User: args.User, Host: args.Host, Key: args.WinRM.Keys.ClientKey(), Cert: args.WinRM.Keys.ClientCert(), Timeout: 25 * time.Second, Secure: true, } caCert := args.WinRM.Keys.CACert() if caCert == nil { logger.Infof("Skipping winrm CA validation") cfg.Insecure = true } else { cfg.CACert = caCert } return winrm.NewClient(cfg) }
go
func enableCertAuth(args *manual.ProvisionMachineArgs) (manual.WinrmClientAPI, error) { var stderr bytes.Buffer pass := args.WinRM.Client.Password() scripts, err := bindInitScripts(pass, args.WinRM.Keys) if err != nil { return nil, errors.Trace(err) } for _, script := range scripts { err = args.WinRM.Client.Run(script, args.Stdout, &stderr) if err != nil { return nil, errors.Trace(err) } if stderr.Len() > 0 { return nil, errors.Errorf( "encountered error executing cert auth script: %s", stderr.String(), ) } } cfg := winrm.ClientConfig{ User: args.User, Host: args.Host, Key: args.WinRM.Keys.ClientKey(), Cert: args.WinRM.Keys.ClientCert(), Timeout: 25 * time.Second, Secure: true, } caCert := args.WinRM.Keys.CACert() if caCert == nil { logger.Infof("Skipping winrm CA validation") cfg.Insecure = true } else { cfg.CACert = caCert } return winrm.NewClient(cfg) }
[ "func", "enableCertAuth", "(", "args", "*", "manual", ".", "ProvisionMachineArgs", ")", "(", "manual", ".", "WinrmClientAPI", ",", "error", ")", "{", "var", "stderr", "bytes", ".", "Buffer", "\n", "pass", ":=", "args", ".", "WinRM", ".", "Client", ".", "Password", "(", ")", "\n\n", "scripts", ",", "err", ":=", "bindInitScripts", "(", "pass", ",", "args", ".", "WinRM", ".", "Keys", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "for", "_", ",", "script", ":=", "range", "scripts", "{", "err", "=", "args", ".", "WinRM", ".", "Client", ".", "Run", "(", "script", ",", "args", ".", "Stdout", ",", "&", "stderr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "stderr", ".", "Len", "(", ")", ">", "0", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "stderr", ".", "String", "(", ")", ",", ")", "\n", "}", "\n", "}", "\n\n", "cfg", ":=", "winrm", ".", "ClientConfig", "{", "User", ":", "args", ".", "User", ",", "Host", ":", "args", ".", "Host", ",", "Key", ":", "args", ".", "WinRM", ".", "Keys", ".", "ClientKey", "(", ")", ",", "Cert", ":", "args", ".", "WinRM", ".", "Keys", ".", "ClientCert", "(", ")", ",", "Timeout", ":", "25", "*", "time", ".", "Second", ",", "Secure", ":", "true", ",", "}", "\n\n", "caCert", ":=", "args", ".", "WinRM", ".", "Keys", ".", "CACert", "(", ")", "\n", "if", "caCert", "==", "nil", "{", "logger", ".", "Infof", "(", "\"", "\"", ")", "\n", "cfg", ".", "Insecure", "=", "true", "\n", "}", "else", "{", "cfg", ".", "CACert", "=", "caCert", "\n", "}", "\n\n", "return", "winrm", ".", "NewClient", "(", "cfg", ")", "\n", "}" ]
// enableCertAuth enables https cert auth interactions // with the winrm listener and returns the client
[ "enableCertAuth", "enables", "https", "cert", "auth", "interactions", "with", "the", "winrm", "listener", "and", "returns", "the", "client" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/manual/winrmprovisioner/winrmprovisioner.go#L173-L213
155,208
juju/juju
environs/manual/winrmprovisioner/winrmprovisioner.go
checkProvisioned
func checkProvisioned(host string, cli manual.WinrmClientAPI) (bool, error) { logger.Tracef("Checking if %s windows machine is already provisioned", host) var stdout, stderr bytes.Buffer // run the command trough winrm // this script detects if the jujud process, service is up and running script, err := shell.NewPSEncodedCommand(detectJujudProcess) if err != nil { return false, errors.Trace(err) } // send the script to the windows machine if err = cli.Run(script, &stdout, &stderr); err != nil { return false, errors.Trace(err) } provisioned := strings.Contains(stdout.String(), "Yes") if stderr.Len() != 0 { err = errors.Annotate(err, strings.TrimSpace(stderr.String())) } // if the script said yes if provisioned { logger.Infof("%s is already provisioned", host) } else { logger.Infof("%s is not provisioned", host) } return provisioned, err }
go
func checkProvisioned(host string, cli manual.WinrmClientAPI) (bool, error) { logger.Tracef("Checking if %s windows machine is already provisioned", host) var stdout, stderr bytes.Buffer // run the command trough winrm // this script detects if the jujud process, service is up and running script, err := shell.NewPSEncodedCommand(detectJujudProcess) if err != nil { return false, errors.Trace(err) } // send the script to the windows machine if err = cli.Run(script, &stdout, &stderr); err != nil { return false, errors.Trace(err) } provisioned := strings.Contains(stdout.String(), "Yes") if stderr.Len() != 0 { err = errors.Annotate(err, strings.TrimSpace(stderr.String())) } // if the script said yes if provisioned { logger.Infof("%s is already provisioned", host) } else { logger.Infof("%s is not provisioned", host) } return provisioned, err }
[ "func", "checkProvisioned", "(", "host", "string", ",", "cli", "manual", ".", "WinrmClientAPI", ")", "(", "bool", ",", "error", ")", "{", "logger", ".", "Tracef", "(", "\"", "\"", ",", "host", ")", "\n", "var", "stdout", ",", "stderr", "bytes", ".", "Buffer", "\n\n", "// run the command trough winrm", "// this script detects if the jujud process, service is up and running", "script", ",", "err", ":=", "shell", ".", "NewPSEncodedCommand", "(", "detectJujudProcess", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// send the script to the windows machine", "if", "err", "=", "cli", ".", "Run", "(", "script", ",", "&", "stdout", ",", "&", "stderr", ")", ";", "err", "!=", "nil", "{", "return", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "provisioned", ":=", "strings", ".", "Contains", "(", "stdout", ".", "String", "(", ")", ",", "\"", "\"", ")", "\n", "if", "stderr", ".", "Len", "(", ")", "!=", "0", "{", "err", "=", "errors", ".", "Annotate", "(", "err", ",", "strings", ".", "TrimSpace", "(", "stderr", ".", "String", "(", ")", ")", ")", "\n", "}", "\n\n", "// if the script said yes", "if", "provisioned", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "host", ")", "\n", "}", "else", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "host", ")", "\n", "}", "\n\n", "return", "provisioned", ",", "err", "\n", "}" ]
// checkProvisioned checks if the machine is already provisioned or not. // if it's already provisioned it will return true
[ "checkProvisioned", "checks", "if", "the", "machine", "is", "already", "provisioned", "or", "not", ".", "if", "it", "s", "already", "provisioned", "it", "will", "return", "true" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/manual/winrmprovisioner/winrmprovisioner.go#L350-L379
155,209
juju/juju
environs/manual/winrmprovisioner/winrmprovisioner.go
DetectSeriesAndHardwareCharacteristics
func DetectSeriesAndHardwareCharacteristics(host string, cli manual.WinrmClientAPI) (hc instance.HardwareCharacteristics, series string, err error) { logger.Infof("Detecting series and characteristics on %s windows machine", host) var stdout, stderr bytes.Buffer script, err := newDetectHardwareScript() if err != nil { return hc, "", err } // send the script to the windows machine if err = cli.Run(script, &stdout, &stderr); err != nil { return hc, "", errors.Trace(err) } if stderr.Len() != 0 { return hc, "", fmt.Errorf("%v (%v)", err, strings.TrimSpace(stderr.String())) } info, err := splitHardWareScript(stdout.String()) if err != nil { return hc, "", errors.Trace(err) } series = strings.Replace(info[2], "\r", "", -1) if err = initHC(&hc, info); err != nil { return hc, "", errors.Trace(err) } return hc, series, nil }
go
func DetectSeriesAndHardwareCharacteristics(host string, cli manual.WinrmClientAPI) (hc instance.HardwareCharacteristics, series string, err error) { logger.Infof("Detecting series and characteristics on %s windows machine", host) var stdout, stderr bytes.Buffer script, err := newDetectHardwareScript() if err != nil { return hc, "", err } // send the script to the windows machine if err = cli.Run(script, &stdout, &stderr); err != nil { return hc, "", errors.Trace(err) } if stderr.Len() != 0 { return hc, "", fmt.Errorf("%v (%v)", err, strings.TrimSpace(stderr.String())) } info, err := splitHardWareScript(stdout.String()) if err != nil { return hc, "", errors.Trace(err) } series = strings.Replace(info[2], "\r", "", -1) if err = initHC(&hc, info); err != nil { return hc, "", errors.Trace(err) } return hc, series, nil }
[ "func", "DetectSeriesAndHardwareCharacteristics", "(", "host", "string", ",", "cli", "manual", ".", "WinrmClientAPI", ")", "(", "hc", "instance", ".", "HardwareCharacteristics", ",", "series", "string", ",", "err", "error", ")", "{", "logger", ".", "Infof", "(", "\"", "\"", ",", "host", ")", "\n", "var", "stdout", ",", "stderr", "bytes", ".", "Buffer", "\n\n", "script", ",", "err", ":=", "newDetectHardwareScript", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "hc", ",", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// send the script to the windows machine", "if", "err", "=", "cli", ".", "Run", "(", "script", ",", "&", "stdout", ",", "&", "stderr", ")", ";", "err", "!=", "nil", "{", "return", "hc", ",", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "stderr", ".", "Len", "(", ")", "!=", "0", "{", "return", "hc", ",", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ",", "strings", ".", "TrimSpace", "(", "stderr", ".", "String", "(", ")", ")", ")", "\n", "}", "\n\n", "info", ",", "err", ":=", "splitHardWareScript", "(", "stdout", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "hc", ",", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "series", "=", "strings", ".", "Replace", "(", "info", "[", "2", "]", ",", "\"", "\\r", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n\n", "if", "err", "=", "initHC", "(", "&", "hc", ",", "info", ")", ";", "err", "!=", "nil", "{", "return", "hc", ",", "\"", "\"", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "hc", ",", "series", ",", "nil", "\n", "}" ]
// DetectSeriesAndHardwareCharacteristics detects the windows OS // series and hardware characteristics of the remote machine // by connecting to the machine and executing a bash script.
[ "DetectSeriesAndHardwareCharacteristics", "detects", "the", "windows", "OS", "series", "and", "hardware", "characteristics", "of", "the", "remote", "machine", "by", "connecting", "to", "the", "machine", "and", "executing", "a", "bash", "script", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/manual/winrmprovisioner/winrmprovisioner.go#L384-L414
155,210
juju/juju
environs/manual/winrmprovisioner/winrmprovisioner.go
splitHardWareScript
func splitHardWareScript(script string) ([]string, error) { scr := strings.Split(script, "\n") n := len(scr) if n < 3 { return nil, fmt.Errorf("No hardware fields on running the powershell deteciton script, %s", script) } for i := 0; i < n; i++ { scr[i] = strings.TrimSpace(scr[i]) } return scr, nil }
go
func splitHardWareScript(script string) ([]string, error) { scr := strings.Split(script, "\n") n := len(scr) if n < 3 { return nil, fmt.Errorf("No hardware fields on running the powershell deteciton script, %s", script) } for i := 0; i < n; i++ { scr[i] = strings.TrimSpace(scr[i]) } return scr, nil }
[ "func", "splitHardWareScript", "(", "script", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "scr", ":=", "strings", ".", "Split", "(", "script", ",", "\"", "\\n", "\"", ")", "\n", "n", ":=", "len", "(", "scr", ")", "\n", "if", "n", "<", "3", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "script", ")", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "n", ";", "i", "++", "{", "scr", "[", "i", "]", "=", "strings", ".", "TrimSpace", "(", "scr", "[", "i", "]", ")", "\n", "}", "\n", "return", "scr", ",", "nil", "\n", "}" ]
// splitHardwareScript will split the result from the detectHardware powershell script // to extract the information in a specific order. // this will return a slice of string that will be used in conjunctions with the above function
[ "splitHardwareScript", "will", "split", "the", "result", "from", "the", "detectHardware", "powershell", "script", "to", "extract", "the", "information", "in", "a", "specific", "order", ".", "this", "will", "return", "a", "slice", "of", "string", "that", "will", "be", "used", "in", "conjunctions", "with", "the", "above", "function" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/manual/winrmprovisioner/winrmprovisioner.go#L451-L461
155,211
juju/juju
environs/manual/winrmprovisioner/winrmprovisioner.go
runProvisionScript
func runProvisionScript(script string, cli manual.WinrmClientAPI, stdin, stderr io.Writer) (err error) { script64 := base64.StdEncoding.EncodeToString([]byte(script)) input := bytes.NewBufferString(script64) // make new buffer out of script // we must make sure to buffer the entire script // in a sequential write fashion first into a script // decouple the provisioning script into little 1024 byte chunks // we are doing this in order to append into a .ps1 file. var buf [1024]byte // if the file dosen't exist ,create it // if the file exists just clear/reset it script, err = shell.NewPSEncodedCommand(initChunk) if err != nil { return err } if err = cli.Run(script, stdin, stderr); err != nil { return errors.Trace(err) } // sequential read. for input.Len() != 0 { n, err := input.Read(buf[:]) if err != nil && err != io.EOF { return errors.Trace(err) } script, err = shell.NewPSEncodedCommand( fmt.Sprintf(saveChunk, string(buf[:n])), ) if err != nil { return errors.Trace(err) } if err = cli.Run(script, stdin, stderr); err != nil { return errors.Trace(err) } } // after the sendAndSave script is successfully done // we must execute the newly writed script script, err = shell.NewPSEncodedCommand(runCmdProv) if err != nil { return err } logger.Debugf("Running the provisioningScript") var outerr bytes.Buffer if err = cli.Run(script, stdin, &outerr); err != nil { return errors.Trace(err) } if outerr.Len() != 0 { return fmt.Errorf("%v ", strings.TrimSpace(outerr.String())) } return err }
go
func runProvisionScript(script string, cli manual.WinrmClientAPI, stdin, stderr io.Writer) (err error) { script64 := base64.StdEncoding.EncodeToString([]byte(script)) input := bytes.NewBufferString(script64) // make new buffer out of script // we must make sure to buffer the entire script // in a sequential write fashion first into a script // decouple the provisioning script into little 1024 byte chunks // we are doing this in order to append into a .ps1 file. var buf [1024]byte // if the file dosen't exist ,create it // if the file exists just clear/reset it script, err = shell.NewPSEncodedCommand(initChunk) if err != nil { return err } if err = cli.Run(script, stdin, stderr); err != nil { return errors.Trace(err) } // sequential read. for input.Len() != 0 { n, err := input.Read(buf[:]) if err != nil && err != io.EOF { return errors.Trace(err) } script, err = shell.NewPSEncodedCommand( fmt.Sprintf(saveChunk, string(buf[:n])), ) if err != nil { return errors.Trace(err) } if err = cli.Run(script, stdin, stderr); err != nil { return errors.Trace(err) } } // after the sendAndSave script is successfully done // we must execute the newly writed script script, err = shell.NewPSEncodedCommand(runCmdProv) if err != nil { return err } logger.Debugf("Running the provisioningScript") var outerr bytes.Buffer if err = cli.Run(script, stdin, &outerr); err != nil { return errors.Trace(err) } if outerr.Len() != 0 { return fmt.Errorf("%v ", strings.TrimSpace(outerr.String())) } return err }
[ "func", "runProvisionScript", "(", "script", "string", ",", "cli", "manual", ".", "WinrmClientAPI", ",", "stdin", ",", "stderr", "io", ".", "Writer", ")", "(", "err", "error", ")", "{", "script64", ":=", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "[", "]", "byte", "(", "script", ")", ")", "\n", "input", ":=", "bytes", ".", "NewBufferString", "(", "script64", ")", "// make new buffer out of script", "\n", "// we must make sure to buffer the entire script", "// in a sequential write fashion first into a script", "// decouple the provisioning script into little 1024 byte chunks", "// we are doing this in order to append into a .ps1 file.", "var", "buf", "[", "1024", "]", "byte", "\n\n", "// if the file dosen't exist ,create it", "// if the file exists just clear/reset it", "script", ",", "err", "=", "shell", ".", "NewPSEncodedCommand", "(", "initChunk", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", "=", "cli", ".", "Run", "(", "script", ",", "stdin", ",", "stderr", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// sequential read.", "for", "input", ".", "Len", "(", ")", "!=", "0", "{", "n", ",", "err", ":=", "input", ".", "Read", "(", "buf", "[", ":", "]", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "io", ".", "EOF", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "script", ",", "err", "=", "shell", ".", "NewPSEncodedCommand", "(", "fmt", ".", "Sprintf", "(", "saveChunk", ",", "string", "(", "buf", "[", ":", "n", "]", ")", ")", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", "=", "cli", ".", "Run", "(", "script", ",", "stdin", ",", "stderr", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "// after the sendAndSave script is successfully done", "// we must execute the newly writed script", "script", ",", "err", "=", "shell", ".", "NewPSEncodedCommand", "(", "runCmdProv", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ")", "\n", "var", "outerr", "bytes", ".", "Buffer", "\n", "if", "err", "=", "cli", ".", "Run", "(", "script", ",", "stdin", ",", "&", "outerr", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "outerr", ".", "Len", "(", ")", "!=", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "strings", ".", "TrimSpace", "(", "outerr", ".", "String", "(", ")", ")", ")", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// runProvisionScript runs the script generated by the provisioner // the script can be big and the underlying protocol dosen't support long messages // we need to send it into little chunks saving first into a file and then execute it.
[ "runProvisionScript", "runs", "the", "script", "generated", "by", "the", "provisioner", "the", "script", "can", "be", "big", "and", "the", "underlying", "protocol", "dosen", "t", "support", "long", "messages", "we", "need", "to", "send", "it", "into", "little", "chunks", "saving", "first", "into", "a", "file", "and", "then", "execute", "it", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/manual/winrmprovisioner/winrmprovisioner.go#L469-L522
155,212
juju/juju
environs/manual/winrmprovisioner/winrmprovisioner.go
ProvisioningScript
func ProvisioningScript(icfg *instancecfg.InstanceConfig) (string, error) { cloudcfg, err := cloudinit.New(icfg.Series) if err != nil { return "", errors.Annotate(err, "error creating new cloud config") } udata, err := cloudconfig.NewUserdataConfig(icfg, cloudcfg) if err != nil { return "", errors.Annotate(err, "error creating new userdata based on the cloud config") } if err := udata.Configure(); err != nil { return "", errors.Annotate(err, "error adding extra configurations in the userdata") } return cloudcfg.RenderScript() }
go
func ProvisioningScript(icfg *instancecfg.InstanceConfig) (string, error) { cloudcfg, err := cloudinit.New(icfg.Series) if err != nil { return "", errors.Annotate(err, "error creating new cloud config") } udata, err := cloudconfig.NewUserdataConfig(icfg, cloudcfg) if err != nil { return "", errors.Annotate(err, "error creating new userdata based on the cloud config") } if err := udata.Configure(); err != nil { return "", errors.Annotate(err, "error adding extra configurations in the userdata") } return cloudcfg.RenderScript() }
[ "func", "ProvisioningScript", "(", "icfg", "*", "instancecfg", ".", "InstanceConfig", ")", "(", "string", ",", "error", ")", "{", "cloudcfg", ",", "err", ":=", "cloudinit", ".", "New", "(", "icfg", ".", "Series", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "udata", ",", "err", ":=", "cloudconfig", ".", "NewUserdataConfig", "(", "icfg", ",", "cloudcfg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", ":=", "udata", ".", "Configure", "(", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "cloudcfg", ".", "RenderScript", "(", ")", "\n", "}" ]
// ProvisioningScript generates a powershell script that can be // executed on a remote host to carry out the cloud-init // configuration.
[ "ProvisioningScript", "generates", "a", "powershell", "script", "that", "can", "be", "executed", "on", "a", "remote", "host", "to", "carry", "out", "the", "cloud", "-", "init", "configuration", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/manual/winrmprovisioner/winrmprovisioner.go#L561-L577
155,213
juju/juju
provider/azure/utils.go
randomAdminPassword
func randomAdminPassword() string { // We want at least one each of lower-alpha, upper-alpha, and digit. // Allocate 16 of each (randomly), and then the remaining characters // will be randomly chosen from the full set. validRunes := append(utils.LowerAlpha, utils.Digits...) validRunes = append(validRunes, utils.UpperAlpha...) lowerAlpha := utils.RandomString(16, utils.LowerAlpha) upperAlpha := utils.RandomString(16, utils.UpperAlpha) digits := utils.RandomString(16, utils.Digits) mixed := utils.RandomString(16, validRunes) password := []rune(lowerAlpha + upperAlpha + digits + mixed) for i := len(password) - 1; i >= 1; i-- { j := rand.Intn(i + 1) password[i], password[j] = password[j], password[i] } return string(password) }
go
func randomAdminPassword() string { // We want at least one each of lower-alpha, upper-alpha, and digit. // Allocate 16 of each (randomly), and then the remaining characters // will be randomly chosen from the full set. validRunes := append(utils.LowerAlpha, utils.Digits...) validRunes = append(validRunes, utils.UpperAlpha...) lowerAlpha := utils.RandomString(16, utils.LowerAlpha) upperAlpha := utils.RandomString(16, utils.UpperAlpha) digits := utils.RandomString(16, utils.Digits) mixed := utils.RandomString(16, validRunes) password := []rune(lowerAlpha + upperAlpha + digits + mixed) for i := len(password) - 1; i >= 1; i-- { j := rand.Intn(i + 1) password[i], password[j] = password[j], password[i] } return string(password) }
[ "func", "randomAdminPassword", "(", ")", "string", "{", "// We want at least one each of lower-alpha, upper-alpha, and digit.", "// Allocate 16 of each (randomly), and then the remaining characters", "// will be randomly chosen from the full set.", "validRunes", ":=", "append", "(", "utils", ".", "LowerAlpha", ",", "utils", ".", "Digits", "...", ")", "\n", "validRunes", "=", "append", "(", "validRunes", ",", "utils", ".", "UpperAlpha", "...", ")", "\n\n", "lowerAlpha", ":=", "utils", ".", "RandomString", "(", "16", ",", "utils", ".", "LowerAlpha", ")", "\n", "upperAlpha", ":=", "utils", ".", "RandomString", "(", "16", ",", "utils", ".", "UpperAlpha", ")", "\n", "digits", ":=", "utils", ".", "RandomString", "(", "16", ",", "utils", ".", "Digits", ")", "\n", "mixed", ":=", "utils", ".", "RandomString", "(", "16", ",", "validRunes", ")", "\n", "password", ":=", "[", "]", "rune", "(", "lowerAlpha", "+", "upperAlpha", "+", "digits", "+", "mixed", ")", "\n", "for", "i", ":=", "len", "(", "password", ")", "-", "1", ";", "i", ">=", "1", ";", "i", "--", "{", "j", ":=", "rand", ".", "Intn", "(", "i", "+", "1", ")", "\n", "password", "[", "i", "]", ",", "password", "[", "j", "]", "=", "password", "[", "j", "]", ",", "password", "[", "i", "]", "\n", "}", "\n", "return", "string", "(", "password", ")", "\n", "}" ]
// randomAdminPassword returns a random administrator password for // Windows machines.
[ "randomAdminPassword", "returns", "a", "random", "administrator", "password", "for", "Windows", "machines", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/azure/utils.go#L37-L54
155,214
juju/juju
provider/azure/utils.go
collectAPIVersions
func collectAPIVersions(ctx context.ProviderCallContext, sdkCtx stdcontext.Context, client resources.ProvidersClient) (map[string]string, error) { result := make(map[string]string) var res resources.ProviderListResultIterator res, err := client.ListComplete(sdkCtx, nil, "") if err != nil { return result, errorutils.HandleCredentialError(errors.Trace(err), ctx) } for ; res.NotDone(); err = res.NextWithContext(sdkCtx) { if err != nil { return map[string]string{}, errorutils.HandleCredentialError(errors.Trace(err), ctx) } provider := res.Value() if provider.ResourceTypes == nil { continue } for _, resourceType := range *provider.ResourceTypes { key := to.String(provider.Namespace) + "/" + to.String(resourceType.ResourceType) versions := to.StringSlice(resourceType.APIVersions) if len(versions) == 0 { continue } // The versions are newest-first. result[key] = versions[0] } } return result, nil }
go
func collectAPIVersions(ctx context.ProviderCallContext, sdkCtx stdcontext.Context, client resources.ProvidersClient) (map[string]string, error) { result := make(map[string]string) var res resources.ProviderListResultIterator res, err := client.ListComplete(sdkCtx, nil, "") if err != nil { return result, errorutils.HandleCredentialError(errors.Trace(err), ctx) } for ; res.NotDone(); err = res.NextWithContext(sdkCtx) { if err != nil { return map[string]string{}, errorutils.HandleCredentialError(errors.Trace(err), ctx) } provider := res.Value() if provider.ResourceTypes == nil { continue } for _, resourceType := range *provider.ResourceTypes { key := to.String(provider.Namespace) + "/" + to.String(resourceType.ResourceType) versions := to.StringSlice(resourceType.APIVersions) if len(versions) == 0 { continue } // The versions are newest-first. result[key] = versions[0] } } return result, nil }
[ "func", "collectAPIVersions", "(", "ctx", "context", ".", "ProviderCallContext", ",", "sdkCtx", "stdcontext", ".", "Context", ",", "client", "resources", ".", "ProvidersClient", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "result", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n\n", "var", "res", "resources", ".", "ProviderListResultIterator", "\n", "res", ",", "err", ":=", "client", ".", "ListComplete", "(", "sdkCtx", ",", "nil", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "errorutils", ".", "HandleCredentialError", "(", "errors", ".", "Trace", "(", "err", ")", ",", "ctx", ")", "\n", "}", "\n", "for", ";", "res", ".", "NotDone", "(", ")", ";", "err", "=", "res", ".", "NextWithContext", "(", "sdkCtx", ")", "{", "if", "err", "!=", "nil", "{", "return", "map", "[", "string", "]", "string", "{", "}", ",", "errorutils", ".", "HandleCredentialError", "(", "errors", ".", "Trace", "(", "err", ")", ",", "ctx", ")", "\n", "}", "\n\n", "provider", ":=", "res", ".", "Value", "(", ")", "\n", "if", "provider", ".", "ResourceTypes", "==", "nil", "{", "continue", "\n", "}", "\n\n", "for", "_", ",", "resourceType", ":=", "range", "*", "provider", ".", "ResourceTypes", "{", "key", ":=", "to", ".", "String", "(", "provider", ".", "Namespace", ")", "+", "\"", "\"", "+", "to", ".", "String", "(", "resourceType", ".", "ResourceType", ")", "\n", "versions", ":=", "to", ".", "StringSlice", "(", "resourceType", ".", "APIVersions", ")", "\n", "if", "len", "(", "versions", ")", "==", "0", "{", "continue", "\n", "}", "\n", "// The versions are newest-first.", "result", "[", "key", "]", "=", "versions", "[", "0", "]", "\n", "}", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// collectAPIVersions returns a map of the latest API version for each // possible resource type. This is needed to use the Azure Resource // Management API, because the API version requested must match the // type of the resource being manipulated through the API, rather than // the API version specified statically in the resource client code.
[ "collectAPIVersions", "returns", "a", "map", "of", "the", "latest", "API", "version", "for", "each", "possible", "resource", "type", ".", "This", "is", "needed", "to", "use", "the", "Azure", "Resource", "Management", "API", "because", "the", "API", "version", "requested", "must", "match", "the", "type", "of", "the", "resource", "being", "manipulated", "through", "the", "API", "rather", "than", "the", "API", "version", "specified", "statically", "in", "the", "resource", "client", "code", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/azure/utils.go#L72-L101
155,215
juju/juju
apiserver/facades/controller/migrationtarget/migrationtarget.go
NewAPI
func NewAPI(ctx facade.Context, getEnviron stateenvirons.NewEnvironFunc, getCAASBroker stateenvirons.NewCAASBrokerFunc, callCtx context.ProviderCallContext) (*API, error) { auth := ctx.Auth() st := ctx.State() if err := checkAuth(auth, st); err != nil { return nil, errors.Trace(err) } return &API{ state: st, pool: ctx.StatePool(), authorizer: auth, resources: ctx.Resources(), presence: ctx.Presence(), getClaimer: ctx.LeadershipClaimer, getEnviron: getEnviron, getCAASBroker: getCAASBroker, callContext: callCtx, }, nil }
go
func NewAPI(ctx facade.Context, getEnviron stateenvirons.NewEnvironFunc, getCAASBroker stateenvirons.NewCAASBrokerFunc, callCtx context.ProviderCallContext) (*API, error) { auth := ctx.Auth() st := ctx.State() if err := checkAuth(auth, st); err != nil { return nil, errors.Trace(err) } return &API{ state: st, pool: ctx.StatePool(), authorizer: auth, resources: ctx.Resources(), presence: ctx.Presence(), getClaimer: ctx.LeadershipClaimer, getEnviron: getEnviron, getCAASBroker: getCAASBroker, callContext: callCtx, }, nil }
[ "func", "NewAPI", "(", "ctx", "facade", ".", "Context", ",", "getEnviron", "stateenvirons", ".", "NewEnvironFunc", ",", "getCAASBroker", "stateenvirons", ".", "NewCAASBrokerFunc", ",", "callCtx", "context", ".", "ProviderCallContext", ")", "(", "*", "API", ",", "error", ")", "{", "auth", ":=", "ctx", ".", "Auth", "(", ")", "\n", "st", ":=", "ctx", ".", "State", "(", ")", "\n", "if", "err", ":=", "checkAuth", "(", "auth", ",", "st", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "&", "API", "{", "state", ":", "st", ",", "pool", ":", "ctx", ".", "StatePool", "(", ")", ",", "authorizer", ":", "auth", ",", "resources", ":", "ctx", ".", "Resources", "(", ")", ",", "presence", ":", "ctx", ".", "Presence", "(", ")", ",", "getClaimer", ":", "ctx", ".", "LeadershipClaimer", ",", "getEnviron", ":", "getEnviron", ",", "getCAASBroker", ":", "getCAASBroker", ",", "callContext", ":", "callCtx", ",", "}", ",", "nil", "\n", "}" ]
// NewAPI returns a new API. Accepts a NewEnvironFunc and context.ProviderCallContext // for testing purposes.
[ "NewAPI", "returns", "a", "new", "API", ".", "Accepts", "a", "NewEnvironFunc", "and", "context", ".", "ProviderCallContext", "for", "testing", "purposes", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/migrationtarget/migrationtarget.go#L52-L69
155,216
juju/juju
apiserver/facades/controller/migrationtarget/migrationtarget.go
Prechecks
func (api *API) Prechecks(model params.MigrationModelInfo) error { ownerTag, err := names.ParseUserTag(model.OwnerTag) if err != nil { return errors.Trace(err) } controllerState := api.pool.SystemState() // NOTE (thumper): it isn't clear to me why api.state would be different // from the controllerState as I had thought that the Precheck call was // on the controller model, in which case it should be the same as the // controllerState. backend, err := migration.PrecheckShim(api.state, controllerState) if err != nil { return errors.Annotate(err, "creating backend") } return migration.TargetPrecheck( backend, migration.PoolShim(api.pool), coremigration.ModelInfo{ UUID: model.UUID, Name: model.Name, Owner: ownerTag, AgentVersion: model.AgentVersion, ControllerAgentVersion: model.ControllerAgentVersion, }, api.presence.ModelPresence(controllerState.ModelUUID()), ) }
go
func (api *API) Prechecks(model params.MigrationModelInfo) error { ownerTag, err := names.ParseUserTag(model.OwnerTag) if err != nil { return errors.Trace(err) } controllerState := api.pool.SystemState() // NOTE (thumper): it isn't clear to me why api.state would be different // from the controllerState as I had thought that the Precheck call was // on the controller model, in which case it should be the same as the // controllerState. backend, err := migration.PrecheckShim(api.state, controllerState) if err != nil { return errors.Annotate(err, "creating backend") } return migration.TargetPrecheck( backend, migration.PoolShim(api.pool), coremigration.ModelInfo{ UUID: model.UUID, Name: model.Name, Owner: ownerTag, AgentVersion: model.AgentVersion, ControllerAgentVersion: model.ControllerAgentVersion, }, api.presence.ModelPresence(controllerState.ModelUUID()), ) }
[ "func", "(", "api", "*", "API", ")", "Prechecks", "(", "model", "params", ".", "MigrationModelInfo", ")", "error", "{", "ownerTag", ",", "err", ":=", "names", ".", "ParseUserTag", "(", "model", ".", "OwnerTag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "controllerState", ":=", "api", ".", "pool", ".", "SystemState", "(", ")", "\n", "// NOTE (thumper): it isn't clear to me why api.state would be different", "// from the controllerState as I had thought that the Precheck call was", "// on the controller model, in which case it should be the same as the", "// controllerState.", "backend", ",", "err", ":=", "migration", ".", "PrecheckShim", "(", "api", ".", "state", ",", "controllerState", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "migration", ".", "TargetPrecheck", "(", "backend", ",", "migration", ".", "PoolShim", "(", "api", ".", "pool", ")", ",", "coremigration", ".", "ModelInfo", "{", "UUID", ":", "model", ".", "UUID", ",", "Name", ":", "model", ".", "Name", ",", "Owner", ":", "ownerTag", ",", "AgentVersion", ":", "model", ".", "AgentVersion", ",", "ControllerAgentVersion", ":", "model", ".", "ControllerAgentVersion", ",", "}", ",", "api", ".", "presence", ".", "ModelPresence", "(", "controllerState", ".", "ModelUUID", "(", ")", ")", ",", ")", "\n", "}" ]
// Prechecks ensure that the target controller is ready to accept a // model migration.
[ "Prechecks", "ensure", "that", "the", "target", "controller", "is", "ready", "to", "accept", "a", "model", "migration", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/migrationtarget/migrationtarget.go#L87-L113
155,217
juju/juju
apiserver/facades/controller/migrationtarget/migrationtarget.go
Import
func (api *API) Import(serialized params.SerializedModel) error { controller := state.NewController(api.pool) _, st, err := migration.ImportModel(controller, api.getClaimer, serialized.Bytes) if err != nil { return err } defer st.Close() // TODO(mjs) - post import checks // NOTE(fwereade) - checks here would be sensible, but we will // also need to check after the binaries are imported too. return err }
go
func (api *API) Import(serialized params.SerializedModel) error { controller := state.NewController(api.pool) _, st, err := migration.ImportModel(controller, api.getClaimer, serialized.Bytes) if err != nil { return err } defer st.Close() // TODO(mjs) - post import checks // NOTE(fwereade) - checks here would be sensible, but we will // also need to check after the binaries are imported too. return err }
[ "func", "(", "api", "*", "API", ")", "Import", "(", "serialized", "params", ".", "SerializedModel", ")", "error", "{", "controller", ":=", "state", ".", "NewController", "(", "api", ".", "pool", ")", "\n", "_", ",", "st", ",", "err", ":=", "migration", ".", "ImportModel", "(", "controller", ",", "api", ".", "getClaimer", ",", "serialized", ".", "Bytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "st", ".", "Close", "(", ")", "\n", "// TODO(mjs) - post import checks", "// NOTE(fwereade) - checks here would be sensible, but we will", "// also need to check after the binaries are imported too.", "return", "err", "\n", "}" ]
// Import takes a serialized Juju model, deserializes it, and // recreates it in the receiving controller.
[ "Import", "takes", "a", "serialized", "Juju", "model", "deserializes", "it", "and", "recreates", "it", "in", "the", "receiving", "controller", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/migrationtarget/migrationtarget.go#L117-L128
155,218
juju/juju
apiserver/facades/controller/migrationtarget/migrationtarget.go
Abort
func (api *API) Abort(args params.ModelArgs) error { model, releaseModel, err := api.getImportingModel(args) if err != nil { return errors.Trace(err) } defer releaseModel() st, err := api.pool.Get(model.UUID()) if err != nil { return errors.Trace(err) } defer st.Release() return st.RemoveImportingModelDocs() }
go
func (api *API) Abort(args params.ModelArgs) error { model, releaseModel, err := api.getImportingModel(args) if err != nil { return errors.Trace(err) } defer releaseModel() st, err := api.pool.Get(model.UUID()) if err != nil { return errors.Trace(err) } defer st.Release() return st.RemoveImportingModelDocs() }
[ "func", "(", "api", "*", "API", ")", "Abort", "(", "args", "params", ".", "ModelArgs", ")", "error", "{", "model", ",", "releaseModel", ",", "err", ":=", "api", ".", "getImportingModel", "(", "args", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "defer", "releaseModel", "(", ")", "\n\n", "st", ",", "err", ":=", "api", ".", "pool", ".", "Get", "(", "model", ".", "UUID", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "defer", "st", ".", "Release", "(", ")", "\n", "return", "st", ".", "RemoveImportingModelDocs", "(", ")", "\n", "}" ]
// Abort removes the specified model from the database. It is an error to // attempt to Abort a model that has a migration mode other than importing.
[ "Abort", "removes", "the", "specified", "model", "from", "the", "database", ".", "It", "is", "an", "error", "to", "attempt", "to", "Abort", "a", "model", "that", "has", "a", "migration", "mode", "other", "than", "importing", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/migrationtarget/migrationtarget.go#L156-L169
155,219
juju/juju
apiserver/facades/controller/migrationtarget/migrationtarget.go
Activate
func (api *API) Activate(args params.ModelArgs) error { model, release, err := api.getImportingModel(args) if err != nil { return errors.Trace(err) } defer release() if err := model.SetStatus(status.StatusInfo{Status: status.Available}); err != nil { return errors.Trace(err) } // TODO(fwereade) - need to validate binaries here. return model.SetMigrationMode(state.MigrationModeNone) }
go
func (api *API) Activate(args params.ModelArgs) error { model, release, err := api.getImportingModel(args) if err != nil { return errors.Trace(err) } defer release() if err := model.SetStatus(status.StatusInfo{Status: status.Available}); err != nil { return errors.Trace(err) } // TODO(fwereade) - need to validate binaries here. return model.SetMigrationMode(state.MigrationModeNone) }
[ "func", "(", "api", "*", "API", ")", "Activate", "(", "args", "params", ".", "ModelArgs", ")", "error", "{", "model", ",", "release", ",", "err", ":=", "api", ".", "getImportingModel", "(", "args", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "defer", "release", "(", ")", "\n\n", "if", "err", ":=", "model", ".", "SetStatus", "(", "status", ".", "StatusInfo", "{", "Status", ":", "status", ".", "Available", "}", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// TODO(fwereade) - need to validate binaries here.", "return", "model", ".", "SetMigrationMode", "(", "state", ".", "MigrationModeNone", ")", "\n", "}" ]
// Activate sets the migration mode of the model to "none", meaning it // is ready for use. It is an error to attempt to Abort a model that // has a migration mode other than importing.
[ "Activate", "sets", "the", "migration", "mode", "of", "the", "model", "to", "none", "meaning", "it", "is", "ready", "for", "use", ".", "It", "is", "an", "error", "to", "attempt", "to", "Abort", "a", "model", "that", "has", "a", "migration", "mode", "other", "than", "importing", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/migrationtarget/migrationtarget.go#L174-L187
155,220
juju/juju
caas/kubernetes/provider/cloud.go
CloudFromKubeConfig
func CloudFromKubeConfig(reader io.Reader, cloudParams KubeCloudParams) (cloud.Cloud, cloud.Credential, string, error) { return newCloudCredentialFromKubeConfig(reader, cloudParams) }
go
func CloudFromKubeConfig(reader io.Reader, cloudParams KubeCloudParams) (cloud.Cloud, cloud.Credential, string, error) { return newCloudCredentialFromKubeConfig(reader, cloudParams) }
[ "func", "CloudFromKubeConfig", "(", "reader", "io", ".", "Reader", ",", "cloudParams", "KubeCloudParams", ")", "(", "cloud", ".", "Cloud", ",", "cloud", ".", "Credential", ",", "string", ",", "error", ")", "{", "return", "newCloudCredentialFromKubeConfig", "(", "reader", ",", "cloudParams", ")", "\n", "}" ]
// CloudFromKubeConfig attempts to extract a cloud and credential details from the provided Kubeconfig.
[ "CloudFromKubeConfig", "attempts", "to", "extract", "a", "cloud", "and", "credential", "details", "from", "the", "provided", "Kubeconfig", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/cloud.go#L49-L51
155,221
juju/juju
caas/kubernetes/provider/cloud.go
ParseCloudRegion
func ParseCloudRegion(cloudRegion string) (string, string, error) { fields := strings.SplitN(cloudRegion, "/", 2) if len(fields) != 2 || fields[0] == "" || fields[1] == "" { return "", "", errors.NotValidf("cloud region %q", cloudRegion) } return fields[0], fields[1], nil }
go
func ParseCloudRegion(cloudRegion string) (string, string, error) { fields := strings.SplitN(cloudRegion, "/", 2) if len(fields) != 2 || fields[0] == "" || fields[1] == "" { return "", "", errors.NotValidf("cloud region %q", cloudRegion) } return fields[0], fields[1], nil }
[ "func", "ParseCloudRegion", "(", "cloudRegion", "string", ")", "(", "string", ",", "string", ",", "error", ")", "{", "fields", ":=", "strings", ".", "SplitN", "(", "cloudRegion", ",", "\"", "\"", ",", "2", ")", "\n", "if", "len", "(", "fields", ")", "!=", "2", "||", "fields", "[", "0", "]", "==", "\"", "\"", "||", "fields", "[", "1", "]", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "cloudRegion", ")", "\n", "}", "\n", "return", "fields", "[", "0", "]", ",", "fields", "[", "1", "]", ",", "nil", "\n", "}" ]
// ParseCloudRegion breaks apart a clusters cloud region.
[ "ParseCloudRegion", "breaks", "apart", "a", "clusters", "cloud", "region", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/cloud.go#L211-L217
155,222
juju/juju
caas/kubernetes/provider/cloud.go
BaseKubeCloudOpenParams
func BaseKubeCloudOpenParams(cloud cloud.Cloud, credential cloud.Credential) (environs.OpenParams, error) { // To get a k8s client, we need a config with minimal information. // It's not used unless operating on a real model but we need to supply it. uuid, err := utils.NewUUID() if err != nil { return environs.OpenParams{}, errors.Trace(err) } attrs := map[string]interface{}{ config.NameKey: "add-cloud", config.TypeKey: "kubernetes", config.UUIDKey: uuid.String(), } cfg, err := config.New(config.NoDefaults, attrs) if err != nil { return environs.OpenParams{}, errors.Trace(err) } cloudSpec, err := environs.MakeCloudSpec(cloud, "", &credential) if err != nil { return environs.OpenParams{}, errors.Trace(err) } openParams := environs.OpenParams{ Cloud: cloudSpec, Config: cfg, } return openParams, nil }
go
func BaseKubeCloudOpenParams(cloud cloud.Cloud, credential cloud.Credential) (environs.OpenParams, error) { // To get a k8s client, we need a config with minimal information. // It's not used unless operating on a real model but we need to supply it. uuid, err := utils.NewUUID() if err != nil { return environs.OpenParams{}, errors.Trace(err) } attrs := map[string]interface{}{ config.NameKey: "add-cloud", config.TypeKey: "kubernetes", config.UUIDKey: uuid.String(), } cfg, err := config.New(config.NoDefaults, attrs) if err != nil { return environs.OpenParams{}, errors.Trace(err) } cloudSpec, err := environs.MakeCloudSpec(cloud, "", &credential) if err != nil { return environs.OpenParams{}, errors.Trace(err) } openParams := environs.OpenParams{ Cloud: cloudSpec, Config: cfg, } return openParams, nil }
[ "func", "BaseKubeCloudOpenParams", "(", "cloud", "cloud", ".", "Cloud", ",", "credential", "cloud", ".", "Credential", ")", "(", "environs", ".", "OpenParams", ",", "error", ")", "{", "// To get a k8s client, we need a config with minimal information.", "// It's not used unless operating on a real model but we need to supply it.", "uuid", ",", "err", ":=", "utils", ".", "NewUUID", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "environs", ".", "OpenParams", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "attrs", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "config", ".", "NameKey", ":", "\"", "\"", ",", "config", ".", "TypeKey", ":", "\"", "\"", ",", "config", ".", "UUIDKey", ":", "uuid", ".", "String", "(", ")", ",", "}", "\n", "cfg", ",", "err", ":=", "config", ".", "New", "(", "config", ".", "NoDefaults", ",", "attrs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "environs", ".", "OpenParams", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "cloudSpec", ",", "err", ":=", "environs", ".", "MakeCloudSpec", "(", "cloud", ",", "\"", "\"", ",", "&", "credential", ")", "\n", "if", "err", "!=", "nil", "{", "return", "environs", ".", "OpenParams", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "openParams", ":=", "environs", ".", "OpenParams", "{", "Cloud", ":", "cloudSpec", ",", "Config", ":", "cfg", ",", "}", "\n", "return", "openParams", ",", "nil", "\n", "}" ]
// BaseKubeCloudOpenParams provides a basic OpenParams for a cluster
[ "BaseKubeCloudOpenParams", "provides", "a", "basic", "OpenParams", "for", "a", "cluster" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/cloud.go#L220-L245
155,223
juju/juju
api/metricsdebug/client.go
GetMetrics
func (c *Client) GetMetrics(tags ...string) ([]params.MetricResult, error) { entities := make([]params.Entity, len(tags)) for i, tag := range tags { entities[i] = params.Entity{Tag: tag} } p := params.Entities{Entities: entities} results := new(params.MetricResults) if err := c.facade.FacadeCall("GetMetrics", p, results); err != nil { return nil, errors.Trace(err) } if err := results.OneError(); err != nil { return nil, errors.Trace(err) } metrics := []params.MetricResult{} for _, r := range results.Results { metrics = append(metrics, r.Metrics...) } return metrics, nil }
go
func (c *Client) GetMetrics(tags ...string) ([]params.MetricResult, error) { entities := make([]params.Entity, len(tags)) for i, tag := range tags { entities[i] = params.Entity{Tag: tag} } p := params.Entities{Entities: entities} results := new(params.MetricResults) if err := c.facade.FacadeCall("GetMetrics", p, results); err != nil { return nil, errors.Trace(err) } if err := results.OneError(); err != nil { return nil, errors.Trace(err) } metrics := []params.MetricResult{} for _, r := range results.Results { metrics = append(metrics, r.Metrics...) } return metrics, nil }
[ "func", "(", "c", "*", "Client", ")", "GetMetrics", "(", "tags", "...", "string", ")", "(", "[", "]", "params", ".", "MetricResult", ",", "error", ")", "{", "entities", ":=", "make", "(", "[", "]", "params", ".", "Entity", ",", "len", "(", "tags", ")", ")", "\n", "for", "i", ",", "tag", ":=", "range", "tags", "{", "entities", "[", "i", "]", "=", "params", ".", "Entity", "{", "Tag", ":", "tag", "}", "\n", "}", "\n", "p", ":=", "params", ".", "Entities", "{", "Entities", ":", "entities", "}", "\n", "results", ":=", "new", "(", "params", ".", "MetricResults", ")", "\n", "if", "err", ":=", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "p", ",", "results", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "results", ".", "OneError", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "metrics", ":=", "[", "]", "params", ".", "MetricResult", "{", "}", "\n", "for", "_", ",", "r", ":=", "range", "results", ".", "Results", "{", "metrics", "=", "append", "(", "metrics", ",", "r", ".", "Metrics", "...", ")", "\n", "}", "\n", "return", "metrics", ",", "nil", "\n", "}" ]
// GetMetrics will receive metrics collected by the given entity
[ "GetMetrics", "will", "receive", "metrics", "collected", "by", "the", "given", "entity" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/metricsdebug/client.go#L48-L66
155,224
juju/juju
api/metricsdebug/client.go
SetMeterStatus
func (c *Client) SetMeterStatus(tag, code, info string) error { args := params.MeterStatusParams{ Statuses: []params.MeterStatusParam{{ Tag: tag, Code: code, Info: info, }, }, } results := new(params.ErrorResults) if err := c.facade.FacadeCall("SetMeterStatus", args, results); err != nil { return errors.Trace(err) } if err := results.OneError(); err != nil { return errors.Trace(err) } return nil }
go
func (c *Client) SetMeterStatus(tag, code, info string) error { args := params.MeterStatusParams{ Statuses: []params.MeterStatusParam{{ Tag: tag, Code: code, Info: info, }, }, } results := new(params.ErrorResults) if err := c.facade.FacadeCall("SetMeterStatus", args, results); err != nil { return errors.Trace(err) } if err := results.OneError(); err != nil { return errors.Trace(err) } return nil }
[ "func", "(", "c", "*", "Client", ")", "SetMeterStatus", "(", "tag", ",", "code", ",", "info", "string", ")", "error", "{", "args", ":=", "params", ".", "MeterStatusParams", "{", "Statuses", ":", "[", "]", "params", ".", "MeterStatusParam", "{", "{", "Tag", ":", "tag", ",", "Code", ":", "code", ",", "Info", ":", "info", ",", "}", ",", "}", ",", "}", "\n", "results", ":=", "new", "(", "params", ".", "ErrorResults", ")", "\n", "if", "err", ":=", "c", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "results", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "results", ".", "OneError", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetMeterStatus will set the meter status on the given entity tag.
[ "SetMeterStatus", "will", "set", "the", "meter", "status", "on", "the", "given", "entity", "tag", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/metricsdebug/client.go#L69-L86
155,225
juju/juju
environs/tools/storage.go
StorageName
func StorageName(vers version.Binary, stream string) string { return storagePrefix(stream) + vers.String() + toolSuffix }
go
func StorageName(vers version.Binary, stream string) string { return storagePrefix(stream) + vers.String() + toolSuffix }
[ "func", "StorageName", "(", "vers", "version", ".", "Binary", ",", "stream", "string", ")", "string", "{", "return", "storagePrefix", "(", "stream", ")", "+", "vers", ".", "String", "(", ")", "+", "toolSuffix", "\n", "}" ]
// StorageName returns the name that is used to store and retrieve the // given version of the juju tools.
[ "StorageName", "returns", "the", "name", "that", "is", "used", "to", "store", "and", "retrieve", "the", "given", "version", "of", "the", "juju", "tools", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/storage.go#L28-L30
155,226
juju/juju
environs/tools/storage.go
ReadList
func ReadList(stor storage.StorageReader, toolsDir string, majorVersion, minorVersion int) (coretools.List, error) { if minorVersion >= 0 { logger.Debugf("reading v%d.%d agent binaries", majorVersion, minorVersion) } else { logger.Debugf("reading v%d.* agent binaries", majorVersion) } storagePrefix := storagePrefix(toolsDir) names, err := storage.List(stor, storagePrefix) if err != nil { return nil, err } var list coretools.List var foundAnyTools bool for _, name := range names { name = filepath.ToSlash(name) if !strings.HasPrefix(name, storagePrefix) || !strings.HasSuffix(name, toolSuffix) { continue } var t coretools.Tools vers := name[len(storagePrefix) : len(name)-len(toolSuffix)] if t.Version, err = version.ParseBinary(vers); err != nil { logger.Debugf("failed to parse version %q: %v", vers, err) continue } foundAnyTools = true // If specified major version value supplied, major version must match. if majorVersion >= 0 && t.Version.Major != majorVersion { continue } // If specified minor version value supplied, minor version must match. if minorVersion >= 0 && t.Version.Minor != minorVersion { continue } logger.Debugf("found %s", vers) if t.URL, err = stor.URL(name); err != nil { return nil, err } list = append(list, &t) // Older versions of Juju only know about ppc64, so add metadata for that arch. if t.Version.Arch == arch.PPC64EL { legacyPPC64Tools := t legacyPPC64Tools.Version.Arch = arch.LEGACY_PPC64 list = append(list, &legacyPPC64Tools) } } if len(list) == 0 { if foundAnyTools { return nil, coretools.ErrNoMatches } return nil, ErrNoTools } return list, nil }
go
func ReadList(stor storage.StorageReader, toolsDir string, majorVersion, minorVersion int) (coretools.List, error) { if minorVersion >= 0 { logger.Debugf("reading v%d.%d agent binaries", majorVersion, minorVersion) } else { logger.Debugf("reading v%d.* agent binaries", majorVersion) } storagePrefix := storagePrefix(toolsDir) names, err := storage.List(stor, storagePrefix) if err != nil { return nil, err } var list coretools.List var foundAnyTools bool for _, name := range names { name = filepath.ToSlash(name) if !strings.HasPrefix(name, storagePrefix) || !strings.HasSuffix(name, toolSuffix) { continue } var t coretools.Tools vers := name[len(storagePrefix) : len(name)-len(toolSuffix)] if t.Version, err = version.ParseBinary(vers); err != nil { logger.Debugf("failed to parse version %q: %v", vers, err) continue } foundAnyTools = true // If specified major version value supplied, major version must match. if majorVersion >= 0 && t.Version.Major != majorVersion { continue } // If specified minor version value supplied, minor version must match. if minorVersion >= 0 && t.Version.Minor != minorVersion { continue } logger.Debugf("found %s", vers) if t.URL, err = stor.URL(name); err != nil { return nil, err } list = append(list, &t) // Older versions of Juju only know about ppc64, so add metadata for that arch. if t.Version.Arch == arch.PPC64EL { legacyPPC64Tools := t legacyPPC64Tools.Version.Arch = arch.LEGACY_PPC64 list = append(list, &legacyPPC64Tools) } } if len(list) == 0 { if foundAnyTools { return nil, coretools.ErrNoMatches } return nil, ErrNoTools } return list, nil }
[ "func", "ReadList", "(", "stor", "storage", ".", "StorageReader", ",", "toolsDir", "string", ",", "majorVersion", ",", "minorVersion", "int", ")", "(", "coretools", ".", "List", ",", "error", ")", "{", "if", "minorVersion", ">=", "0", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "majorVersion", ",", "minorVersion", ")", "\n", "}", "else", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "majorVersion", ")", "\n", "}", "\n", "storagePrefix", ":=", "storagePrefix", "(", "toolsDir", ")", "\n", "names", ",", "err", ":=", "storage", ".", "List", "(", "stor", ",", "storagePrefix", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "list", "coretools", ".", "List", "\n", "var", "foundAnyTools", "bool", "\n", "for", "_", ",", "name", ":=", "range", "names", "{", "name", "=", "filepath", ".", "ToSlash", "(", "name", ")", "\n", "if", "!", "strings", ".", "HasPrefix", "(", "name", ",", "storagePrefix", ")", "||", "!", "strings", ".", "HasSuffix", "(", "name", ",", "toolSuffix", ")", "{", "continue", "\n", "}", "\n", "var", "t", "coretools", ".", "Tools", "\n", "vers", ":=", "name", "[", "len", "(", "storagePrefix", ")", ":", "len", "(", "name", ")", "-", "len", "(", "toolSuffix", ")", "]", "\n", "if", "t", ".", "Version", ",", "err", "=", "version", ".", "ParseBinary", "(", "vers", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "vers", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "foundAnyTools", "=", "true", "\n", "// If specified major version value supplied, major version must match.", "if", "majorVersion", ">=", "0", "&&", "t", ".", "Version", ".", "Major", "!=", "majorVersion", "{", "continue", "\n", "}", "\n", "// If specified minor version value supplied, minor version must match.", "if", "minorVersion", ">=", "0", "&&", "t", ".", "Version", ".", "Minor", "!=", "minorVersion", "{", "continue", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "vers", ")", "\n", "if", "t", ".", "URL", ",", "err", "=", "stor", ".", "URL", "(", "name", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "list", "=", "append", "(", "list", ",", "&", "t", ")", "\n", "// Older versions of Juju only know about ppc64, so add metadata for that arch.", "if", "t", ".", "Version", ".", "Arch", "==", "arch", ".", "PPC64EL", "{", "legacyPPC64Tools", ":=", "t", "\n", "legacyPPC64Tools", ".", "Version", ".", "Arch", "=", "arch", ".", "LEGACY_PPC64", "\n", "list", "=", "append", "(", "list", ",", "&", "legacyPPC64Tools", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "list", ")", "==", "0", "{", "if", "foundAnyTools", "{", "return", "nil", ",", "coretools", ".", "ErrNoMatches", "\n", "}", "\n", "return", "nil", ",", "ErrNoTools", "\n", "}", "\n", "return", "list", ",", "nil", "\n", "}" ]
// ReadList returns a List of the tools in store with the given major.minor version. // If minorVersion = -1, then only majorVersion is considered. // If majorVersion is -1, then all tools tarballs are used. // If store contains no such tools, it returns ErrNoMatches.
[ "ReadList", "returns", "a", "List", "of", "the", "tools", "in", "store", "with", "the", "given", "major", ".", "minor", "version", ".", "If", "minorVersion", "=", "-", "1", "then", "only", "majorVersion", "is", "considered", ".", "If", "majorVersion", "is", "-", "1", "then", "all", "tools", "tarballs", "are", "used", ".", "If", "store", "contains", "no", "such", "tools", "it", "returns", "ErrNoMatches", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/tools/storage.go#L40-L92
155,227
juju/juju
resource/api/download.go
NewHTTPDownloadRequest
func NewHTTPDownloadRequest(resourceName string) (*http.Request, error) { return http.NewRequest("GET", "/resources/"+resourceName, nil) }
go
func NewHTTPDownloadRequest(resourceName string) (*http.Request, error) { return http.NewRequest("GET", "/resources/"+resourceName, nil) }
[ "func", "NewHTTPDownloadRequest", "(", "resourceName", "string", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "return", "http", ".", "NewRequest", "(", "\"", "\"", ",", "\"", "\"", "+", "resourceName", ",", "nil", ")", "\n", "}" ]
// NewHTTPDownloadRequest creates a new HTTP download request // for the given resource. // // Intended for use on the client side.
[ "NewHTTPDownloadRequest", "creates", "a", "new", "HTTP", "download", "request", "for", "the", "given", "resource", ".", "Intended", "for", "use", "on", "the", "client", "side", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/resource/api/download.go#L12-L14
155,228
juju/juju
provider/gce/google/zone.go
NewZone
func NewZone(name, status, state, replacement string) AvailabilityZone { zone := &compute.Zone{ Name: name, Status: status, } if state != "" { zone.Deprecated = &compute.DeprecationStatus{ State: state, Replacement: replacement, } } return AvailabilityZone{zone: zone} }
go
func NewZone(name, status, state, replacement string) AvailabilityZone { zone := &compute.Zone{ Name: name, Status: status, } if state != "" { zone.Deprecated = &compute.DeprecationStatus{ State: state, Replacement: replacement, } } return AvailabilityZone{zone: zone} }
[ "func", "NewZone", "(", "name", ",", "status", ",", "state", ",", "replacement", "string", ")", "AvailabilityZone", "{", "zone", ":=", "&", "compute", ".", "Zone", "{", "Name", ":", "name", ",", "Status", ":", "status", ",", "}", "\n", "if", "state", "!=", "\"", "\"", "{", "zone", ".", "Deprecated", "=", "&", "compute", ".", "DeprecationStatus", "{", "State", ":", "state", ",", "Replacement", ":", "replacement", ",", "}", "\n", "}", "\n", "return", "AvailabilityZone", "{", "zone", ":", "zone", "}", "\n", "}" ]
// NewZone build an availability zone from the provided name, status // state, and replacement and returns it.
[ "NewZone", "build", "an", "availability", "zone", "from", "the", "provided", "name", "status", "state", "and", "replacement", "and", "returns", "it", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/zone.go#L18-L30
155,229
juju/juju
provider/gce/google/zone.go
Deprecated
func (z AvailabilityZone) Deprecated() bool { deprecated := z.zone.Deprecated != nil if deprecated { logger.Warningf("zone %q is %q", z.Name(), z.zone.Deprecated.State) if z.zone.Deprecated.Replacement != "" { logger.Warningf("zone %q is the replacement for zone %q", z.zone.Deprecated.Replacement, z.Name()) } } return deprecated }
go
func (z AvailabilityZone) Deprecated() bool { deprecated := z.zone.Deprecated != nil if deprecated { logger.Warningf("zone %q is %q", z.Name(), z.zone.Deprecated.State) if z.zone.Deprecated.Replacement != "" { logger.Warningf("zone %q is the replacement for zone %q", z.zone.Deprecated.Replacement, z.Name()) } } return deprecated }
[ "func", "(", "z", "AvailabilityZone", ")", "Deprecated", "(", ")", "bool", "{", "deprecated", ":=", "z", ".", "zone", ".", "Deprecated", "!=", "nil", "\n", "if", "deprecated", "{", "logger", ".", "Warningf", "(", "\"", "\"", ",", "z", ".", "Name", "(", ")", ",", "z", ".", "zone", ".", "Deprecated", ".", "State", ")", "\n", "if", "z", ".", "zone", ".", "Deprecated", ".", "Replacement", "!=", "\"", "\"", "{", "logger", ".", "Warningf", "(", "\"", "\"", ",", "z", ".", "zone", ".", "Deprecated", ".", "Replacement", ",", "z", ".", "Name", "(", ")", ")", "\n", "}", "\n", "}", "\n", "return", "deprecated", "\n", "}" ]
// Deprecated returns true if the zone has been deprecated.
[ "Deprecated", "returns", "true", "if", "the", "zone", "has", "been", "deprecated", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/gce/google/zone.go#L46-L55
155,230
juju/juju
api/agent/state.go
IsMaster
func (st *State) IsMaster() (bool, error) { var results params.IsMasterResult err := st.facade.FacadeCall("IsMaster", nil, &results) return results.Master, err }
go
func (st *State) IsMaster() (bool, error) { var results params.IsMasterResult err := st.facade.FacadeCall("IsMaster", nil, &results) return results.Master, err }
[ "func", "(", "st", "*", "State", ")", "IsMaster", "(", ")", "(", "bool", ",", "error", ")", "{", "var", "results", "params", ".", "IsMasterResult", "\n", "err", ":=", "st", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "nil", ",", "&", "results", ")", "\n", "return", "results", ".", "Master", ",", "err", "\n", "}" ]
// IsMaster reports whether the connected machine // agent lives at the same network address as the primary // mongo server for the replica set. // This call will return an error if the connected // agent is not a machine agent with model-manager // privileges.
[ "IsMaster", "reports", "whether", "the", "connected", "machine", "agent", "lives", "at", "the", "same", "network", "address", "as", "the", "primary", "mongo", "server", "for", "the", "replica", "set", ".", "This", "call", "will", "return", "an", "error", "if", "the", "connected", "agent", "is", "not", "a", "machine", "agent", "with", "model", "-", "manager", "privileges", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/agent/state.go#L74-L78
155,231
juju/juju
api/agent/state.go
ClearReboot
func (m *Entity) ClearReboot() error { var result params.ErrorResults args := params.SetStatus{ Entities: []params.EntityStatusArgs{ {Tag: m.tag.String()}, }, } err := m.st.facade.FacadeCall("ClearReboot", args, &result) if err != nil { return err } return result.OneError() }
go
func (m *Entity) ClearReboot() error { var result params.ErrorResults args := params.SetStatus{ Entities: []params.EntityStatusArgs{ {Tag: m.tag.String()}, }, } err := m.st.facade.FacadeCall("ClearReboot", args, &result) if err != nil { return err } return result.OneError() }
[ "func", "(", "m", "*", "Entity", ")", "ClearReboot", "(", ")", "error", "{", "var", "result", "params", ".", "ErrorResults", "\n", "args", ":=", "params", ".", "SetStatus", "{", "Entities", ":", "[", "]", "params", ".", "EntityStatusArgs", "{", "{", "Tag", ":", "m", ".", "tag", ".", "String", "(", ")", "}", ",", "}", ",", "}", "\n", "err", ":=", "m", ".", "st", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "result", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "result", ".", "OneError", "(", ")", "\n", "}" ]
// ClearReboot clears the reboot flag of the machine.
[ "ClearReboot", "clears", "the", "reboot", "flag", "of", "the", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/agent/state.go#L139-L151
155,232
juju/juju
apiserver/facades/controller/externalcontrollerupdater/externalcontrollerupdater.go
NewStateAPI
func NewStateAPI(ctx facade.Context) (*ExternalControllerUpdaterAPI, error) { return NewAPI( ctx.Auth(), ctx.Resources(), state.NewExternalControllers(ctx.State()), ) }
go
func NewStateAPI(ctx facade.Context) (*ExternalControllerUpdaterAPI, error) { return NewAPI( ctx.Auth(), ctx.Resources(), state.NewExternalControllers(ctx.State()), ) }
[ "func", "NewStateAPI", "(", "ctx", "facade", ".", "Context", ")", "(", "*", "ExternalControllerUpdaterAPI", ",", "error", ")", "{", "return", "NewAPI", "(", "ctx", ".", "Auth", "(", ")", ",", "ctx", ".", "Resources", "(", ")", ",", "state", ".", "NewExternalControllers", "(", "ctx", ".", "State", "(", ")", ")", ",", ")", "\n", "}" ]
// NewStateAPI creates a new server-side CrossModelRelationsAPI API facade // backed by global state.
[ "NewStateAPI", "creates", "a", "new", "server", "-", "side", "CrossModelRelationsAPI", "API", "facade", "backed", "by", "global", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/externalcontrollerupdater/externalcontrollerupdater.go#L28-L34
155,233
juju/juju
apiserver/facades/controller/externalcontrollerupdater/externalcontrollerupdater.go
NewAPI
func NewAPI( auth facade.Authorizer, resources facade.Resources, externalControllers state.ExternalControllers, ) (*ExternalControllerUpdaterAPI, error) { if !auth.AuthController() { return nil, common.ErrPerm } return &ExternalControllerUpdaterAPI{ externalControllers, resources, }, nil }
go
func NewAPI( auth facade.Authorizer, resources facade.Resources, externalControllers state.ExternalControllers, ) (*ExternalControllerUpdaterAPI, error) { if !auth.AuthController() { return nil, common.ErrPerm } return &ExternalControllerUpdaterAPI{ externalControllers, resources, }, nil }
[ "func", "NewAPI", "(", "auth", "facade", ".", "Authorizer", ",", "resources", "facade", ".", "Resources", ",", "externalControllers", "state", ".", "ExternalControllers", ",", ")", "(", "*", "ExternalControllerUpdaterAPI", ",", "error", ")", "{", "if", "!", "auth", ".", "AuthController", "(", ")", "{", "return", "nil", ",", "common", ".", "ErrPerm", "\n", "}", "\n", "return", "&", "ExternalControllerUpdaterAPI", "{", "externalControllers", ",", "resources", ",", "}", ",", "nil", "\n", "}" ]
// NewAPI creates a new server-side CrossModelRelationsAPI API facade backed // by the given interfaces.
[ "NewAPI", "creates", "a", "new", "server", "-", "side", "CrossModelRelationsAPI", "API", "facade", "backed", "by", "the", "given", "interfaces", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/externalcontrollerupdater/externalcontrollerupdater.go#L38-L50
155,234
juju/juju
apiserver/facades/controller/externalcontrollerupdater/externalcontrollerupdater.go
WatchExternalControllers
func (api *ExternalControllerUpdaterAPI) WatchExternalControllers() (params.StringsWatchResults, error) { w := api.externalControllers.Watch() changes, ok := <-w.Changes() if !ok { return params.StringsWatchResults{ []params.StringsWatchResult{{ Error: common.ServerError(watcher.EnsureErr(w)), }}, }, nil } return params.StringsWatchResults{ []params.StringsWatchResult{{ StringsWatcherId: api.resources.Register(w), Changes: changes, }}, }, nil }
go
func (api *ExternalControllerUpdaterAPI) WatchExternalControllers() (params.StringsWatchResults, error) { w := api.externalControllers.Watch() changes, ok := <-w.Changes() if !ok { return params.StringsWatchResults{ []params.StringsWatchResult{{ Error: common.ServerError(watcher.EnsureErr(w)), }}, }, nil } return params.StringsWatchResults{ []params.StringsWatchResult{{ StringsWatcherId: api.resources.Register(w), Changes: changes, }}, }, nil }
[ "func", "(", "api", "*", "ExternalControllerUpdaterAPI", ")", "WatchExternalControllers", "(", ")", "(", "params", ".", "StringsWatchResults", ",", "error", ")", "{", "w", ":=", "api", ".", "externalControllers", ".", "Watch", "(", ")", "\n", "changes", ",", "ok", ":=", "<-", "w", ".", "Changes", "(", ")", "\n", "if", "!", "ok", "{", "return", "params", ".", "StringsWatchResults", "{", "[", "]", "params", ".", "StringsWatchResult", "{", "{", "Error", ":", "common", ".", "ServerError", "(", "watcher", ".", "EnsureErr", "(", "w", ")", ")", ",", "}", "}", ",", "}", ",", "nil", "\n", "}", "\n", "return", "params", ".", "StringsWatchResults", "{", "[", "]", "params", ".", "StringsWatchResult", "{", "{", "StringsWatcherId", ":", "api", ".", "resources", ".", "Register", "(", "w", ")", ",", "Changes", ":", "changes", ",", "}", "}", ",", "}", ",", "nil", "\n", "}" ]
// WatchExternalControllers watches for the addition and removal of external // controller records to the local controller's database.
[ "WatchExternalControllers", "watches", "for", "the", "addition", "and", "removal", "of", "external", "controller", "records", "to", "the", "local", "controller", "s", "database", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/externalcontrollerupdater/externalcontrollerupdater.go#L54-L70
155,235
juju/juju
apiserver/facades/controller/externalcontrollerupdater/externalcontrollerupdater.go
ExternalControllerInfo
func (s *ExternalControllerUpdaterAPI) ExternalControllerInfo(args params.Entities) (params.ExternalControllerInfoResults, error) { result := params.ExternalControllerInfoResults{ Results: make([]params.ExternalControllerInfoResult, len(args.Entities)), } for i, entity := range args.Entities { controllerTag, err := names.ParseControllerTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } controller, err := s.externalControllers.Controller(controllerTag.Id()) if err != nil { result.Results[i].Error = common.ServerError(err) continue } info := controller.ControllerInfo() result.Results[i].Result = &params.ExternalControllerInfo{ ControllerTag: controllerTag.String(), Alias: info.Alias, Addrs: info.Addrs, CACert: info.CACert, } } return result, nil }
go
func (s *ExternalControllerUpdaterAPI) ExternalControllerInfo(args params.Entities) (params.ExternalControllerInfoResults, error) { result := params.ExternalControllerInfoResults{ Results: make([]params.ExternalControllerInfoResult, len(args.Entities)), } for i, entity := range args.Entities { controllerTag, err := names.ParseControllerTag(entity.Tag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } controller, err := s.externalControllers.Controller(controllerTag.Id()) if err != nil { result.Results[i].Error = common.ServerError(err) continue } info := controller.ControllerInfo() result.Results[i].Result = &params.ExternalControllerInfo{ ControllerTag: controllerTag.String(), Alias: info.Alias, Addrs: info.Addrs, CACert: info.CACert, } } return result, nil }
[ "func", "(", "s", "*", "ExternalControllerUpdaterAPI", ")", "ExternalControllerInfo", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "ExternalControllerInfoResults", ",", "error", ")", "{", "result", ":=", "params", ".", "ExternalControllerInfoResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "ExternalControllerInfoResult", ",", "len", "(", "args", ".", "Entities", ")", ")", ",", "}", "\n", "for", "i", ",", "entity", ":=", "range", "args", ".", "Entities", "{", "controllerTag", ",", "err", ":=", "names", ".", "ParseControllerTag", "(", "entity", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "controller", ",", "err", ":=", "s", ".", "externalControllers", ".", "Controller", "(", "controllerTag", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "info", ":=", "controller", ".", "ControllerInfo", "(", ")", "\n", "result", ".", "Results", "[", "i", "]", ".", "Result", "=", "&", "params", ".", "ExternalControllerInfo", "{", "ControllerTag", ":", "controllerTag", ".", "String", "(", ")", ",", "Alias", ":", "info", ".", "Alias", ",", "Addrs", ":", "info", ".", "Addrs", ",", "CACert", ":", "info", ".", "CACert", ",", "}", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// ExternalControllerInfo returns the info for the specified external controllers.
[ "ExternalControllerInfo", "returns", "the", "info", "for", "the", "specified", "external", "controllers", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/externalcontrollerupdater/externalcontrollerupdater.go#L73-L97
155,236
juju/juju
apiserver/facades/controller/externalcontrollerupdater/externalcontrollerupdater.go
SetExternalControllerInfo
func (s *ExternalControllerUpdaterAPI) SetExternalControllerInfo(args params.SetExternalControllersInfoParams) (params.ErrorResults, error) { result := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Controllers)), } for i, arg := range args.Controllers { controllerTag, err := names.ParseControllerTag(arg.Info.ControllerTag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } if _, err := s.externalControllers.Save(crossmodel.ControllerInfo{ ControllerTag: controllerTag, Alias: arg.Info.Alias, Addrs: arg.Info.Addrs, CACert: arg.Info.CACert, }); err != nil { result.Results[i].Error = common.ServerError(err) continue } } return result, nil }
go
func (s *ExternalControllerUpdaterAPI) SetExternalControllerInfo(args params.SetExternalControllersInfoParams) (params.ErrorResults, error) { result := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Controllers)), } for i, arg := range args.Controllers { controllerTag, err := names.ParseControllerTag(arg.Info.ControllerTag) if err != nil { result.Results[i].Error = common.ServerError(err) continue } if _, err := s.externalControllers.Save(crossmodel.ControllerInfo{ ControllerTag: controllerTag, Alias: arg.Info.Alias, Addrs: arg.Info.Addrs, CACert: arg.Info.CACert, }); err != nil { result.Results[i].Error = common.ServerError(err) continue } } return result, nil }
[ "func", "(", "s", "*", "ExternalControllerUpdaterAPI", ")", "SetExternalControllerInfo", "(", "args", "params", ".", "SetExternalControllersInfoParams", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "result", ":=", "params", ".", "ErrorResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "args", ".", "Controllers", ")", ")", ",", "}", "\n", "for", "i", ",", "arg", ":=", "range", "args", ".", "Controllers", "{", "controllerTag", ",", "err", ":=", "names", ".", "ParseControllerTag", "(", "arg", ".", "Info", ".", "ControllerTag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "_", ",", "err", ":=", "s", ".", "externalControllers", ".", "Save", "(", "crossmodel", ".", "ControllerInfo", "{", "ControllerTag", ":", "controllerTag", ",", "Alias", ":", "arg", ".", "Info", ".", "Alias", ",", "Addrs", ":", "arg", ".", "Info", ".", "Addrs", ",", "CACert", ":", "arg", ".", "Info", ".", "CACert", ",", "}", ")", ";", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// SetExternalControllerInfo saves the info for the specified external controllers.
[ "SetExternalControllerInfo", "saves", "the", "info", "for", "the", "specified", "external", "controllers", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/controller/externalcontrollerupdater/externalcontrollerupdater.go#L100-L121
155,237
juju/juju
container/broker/instance_broker.go
Validate
func (c Config) Validate() error { if c.Name == "" { return errors.NotValidf("empty Name") } if string(c.ContainerType) == "" { return errors.NotValidf("empty ContainerType") } if c.APICaller == nil { return errors.NotValidf("nil APICaller") } if c.AgentConfig == nil { return errors.NotValidf("nil AgentConfig") } if c.MachineTag.Id() == "" { return errors.NotValidf("empty MachineTag") } if c.MachineLock == nil { return errors.NotValidf("nil MachineLock") } if c.GetNetConfig == nil { return errors.NotValidf("nil GetNetConfig") } return nil }
go
func (c Config) Validate() error { if c.Name == "" { return errors.NotValidf("empty Name") } if string(c.ContainerType) == "" { return errors.NotValidf("empty ContainerType") } if c.APICaller == nil { return errors.NotValidf("nil APICaller") } if c.AgentConfig == nil { return errors.NotValidf("nil AgentConfig") } if c.MachineTag.Id() == "" { return errors.NotValidf("empty MachineTag") } if c.MachineLock == nil { return errors.NotValidf("nil MachineLock") } if c.GetNetConfig == nil { return errors.NotValidf("nil GetNetConfig") } return nil }
[ "func", "(", "c", "Config", ")", "Validate", "(", ")", "error", "{", "if", "c", ".", "Name", "==", "\"", "\"", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "string", "(", "c", ".", "ContainerType", ")", "==", "\"", "\"", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "APICaller", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "AgentConfig", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "MachineTag", ".", "Id", "(", ")", "==", "\"", "\"", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "MachineLock", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "GetNetConfig", "==", "nil", "{", "return", "errors", ".", "NotValidf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate validates the instance broker configuration.
[ "Validate", "validates", "the", "instance", "broker", "configuration", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/broker/instance_broker.go#L50-L73
155,238
juju/juju
container/broker/instance_broker.go
New
func New(config Config) (environs.InstanceBroker, error) { if err := config.Validate(); err != nil { return nil, errors.Trace(err) } manager, err := factory.NewContainerManager(config.ContainerType, config.ManagerConfig) if err != nil { return nil, errors.Trace(err) } var newBroker ContainerBrokerFunc switch config.ContainerType { case instance.KVM: newBroker = NewKVMBroker case instance.LXD: newBroker = NewLXDBroker default: return nil, errors.NotValidf("ContainerType %s", config.ContainerType) } broker, err := newBroker(prepareHost(config), config.APICaller, manager, config.AgentConfig) if err != nil { logger.Errorf("failed to create new %s broker", config.ContainerType) return nil, errors.Trace(err) } return broker, nil }
go
func New(config Config) (environs.InstanceBroker, error) { if err := config.Validate(); err != nil { return nil, errors.Trace(err) } manager, err := factory.NewContainerManager(config.ContainerType, config.ManagerConfig) if err != nil { return nil, errors.Trace(err) } var newBroker ContainerBrokerFunc switch config.ContainerType { case instance.KVM: newBroker = NewKVMBroker case instance.LXD: newBroker = NewLXDBroker default: return nil, errors.NotValidf("ContainerType %s", config.ContainerType) } broker, err := newBroker(prepareHost(config), config.APICaller, manager, config.AgentConfig) if err != nil { logger.Errorf("failed to create new %s broker", config.ContainerType) return nil, errors.Trace(err) } return broker, nil }
[ "func", "New", "(", "config", "Config", ")", "(", "environs", ".", "InstanceBroker", ",", "error", ")", "{", "if", "err", ":=", "config", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "manager", ",", "err", ":=", "factory", ".", "NewContainerManager", "(", "config", ".", "ContainerType", ",", "config", ".", "ManagerConfig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "var", "newBroker", "ContainerBrokerFunc", "\n", "switch", "config", ".", "ContainerType", "{", "case", "instance", ".", "KVM", ":", "newBroker", "=", "NewKVMBroker", "\n", "case", "instance", ".", "LXD", ":", "newBroker", "=", "NewLXDBroker", "\n", "default", ":", "return", "nil", ",", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "config", ".", "ContainerType", ")", "\n", "}", "\n\n", "broker", ",", "err", ":=", "newBroker", "(", "prepareHost", "(", "config", ")", ",", "config", ".", "APICaller", ",", "manager", ",", "config", ".", "AgentConfig", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "config", ".", "ContainerType", ")", "\n", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "broker", ",", "nil", "\n", "}" ]
// New creates a new InstanceBroker from the Config
[ "New", "creates", "a", "new", "InstanceBroker", "from", "the", "Config" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/broker/instance_broker.go#L80-L107
155,239
juju/juju
container/broker/instance_broker.go
ConfigureAvailabilityZone
func ConfigureAvailabilityZone(managerConfig container.ManagerConfig, machineZone AvailabilityZoner) (container.ManagerConfig, error) { availabilityZone, err := machineZone.AvailabilityZone() if err != nil { return nil, errors.Trace(err) } managerConfig[container.ConfigAvailabilityZone] = availabilityZone return managerConfig, nil }
go
func ConfigureAvailabilityZone(managerConfig container.ManagerConfig, machineZone AvailabilityZoner) (container.ManagerConfig, error) { availabilityZone, err := machineZone.AvailabilityZone() if err != nil { return nil, errors.Trace(err) } managerConfig[container.ConfigAvailabilityZone] = availabilityZone return managerConfig, nil }
[ "func", "ConfigureAvailabilityZone", "(", "managerConfig", "container", ".", "ManagerConfig", ",", "machineZone", "AvailabilityZoner", ")", "(", "container", ".", "ManagerConfig", ",", "error", ")", "{", "availabilityZone", ",", "err", ":=", "machineZone", ".", "AvailabilityZone", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "managerConfig", "[", "container", ".", "ConfigAvailabilityZone", "]", "=", "availabilityZone", "\n\n", "return", "managerConfig", ",", "nil", "\n", "}" ]
// ConfigureAvailabilityZone reads the availability zone from the machine and // adds the resulting information to the the manager config.
[ "ConfigureAvailabilityZone", "reads", "the", "availability", "zone", "from", "the", "machine", "and", "adds", "the", "resulting", "information", "to", "the", "the", "manager", "config", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/container/broker/instance_broker.go#L157-L165
155,240
juju/juju
cmd/juju/action/common.go
getActionTagsByPrefix
func getActionTagsByPrefix(api APIClient, prefix string) ([]names.ActionTag, error) { results := []names.ActionTag{} tags, err := api.FindActionTagsByPrefix(params.FindTags{Prefixes: []string{prefix}}) if err != nil { return results, err } matches, ok := tags.Matches[prefix] if !ok || len(matches) < 1 { return results, nil } results, rejects := getActionTags(matches) if len(rejects) > 0 { logger.Errorf("FindActionTagsByPrefix for prefix %q found invalid tags %v", prefix, rejects) } return results, nil }
go
func getActionTagsByPrefix(api APIClient, prefix string) ([]names.ActionTag, error) { results := []names.ActionTag{} tags, err := api.FindActionTagsByPrefix(params.FindTags{Prefixes: []string{prefix}}) if err != nil { return results, err } matches, ok := tags.Matches[prefix] if !ok || len(matches) < 1 { return results, nil } results, rejects := getActionTags(matches) if len(rejects) > 0 { logger.Errorf("FindActionTagsByPrefix for prefix %q found invalid tags %v", prefix, rejects) } return results, nil }
[ "func", "getActionTagsByPrefix", "(", "api", "APIClient", ",", "prefix", "string", ")", "(", "[", "]", "names", ".", "ActionTag", ",", "error", ")", "{", "results", ":=", "[", "]", "names", ".", "ActionTag", "{", "}", "\n\n", "tags", ",", "err", ":=", "api", ".", "FindActionTagsByPrefix", "(", "params", ".", "FindTags", "{", "Prefixes", ":", "[", "]", "string", "{", "prefix", "}", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "results", ",", "err", "\n", "}", "\n\n", "matches", ",", "ok", ":=", "tags", ".", "Matches", "[", "prefix", "]", "\n", "if", "!", "ok", "||", "len", "(", "matches", ")", "<", "1", "{", "return", "results", ",", "nil", "\n", "}", "\n\n", "results", ",", "rejects", ":=", "getActionTags", "(", "matches", ")", "\n", "if", "len", "(", "rejects", ")", ">", "0", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "prefix", ",", "rejects", ")", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// getActionTagByPrefix uses the APIClient to get all ActionTags matching a prefix.
[ "getActionTagByPrefix", "uses", "the", "APIClient", "to", "get", "all", "ActionTags", "matching", "a", "prefix", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/action/common.go#L17-L35
155,241
juju/juju
cmd/juju/action/common.go
getActionTagByPrefix
func getActionTagByPrefix(api APIClient, prefix string) (names.ActionTag, error) { tag := names.ActionTag{} actiontags, err := getActionTagsByPrefix(api, prefix) if err != nil { return tag, err } if len(actiontags) < 1 { return tag, errors.Errorf("actions for identifier %q not found", prefix) } if len(actiontags) > 1 { return tag, errors.Errorf("identifier %q matched multiple actions %v", prefix, actiontags) } return actiontags[0], nil }
go
func getActionTagByPrefix(api APIClient, prefix string) (names.ActionTag, error) { tag := names.ActionTag{} actiontags, err := getActionTagsByPrefix(api, prefix) if err != nil { return tag, err } if len(actiontags) < 1 { return tag, errors.Errorf("actions for identifier %q not found", prefix) } if len(actiontags) > 1 { return tag, errors.Errorf("identifier %q matched multiple actions %v", prefix, actiontags) } return actiontags[0], nil }
[ "func", "getActionTagByPrefix", "(", "api", "APIClient", ",", "prefix", "string", ")", "(", "names", ".", "ActionTag", ",", "error", ")", "{", "tag", ":=", "names", ".", "ActionTag", "{", "}", "\n", "actiontags", ",", "err", ":=", "getActionTagsByPrefix", "(", "api", ",", "prefix", ")", "\n", "if", "err", "!=", "nil", "{", "return", "tag", ",", "err", "\n", "}", "\n\n", "if", "len", "(", "actiontags", ")", "<", "1", "{", "return", "tag", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "prefix", ")", "\n", "}", "\n\n", "if", "len", "(", "actiontags", ")", ">", "1", "{", "return", "tag", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "prefix", ",", "actiontags", ")", "\n", "}", "\n\n", "return", "actiontags", "[", "0", "]", ",", "nil", "\n", "}" ]
// getActionTagByPrefix uses the APIClient to get an ActionTag from a prefix.
[ "getActionTagByPrefix", "uses", "the", "APIClient", "to", "get", "an", "ActionTag", "from", "a", "prefix", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/action/common.go#L38-L54
155,242
juju/juju
cmd/juju/action/common.go
getActionTags
func getActionTags(entities []params.Entity) (good []names.ActionTag, bad []string) { for _, entity := range entities { if tag, err := entityToActionTag(entity); err != nil { bad = append(bad, entity.Tag) } else { good = append(good, tag) } } return }
go
func getActionTags(entities []params.Entity) (good []names.ActionTag, bad []string) { for _, entity := range entities { if tag, err := entityToActionTag(entity); err != nil { bad = append(bad, entity.Tag) } else { good = append(good, tag) } } return }
[ "func", "getActionTags", "(", "entities", "[", "]", "params", ".", "Entity", ")", "(", "good", "[", "]", "names", ".", "ActionTag", ",", "bad", "[", "]", "string", ")", "{", "for", "_", ",", "entity", ":=", "range", "entities", "{", "if", "tag", ",", "err", ":=", "entityToActionTag", "(", "entity", ")", ";", "err", "!=", "nil", "{", "bad", "=", "append", "(", "bad", ",", "entity", ".", "Tag", ")", "\n", "}", "else", "{", "good", "=", "append", "(", "good", ",", "tag", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// getActionTags converts a slice of params.Entity to a slice of names.ActionTag, and // also populates a slice of strings for the params.Entity.Tag that are not a valid // names.ActionTag.
[ "getActionTags", "converts", "a", "slice", "of", "params", ".", "Entity", "to", "a", "slice", "of", "names", ".", "ActionTag", "and", "also", "populates", "a", "slice", "of", "strings", "for", "the", "params", ".", "Entity", ".", "Tag", "that", "are", "not", "a", "valid", "names", ".", "ActionTag", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/action/common.go#L59-L68
155,243
juju/juju
cmd/juju/action/common.go
entityToActionTag
func entityToActionTag(entity params.Entity) (names.ActionTag, error) { return names.ParseActionTag(entity.Tag) }
go
func entityToActionTag(entity params.Entity) (names.ActionTag, error) { return names.ParseActionTag(entity.Tag) }
[ "func", "entityToActionTag", "(", "entity", "params", ".", "Entity", ")", "(", "names", ".", "ActionTag", ",", "error", ")", "{", "return", "names", ".", "ParseActionTag", "(", "entity", ".", "Tag", ")", "\n", "}" ]
// entityToActionTag converts the params.Entity type to a names.ActionTag
[ "entityToActionTag", "converts", "the", "params", ".", "Entity", "type", "to", "a", "names", ".", "ActionTag" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/action/common.go#L71-L73
155,244
juju/juju
storage/plans/iscsi/iscsi.go
sessionBase
func (i *iscsiConnectionInfo) sessionBase(deviceName string) (string, error) { lnkPath := filepath.Join(sysfsBlock, deviceName) lnkRealPath, err := os.Readlink(lnkPath) if err != nil { return "", err } fullPath, err := filepath.Abs(filepath.Join(sysfsBlock, lnkRealPath)) if err != nil { return "", err } segments := strings.SplitN(fullPath[1:], "/", -1) if len(segments) != 9 { // iscsi block devices look like: // /sys/devices/platform/host2/session1/target2:0:0/2:0:0:1/block/sda return "", errors.Errorf("not an iscsi device") } if _, err := os.Stat(filepath.Join(sysfsiSCSIHost, segments[3])); err != nil { return "", errors.Errorf("not an iscsi device") } sessionPath := filepath.Join(sysfsiSCSISession, segments[4]) if _, err := os.Stat(sessionPath); err != nil { return "", errors.Errorf("session does not exits") } return sessionPath, nil }
go
func (i *iscsiConnectionInfo) sessionBase(deviceName string) (string, error) { lnkPath := filepath.Join(sysfsBlock, deviceName) lnkRealPath, err := os.Readlink(lnkPath) if err != nil { return "", err } fullPath, err := filepath.Abs(filepath.Join(sysfsBlock, lnkRealPath)) if err != nil { return "", err } segments := strings.SplitN(fullPath[1:], "/", -1) if len(segments) != 9 { // iscsi block devices look like: // /sys/devices/platform/host2/session1/target2:0:0/2:0:0:1/block/sda return "", errors.Errorf("not an iscsi device") } if _, err := os.Stat(filepath.Join(sysfsiSCSIHost, segments[3])); err != nil { return "", errors.Errorf("not an iscsi device") } sessionPath := filepath.Join(sysfsiSCSISession, segments[4]) if _, err := os.Stat(sessionPath); err != nil { return "", errors.Errorf("session does not exits") } return sessionPath, nil }
[ "func", "(", "i", "*", "iscsiConnectionInfo", ")", "sessionBase", "(", "deviceName", "string", ")", "(", "string", ",", "error", ")", "{", "lnkPath", ":=", "filepath", ".", "Join", "(", "sysfsBlock", ",", "deviceName", ")", "\n", "lnkRealPath", ",", "err", ":=", "os", ".", "Readlink", "(", "lnkPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "fullPath", ",", "err", ":=", "filepath", ".", "Abs", "(", "filepath", ".", "Join", "(", "sysfsBlock", ",", "lnkRealPath", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "segments", ":=", "strings", ".", "SplitN", "(", "fullPath", "[", "1", ":", "]", ",", "\"", "\"", ",", "-", "1", ")", "\n", "if", "len", "(", "segments", ")", "!=", "9", "{", "// iscsi block devices look like:", "// /sys/devices/platform/host2/session1/target2:0:0/2:0:0:1/block/sda", "return", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "filepath", ".", "Join", "(", "sysfsiSCSIHost", ",", "segments", "[", "3", "]", ")", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "sessionPath", ":=", "filepath", ".", "Join", "(", "sysfsiSCSISession", ",", "segments", "[", "4", "]", ")", "\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "sessionPath", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "sessionPath", ",", "nil", "\n", "}" ]
// sessionBase returns the iSCSI sysfs session folder
[ "sessionBase", "returns", "the", "iSCSI", "sysfs", "session", "folder" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/storage/plans/iscsi/iscsi.go#L167-L191
155,245
juju/juju
storage/plans/iscsi/iscsi.go
addTarget
func (i *iscsiConnectionInfo) addTarget() error { newNodeParams := []string{ "iscsiadm", "-m", "node", "-o", "new", "-T", i.iqn, "-p", i.portal()} result, err := runCommand(newNodeParams) if err != nil { return errors.Annotatef(err, "iscsiadm failed to add new node: %s", result.Stderr) } startupParams := []string{ "iscsiadm", "-m", "node", "-o", "update", "-T", i.iqn, "-n", "node.startup", "-v", "automatic"} result, err = runCommand(startupParams) if err != nil { return errors.Annotatef(err, "iscsiadm failed to set startup mode: %s", result.Stderr) } if i.chapSecret != "" && i.chapUser != "" { authModeParams := []string{ "iscsiadm", "-m", "node", "-o", "update", "-T", i.iqn, "-p", i.portal(), "-n", "node.session.auth.authmethod", "-v", "CHAP", } result, err = runCommand(authModeParams) if err != nil { return errors.Annotatef(err, "iscsiadm failed to set auth method: %s", result.Stderr) } usernameParams := []string{ "iscsiadm", "-m", "node", "-o", "update", "-T", i.iqn, "-p", i.portal(), "-n", "node.session.auth.username", "-v", i.chapUser, } result, err = runCommand(usernameParams) if err != nil { return errors.Annotatef(err, "iscsiadm failed to set auth username: %s", result.Stderr) } passwordParams := []string{ "iscsiadm", "-m", "node", "-o", "update", "-T", i.iqn, "-p", i.portal(), "-n", "node.session.auth.password", "-v", i.chapSecret, } result, err = runCommand(passwordParams) if err != nil { return errors.Annotatef(err, "iscsiadm failed to set auth password: %s", result.Stderr) } } return nil }
go
func (i *iscsiConnectionInfo) addTarget() error { newNodeParams := []string{ "iscsiadm", "-m", "node", "-o", "new", "-T", i.iqn, "-p", i.portal()} result, err := runCommand(newNodeParams) if err != nil { return errors.Annotatef(err, "iscsiadm failed to add new node: %s", result.Stderr) } startupParams := []string{ "iscsiadm", "-m", "node", "-o", "update", "-T", i.iqn, "-n", "node.startup", "-v", "automatic"} result, err = runCommand(startupParams) if err != nil { return errors.Annotatef(err, "iscsiadm failed to set startup mode: %s", result.Stderr) } if i.chapSecret != "" && i.chapUser != "" { authModeParams := []string{ "iscsiadm", "-m", "node", "-o", "update", "-T", i.iqn, "-p", i.portal(), "-n", "node.session.auth.authmethod", "-v", "CHAP", } result, err = runCommand(authModeParams) if err != nil { return errors.Annotatef(err, "iscsiadm failed to set auth method: %s", result.Stderr) } usernameParams := []string{ "iscsiadm", "-m", "node", "-o", "update", "-T", i.iqn, "-p", i.portal(), "-n", "node.session.auth.username", "-v", i.chapUser, } result, err = runCommand(usernameParams) if err != nil { return errors.Annotatef(err, "iscsiadm failed to set auth username: %s", result.Stderr) } passwordParams := []string{ "iscsiadm", "-m", "node", "-o", "update", "-T", i.iqn, "-p", i.portal(), "-n", "node.session.auth.password", "-v", i.chapSecret, } result, err = runCommand(passwordParams) if err != nil { return errors.Annotatef(err, "iscsiadm failed to set auth password: %s", result.Stderr) } } return nil }
[ "func", "(", "i", "*", "iscsiConnectionInfo", ")", "addTarget", "(", ")", "error", "{", "newNodeParams", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "i", ".", "iqn", ",", "\"", "\"", ",", "i", ".", "portal", "(", ")", "}", "\n", "result", ",", "err", ":=", "runCommand", "(", "newNodeParams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "result", ".", "Stderr", ")", "\n", "}", "\n\n", "startupParams", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "i", ".", "iqn", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", "\n", "result", ",", "err", "=", "runCommand", "(", "startupParams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "result", ".", "Stderr", ")", "\n", "}", "\n\n", "if", "i", ".", "chapSecret", "!=", "\"", "\"", "&&", "i", ".", "chapUser", "!=", "\"", "\"", "{", "authModeParams", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "i", ".", "iqn", ",", "\"", "\"", ",", "i", ".", "portal", "(", ")", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "}", "\n", "result", ",", "err", "=", "runCommand", "(", "authModeParams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "result", ".", "Stderr", ")", "\n", "}", "\n", "usernameParams", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "i", ".", "iqn", ",", "\"", "\"", ",", "i", ".", "portal", "(", ")", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "i", ".", "chapUser", ",", "}", "\n", "result", ",", "err", "=", "runCommand", "(", "usernameParams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "result", ".", "Stderr", ")", "\n", "}", "\n", "passwordParams", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "i", ".", "iqn", ",", "\"", "\"", ",", "i", ".", "portal", "(", ")", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "i", ".", "chapSecret", ",", "}", "\n", "result", ",", "err", "=", "runCommand", "(", "passwordParams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "result", ".", "Stderr", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// addTarget adds the iscsi target config
[ "addTarget", "adds", "the", "iscsi", "target", "config" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/storage/plans/iscsi/iscsi.go#L239-L300
155,246
juju/juju
worker/storageprovisioner/schedule.go
scheduleOperations
func scheduleOperations(ctx *context, ops ...scheduleOp) { if len(ops) == 0 { return } now := ctx.config.Clock.Now() for _, op := range ops { k := op.key() d := op.delay() ctx.schedule.Add(k, op, now.Add(d)) } }
go
func scheduleOperations(ctx *context, ops ...scheduleOp) { if len(ops) == 0 { return } now := ctx.config.Clock.Now() for _, op := range ops { k := op.key() d := op.delay() ctx.schedule.Add(k, op, now.Add(d)) } }
[ "func", "scheduleOperations", "(", "ctx", "*", "context", ",", "ops", "...", "scheduleOp", ")", "{", "if", "len", "(", "ops", ")", "==", "0", "{", "return", "\n", "}", "\n", "now", ":=", "ctx", ".", "config", ".", "Clock", ".", "Now", "(", ")", "\n", "for", "_", ",", "op", ":=", "range", "ops", "{", "k", ":=", "op", ".", "key", "(", ")", "\n", "d", ":=", "op", ".", "delay", "(", ")", "\n", "ctx", ".", "schedule", ".", "Add", "(", "k", ",", "op", ",", "now", ".", "Add", "(", "d", ")", ")", "\n", "}", "\n", "}" ]
// scheduleOperations schedules the given operations // by calculating the current time once, and then // adding each operation's delay to that time. By // calculating the current time once, we guarantee // that operations with the same delay will be // batched together.
[ "scheduleOperations", "schedules", "the", "given", "operations", "by", "calculating", "the", "current", "time", "once", "and", "then", "adding", "each", "operation", "s", "delay", "to", "that", "time", ".", "By", "calculating", "the", "current", "time", "once", "we", "guarantee", "that", "operations", "with", "the", "same", "delay", "will", "be", "batched", "together", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/storageprovisioner/schedule.go#L24-L34
155,247
juju/juju
provider/azure/credentials.go
DetectCredentials
func (c environProviderCredentials) DetectCredentials() (*cloud.CloudCredential, error) { // Attempt to get accounts from az. accounts, err := c.azureCLI.ListAccounts() if err != nil { logger.Debugf("error getting accounts from az: %s", err) return nil, errors.NotFoundf("credentials") } if len(accounts) < 1 { return nil, errors.NotFoundf("credentials") } clouds, err := c.azureCLI.ListClouds() if err != nil { logger.Debugf("error getting clouds from az: %s", err) return nil, errors.NotFoundf("credentials") } cloudMap := make(map[string]azurecli.Cloud, len(clouds)) for _, cloud := range clouds { cloudMap[cloud.Name] = cloud } var defaultCredential string authCredentials := make(map[string]cloud.Credential) for i, acc := range accounts { cloudInfo, ok := cloudMap[acc.CloudName] if !ok { continue } cred, err := c.accountCredential(acc, cloudInfo) if err != nil { logger.Debugf("cannot get credential for %s: %s", acc.Name, err) if i == 0 { // Assume that if this fails the first // time then it will always fail and // don't attempt to create any further // credentials. return nil, errors.NotFoundf("credentials") } continue } cred.Label = fmt.Sprintf("%s subscription %s", cloudInfo.Name, acc.Name) authCredentials[acc.Name] = cred if acc.IsDefault { defaultCredential = acc.Name } } if len(authCredentials) < 1 { return nil, errors.NotFoundf("credentials") } return &cloud.CloudCredential{ DefaultCredential: defaultCredential, AuthCredentials: authCredentials, }, nil }
go
func (c environProviderCredentials) DetectCredentials() (*cloud.CloudCredential, error) { // Attempt to get accounts from az. accounts, err := c.azureCLI.ListAccounts() if err != nil { logger.Debugf("error getting accounts from az: %s", err) return nil, errors.NotFoundf("credentials") } if len(accounts) < 1 { return nil, errors.NotFoundf("credentials") } clouds, err := c.azureCLI.ListClouds() if err != nil { logger.Debugf("error getting clouds from az: %s", err) return nil, errors.NotFoundf("credentials") } cloudMap := make(map[string]azurecli.Cloud, len(clouds)) for _, cloud := range clouds { cloudMap[cloud.Name] = cloud } var defaultCredential string authCredentials := make(map[string]cloud.Credential) for i, acc := range accounts { cloudInfo, ok := cloudMap[acc.CloudName] if !ok { continue } cred, err := c.accountCredential(acc, cloudInfo) if err != nil { logger.Debugf("cannot get credential for %s: %s", acc.Name, err) if i == 0 { // Assume that if this fails the first // time then it will always fail and // don't attempt to create any further // credentials. return nil, errors.NotFoundf("credentials") } continue } cred.Label = fmt.Sprintf("%s subscription %s", cloudInfo.Name, acc.Name) authCredentials[acc.Name] = cred if acc.IsDefault { defaultCredential = acc.Name } } if len(authCredentials) < 1 { return nil, errors.NotFoundf("credentials") } return &cloud.CloudCredential{ DefaultCredential: defaultCredential, AuthCredentials: authCredentials, }, nil }
[ "func", "(", "c", "environProviderCredentials", ")", "DetectCredentials", "(", ")", "(", "*", "cloud", ".", "CloudCredential", ",", "error", ")", "{", "// Attempt to get accounts from az.", "accounts", ",", "err", ":=", "c", ".", "azureCLI", ".", "ListAccounts", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "accounts", ")", "<", "1", "{", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ")", "\n", "}", "\n", "clouds", ",", "err", ":=", "c", ".", "azureCLI", ".", "ListClouds", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ")", "\n", "}", "\n", "cloudMap", ":=", "make", "(", "map", "[", "string", "]", "azurecli", ".", "Cloud", ",", "len", "(", "clouds", ")", ")", "\n", "for", "_", ",", "cloud", ":=", "range", "clouds", "{", "cloudMap", "[", "cloud", ".", "Name", "]", "=", "cloud", "\n", "}", "\n", "var", "defaultCredential", "string", "\n", "authCredentials", ":=", "make", "(", "map", "[", "string", "]", "cloud", ".", "Credential", ")", "\n", "for", "i", ",", "acc", ":=", "range", "accounts", "{", "cloudInfo", ",", "ok", ":=", "cloudMap", "[", "acc", ".", "CloudName", "]", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "cred", ",", "err", ":=", "c", ".", "accountCredential", "(", "acc", ",", "cloudInfo", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "acc", ".", "Name", ",", "err", ")", "\n", "if", "i", "==", "0", "{", "// Assume that if this fails the first", "// time then it will always fail and", "// don't attempt to create any further", "// credentials.", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ")", "\n", "}", "\n", "continue", "\n", "}", "\n", "cred", ".", "Label", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cloudInfo", ".", "Name", ",", "acc", ".", "Name", ")", "\n", "authCredentials", "[", "acc", ".", "Name", "]", "=", "cred", "\n", "if", "acc", ".", "IsDefault", "{", "defaultCredential", "=", "acc", ".", "Name", "\n", "}", "\n", "}", "\n", "if", "len", "(", "authCredentials", ")", "<", "1", "{", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "&", "cloud", ".", "CloudCredential", "{", "DefaultCredential", ":", "defaultCredential", ",", "AuthCredentials", ":", "authCredentials", ",", "}", ",", "nil", "\n", "}" ]
// DetectCredentials is part of the environs.ProviderCredentials // interface. It attempts to detect subscription IDs from accounts // configured in the Azure CLI.
[ "DetectCredentials", "is", "part", "of", "the", "environs", ".", "ProviderCredentials", "interface", ".", "It", "attempts", "to", "detect", "subscription", "IDs", "from", "accounts", "configured", "in", "the", "Azure", "CLI", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/azure/credentials.go#L98-L149
155,248
juju/juju
cmd/jujud/agent/machine.go
NewMachineAgentCmd
func NewMachineAgentCmd( ctx *cmd.Context, machineAgentFactory machineAgentFactoryFnType, agentInitializer AgentInitializer, configFetcher AgentConfigWriter, ) cmd.Command { return &machineAgentCmd{ ctx: ctx, machineAgentFactory: machineAgentFactory, agentInitializer: agentInitializer, currentConfig: configFetcher, } }
go
func NewMachineAgentCmd( ctx *cmd.Context, machineAgentFactory machineAgentFactoryFnType, agentInitializer AgentInitializer, configFetcher AgentConfigWriter, ) cmd.Command { return &machineAgentCmd{ ctx: ctx, machineAgentFactory: machineAgentFactory, agentInitializer: agentInitializer, currentConfig: configFetcher, } }
[ "func", "NewMachineAgentCmd", "(", "ctx", "*", "cmd", ".", "Context", ",", "machineAgentFactory", "machineAgentFactoryFnType", ",", "agentInitializer", "AgentInitializer", ",", "configFetcher", "AgentConfigWriter", ",", ")", "cmd", ".", "Command", "{", "return", "&", "machineAgentCmd", "{", "ctx", ":", "ctx", ",", "machineAgentFactory", ":", "machineAgentFactory", ",", "agentInitializer", ":", "agentInitializer", ",", "currentConfig", ":", "configFetcher", ",", "}", "\n", "}" ]
// NewMachineAgentCmd creates a Command which handles parsing // command-line arguments and instantiating and running a // MachineAgent.
[ "NewMachineAgentCmd", "creates", "a", "Command", "which", "handles", "parsing", "command", "-", "line", "arguments", "and", "instantiating", "and", "running", "a", "MachineAgent", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/machine.go#L157-L169
155,249
juju/juju
cmd/jujud/agent/machine.go
Init
func (a *machineAgentCmd) Init(args []string) error { if !names.IsValidMachine(a.machineId) { return errors.Errorf("--machine-id option must be set, and expects a non-negative integer") } if err := a.agentInitializer.CheckArgs(args); err != nil { return err } // Due to changes in the logging, and needing to care about old // models that have been upgraded, we need to explicitly remove the // file writer if one has been added, otherwise we will get duplicate // lines of all logging in the log file. loggo.RemoveWriter("logfile") if a.logToStdErr { return nil } if err := a.currentConfig.ReadConfig(a.tag().String()); err != nil { return errors.Errorf("cannot read agent configuration: %v", err) } config := a.currentConfig.CurrentConfig() // the context's stderr is set as the loggo writer in github.com/juju/cmd/logging.go a.ctx.Stderr = &lumberjack.Logger{ Filename: agent.LogFilename(config), MaxSize: 300, // megabytes MaxBackups: 2, Compress: true, } return nil }
go
func (a *machineAgentCmd) Init(args []string) error { if !names.IsValidMachine(a.machineId) { return errors.Errorf("--machine-id option must be set, and expects a non-negative integer") } if err := a.agentInitializer.CheckArgs(args); err != nil { return err } // Due to changes in the logging, and needing to care about old // models that have been upgraded, we need to explicitly remove the // file writer if one has been added, otherwise we will get duplicate // lines of all logging in the log file. loggo.RemoveWriter("logfile") if a.logToStdErr { return nil } if err := a.currentConfig.ReadConfig(a.tag().String()); err != nil { return errors.Errorf("cannot read agent configuration: %v", err) } config := a.currentConfig.CurrentConfig() // the context's stderr is set as the loggo writer in github.com/juju/cmd/logging.go a.ctx.Stderr = &lumberjack.Logger{ Filename: agent.LogFilename(config), MaxSize: 300, // megabytes MaxBackups: 2, Compress: true, } return nil }
[ "func", "(", "a", "*", "machineAgentCmd", ")", "Init", "(", "args", "[", "]", "string", ")", "error", "{", "if", "!", "names", ".", "IsValidMachine", "(", "a", ".", "machineId", ")", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "a", ".", "agentInitializer", ".", "CheckArgs", "(", "args", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Due to changes in the logging, and needing to care about old", "// models that have been upgraded, we need to explicitly remove the", "// file writer if one has been added, otherwise we will get duplicate", "// lines of all logging in the log file.", "loggo", ".", "RemoveWriter", "(", "\"", "\"", ")", "\n\n", "if", "a", ".", "logToStdErr", "{", "return", "nil", "\n", "}", "\n\n", "if", "err", ":=", "a", ".", "currentConfig", ".", "ReadConfig", "(", "a", ".", "tag", "(", ")", ".", "String", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "config", ":=", "a", ".", "currentConfig", ".", "CurrentConfig", "(", ")", "\n", "// the context's stderr is set as the loggo writer in github.com/juju/cmd/logging.go", "a", ".", "ctx", ".", "Stderr", "=", "&", "lumberjack", ".", "Logger", "{", "Filename", ":", "agent", ".", "LogFilename", "(", "config", ")", ",", "MaxSize", ":", "300", ",", "// megabytes", "MaxBackups", ":", "2", ",", "Compress", ":", "true", ",", "}", "\n", "return", "nil", "\n", "}" ]
// Init is called by the cmd system to initialize the structure for // running.
[ "Init", "is", "called", "by", "the", "cmd", "system", "to", "initialize", "the", "structure", "for", "running", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/machine.go#L189-L220
155,250
juju/juju
cmd/jujud/agent/machine.go
Run
func (a *machineAgentCmd) Run(c *cmd.Context) error { config := a.currentConfig.CurrentConfig() isCaasMachineAgent := config.Value(agent.ProviderType) == k8sprovider.CAASProviderType machineAgent, err := a.machineAgentFactory(a.machineId, isCaasMachineAgent) if err != nil { return errors.Trace(err) } return machineAgent.Run(c) }
go
func (a *machineAgentCmd) Run(c *cmd.Context) error { config := a.currentConfig.CurrentConfig() isCaasMachineAgent := config.Value(agent.ProviderType) == k8sprovider.CAASProviderType machineAgent, err := a.machineAgentFactory(a.machineId, isCaasMachineAgent) if err != nil { return errors.Trace(err) } return machineAgent.Run(c) }
[ "func", "(", "a", "*", "machineAgentCmd", ")", "Run", "(", "c", "*", "cmd", ".", "Context", ")", "error", "{", "config", ":=", "a", ".", "currentConfig", ".", "CurrentConfig", "(", ")", "\n", "isCaasMachineAgent", ":=", "config", ".", "Value", "(", "agent", ".", "ProviderType", ")", "==", "k8sprovider", ".", "CAASProviderType", "\n", "machineAgent", ",", "err", ":=", "a", ".", "machineAgentFactory", "(", "a", ".", "machineId", ",", "isCaasMachineAgent", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "machineAgent", ".", "Run", "(", "c", ")", "\n", "}" ]
// Run instantiates a MachineAgent and runs it.
[ "Run", "instantiates", "a", "MachineAgent", "and", "runs", "it", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/machine.go#L227-L235
155,251
juju/juju
cmd/jujud/agent/machine.go
SetFlags
func (a *machineAgentCmd) SetFlags(f *gnuflag.FlagSet) { a.agentInitializer.AddFlags(f) f.StringVar(&a.machineId, "machine-id", "", "id of the machine to run") }
go
func (a *machineAgentCmd) SetFlags(f *gnuflag.FlagSet) { a.agentInitializer.AddFlags(f) f.StringVar(&a.machineId, "machine-id", "", "id of the machine to run") }
[ "func", "(", "a", "*", "machineAgentCmd", ")", "SetFlags", "(", "f", "*", "gnuflag", ".", "FlagSet", ")", "{", "a", ".", "agentInitializer", ".", "AddFlags", "(", "f", ")", "\n", "f", ".", "StringVar", "(", "&", "a", ".", "machineId", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}" ]
// SetFlags adds the requisite flags to run this command.
[ "SetFlags", "adds", "the", "requisite", "flags", "to", "run", "this", "command", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/machine.go#L238-L241
155,252
juju/juju
cmd/jujud/agent/machine.go
MachineAgentFactoryFn
func MachineAgentFactoryFn( agentConfWriter AgentConfigWriter, bufferedLogger *logsender.BufferedLogWriter, newIntrospectionSocketName func(names.Tag) string, preUpgradeSteps upgrades.PreUpgradeStepsFunc, rootDir string, ) machineAgentFactoryFnType { return func(machineId string, isCaasMachineAgent bool) (*MachineAgent, error) { return NewMachineAgent( machineId, agentConfWriter, bufferedLogger, worker.NewRunner(worker.RunnerParams{ IsFatal: cmdutil.IsFatal, MoreImportant: cmdutil.MoreImportant, RestartDelay: jworker.RestartDelay, }), looputil.NewLoopDeviceManager(), newIntrospectionSocketName, preUpgradeSteps, rootDir, isCaasMachineAgent, ) } }
go
func MachineAgentFactoryFn( agentConfWriter AgentConfigWriter, bufferedLogger *logsender.BufferedLogWriter, newIntrospectionSocketName func(names.Tag) string, preUpgradeSteps upgrades.PreUpgradeStepsFunc, rootDir string, ) machineAgentFactoryFnType { return func(machineId string, isCaasMachineAgent bool) (*MachineAgent, error) { return NewMachineAgent( machineId, agentConfWriter, bufferedLogger, worker.NewRunner(worker.RunnerParams{ IsFatal: cmdutil.IsFatal, MoreImportant: cmdutil.MoreImportant, RestartDelay: jworker.RestartDelay, }), looputil.NewLoopDeviceManager(), newIntrospectionSocketName, preUpgradeSteps, rootDir, isCaasMachineAgent, ) } }
[ "func", "MachineAgentFactoryFn", "(", "agentConfWriter", "AgentConfigWriter", ",", "bufferedLogger", "*", "logsender", ".", "BufferedLogWriter", ",", "newIntrospectionSocketName", "func", "(", "names", ".", "Tag", ")", "string", ",", "preUpgradeSteps", "upgrades", ".", "PreUpgradeStepsFunc", ",", "rootDir", "string", ",", ")", "machineAgentFactoryFnType", "{", "return", "func", "(", "machineId", "string", ",", "isCaasMachineAgent", "bool", ")", "(", "*", "MachineAgent", ",", "error", ")", "{", "return", "NewMachineAgent", "(", "machineId", ",", "agentConfWriter", ",", "bufferedLogger", ",", "worker", ".", "NewRunner", "(", "worker", ".", "RunnerParams", "{", "IsFatal", ":", "cmdutil", ".", "IsFatal", ",", "MoreImportant", ":", "cmdutil", ".", "MoreImportant", ",", "RestartDelay", ":", "jworker", ".", "RestartDelay", ",", "}", ")", ",", "looputil", ".", "NewLoopDeviceManager", "(", ")", ",", "newIntrospectionSocketName", ",", "preUpgradeSteps", ",", "rootDir", ",", "isCaasMachineAgent", ",", ")", "\n", "}", "\n", "}" ]
// MachineAgentFactoryFn returns a function which instantiates a // MachineAgent given a machineId.
[ "MachineAgentFactoryFn", "returns", "a", "function", "which", "instantiates", "a", "MachineAgent", "given", "a", "machineId", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/machine.go#L253-L277
155,253
juju/juju
cmd/jujud/agent/machine.go
NewMachineAgent
func NewMachineAgent( machineId string, agentConfWriter AgentConfigWriter, bufferedLogger *logsender.BufferedLogWriter, runner *worker.Runner, loopDeviceManager looputil.LoopDeviceManager, newIntrospectionSocketName func(names.Tag) string, preUpgradeSteps upgrades.PreUpgradeStepsFunc, rootDir string, isCaasMachineAgent bool, ) (*MachineAgent, error) { prometheusRegistry, err := newPrometheusRegistry() if err != nil { return nil, errors.Trace(err) } a := &MachineAgent{ machineId: machineId, AgentConfigWriter: agentConfWriter, configChangedVal: voyeur.NewValue(true), bufferedLogger: bufferedLogger, workersStarted: make(chan struct{}), dead: make(chan struct{}), runner: runner, rootDir: rootDir, initialUpgradeCheckComplete: gate.NewLock(), loopDeviceManager: loopDeviceManager, newIntrospectionSocketName: newIntrospectionSocketName, prometheusRegistry: prometheusRegistry, mongoTxnCollector: mongometrics.NewTxnCollector(), mongoDialCollector: mongometrics.NewDialCollector(), preUpgradeSteps: preUpgradeSteps, isCaasMachineAgent: isCaasMachineAgent, } return a, nil }
go
func NewMachineAgent( machineId string, agentConfWriter AgentConfigWriter, bufferedLogger *logsender.BufferedLogWriter, runner *worker.Runner, loopDeviceManager looputil.LoopDeviceManager, newIntrospectionSocketName func(names.Tag) string, preUpgradeSteps upgrades.PreUpgradeStepsFunc, rootDir string, isCaasMachineAgent bool, ) (*MachineAgent, error) { prometheusRegistry, err := newPrometheusRegistry() if err != nil { return nil, errors.Trace(err) } a := &MachineAgent{ machineId: machineId, AgentConfigWriter: agentConfWriter, configChangedVal: voyeur.NewValue(true), bufferedLogger: bufferedLogger, workersStarted: make(chan struct{}), dead: make(chan struct{}), runner: runner, rootDir: rootDir, initialUpgradeCheckComplete: gate.NewLock(), loopDeviceManager: loopDeviceManager, newIntrospectionSocketName: newIntrospectionSocketName, prometheusRegistry: prometheusRegistry, mongoTxnCollector: mongometrics.NewTxnCollector(), mongoDialCollector: mongometrics.NewDialCollector(), preUpgradeSteps: preUpgradeSteps, isCaasMachineAgent: isCaasMachineAgent, } return a, nil }
[ "func", "NewMachineAgent", "(", "machineId", "string", ",", "agentConfWriter", "AgentConfigWriter", ",", "bufferedLogger", "*", "logsender", ".", "BufferedLogWriter", ",", "runner", "*", "worker", ".", "Runner", ",", "loopDeviceManager", "looputil", ".", "LoopDeviceManager", ",", "newIntrospectionSocketName", "func", "(", "names", ".", "Tag", ")", "string", ",", "preUpgradeSteps", "upgrades", ".", "PreUpgradeStepsFunc", ",", "rootDir", "string", ",", "isCaasMachineAgent", "bool", ",", ")", "(", "*", "MachineAgent", ",", "error", ")", "{", "prometheusRegistry", ",", "err", ":=", "newPrometheusRegistry", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "a", ":=", "&", "MachineAgent", "{", "machineId", ":", "machineId", ",", "AgentConfigWriter", ":", "agentConfWriter", ",", "configChangedVal", ":", "voyeur", ".", "NewValue", "(", "true", ")", ",", "bufferedLogger", ":", "bufferedLogger", ",", "workersStarted", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "dead", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "runner", ":", "runner", ",", "rootDir", ":", "rootDir", ",", "initialUpgradeCheckComplete", ":", "gate", ".", "NewLock", "(", ")", ",", "loopDeviceManager", ":", "loopDeviceManager", ",", "newIntrospectionSocketName", ":", "newIntrospectionSocketName", ",", "prometheusRegistry", ":", "prometheusRegistry", ",", "mongoTxnCollector", ":", "mongometrics", ".", "NewTxnCollector", "(", ")", ",", "mongoDialCollector", ":", "mongometrics", ".", "NewDialCollector", "(", ")", ",", "preUpgradeSteps", ":", "preUpgradeSteps", ",", "isCaasMachineAgent", ":", "isCaasMachineAgent", ",", "}", "\n", "return", "a", ",", "nil", "\n", "}" ]
// NewMachineAgent instantiates a new MachineAgent.
[ "NewMachineAgent", "instantiates", "a", "new", "MachineAgent", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/machine.go#L280-L314
155,254
juju/juju
cmd/jujud/agent/machine.go
upgradeCertificateDNSNames
func upgradeCertificateDNSNames(config agent.ConfigSetter) error { si, ok := config.StateServingInfo() if !ok || si.CAPrivateKey == "" { // No certificate information exists yet, nothing to do. return nil } // Validate the current certificate and private key pair, and then // extract the current DNS names from the certificate. If the // certificate validation fails, or it does not contain the DNS // names we require, we will generate a new one. var dnsNames set.Strings serverCert, _, err := utilscert.ParseCertAndKey(si.Cert, si.PrivateKey) if err != nil { // The certificate is invalid, so create a new one. logger.Infof("parsing certificate/key failed, will generate a new one: %v", err) dnsNames = set.NewStrings() } else { dnsNames = set.NewStrings(serverCert.DNSNames...) } update := false requiredDNSNames := []string{"localhost", "juju-apiserver", "juju-mongodb"} for _, dnsName := range requiredDNSNames { if dnsNames.Contains(dnsName) { continue } dnsNames.Add(dnsName) update = true } if !update { return nil } // Write a new certificate to the mongo pem and agent config files. si.Cert, si.PrivateKey, err = cert.NewDefaultServer(config.CACert(), si.CAPrivateKey, dnsNames.Values()) if err != nil { return err } if err := mongo.UpdateSSLKey(config.DataDir(), si.Cert, si.PrivateKey); err != nil { return err } config.SetStateServingInfo(si) return nil }
go
func upgradeCertificateDNSNames(config agent.ConfigSetter) error { si, ok := config.StateServingInfo() if !ok || si.CAPrivateKey == "" { // No certificate information exists yet, nothing to do. return nil } // Validate the current certificate and private key pair, and then // extract the current DNS names from the certificate. If the // certificate validation fails, or it does not contain the DNS // names we require, we will generate a new one. var dnsNames set.Strings serverCert, _, err := utilscert.ParseCertAndKey(si.Cert, si.PrivateKey) if err != nil { // The certificate is invalid, so create a new one. logger.Infof("parsing certificate/key failed, will generate a new one: %v", err) dnsNames = set.NewStrings() } else { dnsNames = set.NewStrings(serverCert.DNSNames...) } update := false requiredDNSNames := []string{"localhost", "juju-apiserver", "juju-mongodb"} for _, dnsName := range requiredDNSNames { if dnsNames.Contains(dnsName) { continue } dnsNames.Add(dnsName) update = true } if !update { return nil } // Write a new certificate to the mongo pem and agent config files. si.Cert, si.PrivateKey, err = cert.NewDefaultServer(config.CACert(), si.CAPrivateKey, dnsNames.Values()) if err != nil { return err } if err := mongo.UpdateSSLKey(config.DataDir(), si.Cert, si.PrivateKey); err != nil { return err } config.SetStateServingInfo(si) return nil }
[ "func", "upgradeCertificateDNSNames", "(", "config", "agent", ".", "ConfigSetter", ")", "error", "{", "si", ",", "ok", ":=", "config", ".", "StateServingInfo", "(", ")", "\n", "if", "!", "ok", "||", "si", ".", "CAPrivateKey", "==", "\"", "\"", "{", "// No certificate information exists yet, nothing to do.", "return", "nil", "\n", "}", "\n\n", "// Validate the current certificate and private key pair, and then", "// extract the current DNS names from the certificate. If the", "// certificate validation fails, or it does not contain the DNS", "// names we require, we will generate a new one.", "var", "dnsNames", "set", ".", "Strings", "\n", "serverCert", ",", "_", ",", "err", ":=", "utilscert", ".", "ParseCertAndKey", "(", "si", ".", "Cert", ",", "si", ".", "PrivateKey", ")", "\n", "if", "err", "!=", "nil", "{", "// The certificate is invalid, so create a new one.", "logger", ".", "Infof", "(", "\"", "\"", ",", "err", ")", "\n", "dnsNames", "=", "set", ".", "NewStrings", "(", ")", "\n", "}", "else", "{", "dnsNames", "=", "set", ".", "NewStrings", "(", "serverCert", ".", "DNSNames", "...", ")", "\n", "}", "\n\n", "update", ":=", "false", "\n", "requiredDNSNames", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", "\n", "for", "_", ",", "dnsName", ":=", "range", "requiredDNSNames", "{", "if", "dnsNames", ".", "Contains", "(", "dnsName", ")", "{", "continue", "\n", "}", "\n", "dnsNames", ".", "Add", "(", "dnsName", ")", "\n", "update", "=", "true", "\n", "}", "\n", "if", "!", "update", "{", "return", "nil", "\n", "}", "\n\n", "// Write a new certificate to the mongo pem and agent config files.", "si", ".", "Cert", ",", "si", ".", "PrivateKey", ",", "err", "=", "cert", ".", "NewDefaultServer", "(", "config", ".", "CACert", "(", ")", ",", "si", ".", "CAPrivateKey", ",", "dnsNames", ".", "Values", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "mongo", ".", "UpdateSSLKey", "(", "config", ".", "DataDir", "(", ")", ",", "si", ".", "Cert", ",", "si", ".", "PrivateKey", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "config", ".", "SetStateServingInfo", "(", "si", ")", "\n", "return", "nil", "\n", "}" ]
// upgradeCertificateDNSNames ensure that the controller certificate // recorded in the agent config and also mongo server.pem contains the // DNSNames entries required by Juju.
[ "upgradeCertificateDNSNames", "ensure", "that", "the", "controller", "certificate", "recorded", "in", "the", "agent", "config", "and", "also", "mongo", "server", ".", "pem", "contains", "the", "DNSNames", "entries", "required", "by", "Juju", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/machine.go#L400-L444
155,255
juju/juju
cmd/jujud/agent/machine.go
Run
func (a *MachineAgent) Run(*cmd.Context) (err error) { defer a.Done(err) useMultipleCPUs() if err := a.ReadConfig(a.Tag().String()); err != nil { return errors.Errorf("cannot read agent configuration: %v", err) } setupAgentLogging(a.CurrentConfig()) if err := introspection.WriteProfileFunctions(); err != nil { // This isn't fatal, just annoying. logger.Errorf("failed to write profile funcs: %v", err) } // When the API server and peergrouper have manifolds, they can // have dependencies on a central hub worker. a.centralHub = centralhub.New(a.Tag().(names.MachineTag)) // Before doing anything else, we need to make sure the certificate generated for // use by mongo to validate controller connections is correct. This needs to be done // before any possible restart of the mongo service. // See bug http://pad.lv/1434680 if err := a.AgentConfigWriter.ChangeConfig(upgradeCertificateDNSNames); err != nil { return errors.Annotate(err, "error upgrading server certificate") } // moved from NewMachineAgent here because the agent config could not be ready yet there. if err := a.registerPrometheusCollectors(); err != nil { return errors.Trace(err) } agentConfig := a.CurrentConfig() agentName := a.Tag().String() machineLock, err := machinelock.New(machinelock.Config{ AgentName: agentName, Clock: clock.WallClock, Logger: loggo.GetLogger("juju.machinelock"), LogFilename: agent.MachineLockLogFilename(agentConfig), }) // There will only be an error if the required configuration // values are not passed in. if err != nil { return errors.Trace(err) } a.machineLock = machineLock a.upgradeComplete = upgradesteps.NewLock(agentConfig) createEngine := a.makeEngineCreator(agentName, agentConfig.UpgradedToVersion()) charmrepo.CacheDir = filepath.Join(agentConfig.DataDir(), "charmcache") if err := a.createJujudSymlinks(agentConfig.DataDir()); err != nil { return err } a.runner.StartWorker("engine", createEngine) // At this point, all workers will have been configured to start close(a.workersStarted) err = a.runner.Wait() switch errors.Cause(err) { case jworker.ErrTerminateAgent: err = a.uninstallAgent() case jworker.ErrRebootMachine: logger.Infof("Caught reboot error") err = a.executeRebootOrShutdown(params.ShouldReboot) case jworker.ErrShutdownMachine: logger.Infof("Caught shutdown error") err = a.executeRebootOrShutdown(params.ShouldShutdown) } return cmdutil.AgentDone(logger, err) }
go
func (a *MachineAgent) Run(*cmd.Context) (err error) { defer a.Done(err) useMultipleCPUs() if err := a.ReadConfig(a.Tag().String()); err != nil { return errors.Errorf("cannot read agent configuration: %v", err) } setupAgentLogging(a.CurrentConfig()) if err := introspection.WriteProfileFunctions(); err != nil { // This isn't fatal, just annoying. logger.Errorf("failed to write profile funcs: %v", err) } // When the API server and peergrouper have manifolds, they can // have dependencies on a central hub worker. a.centralHub = centralhub.New(a.Tag().(names.MachineTag)) // Before doing anything else, we need to make sure the certificate generated for // use by mongo to validate controller connections is correct. This needs to be done // before any possible restart of the mongo service. // See bug http://pad.lv/1434680 if err := a.AgentConfigWriter.ChangeConfig(upgradeCertificateDNSNames); err != nil { return errors.Annotate(err, "error upgrading server certificate") } // moved from NewMachineAgent here because the agent config could not be ready yet there. if err := a.registerPrometheusCollectors(); err != nil { return errors.Trace(err) } agentConfig := a.CurrentConfig() agentName := a.Tag().String() machineLock, err := machinelock.New(machinelock.Config{ AgentName: agentName, Clock: clock.WallClock, Logger: loggo.GetLogger("juju.machinelock"), LogFilename: agent.MachineLockLogFilename(agentConfig), }) // There will only be an error if the required configuration // values are not passed in. if err != nil { return errors.Trace(err) } a.machineLock = machineLock a.upgradeComplete = upgradesteps.NewLock(agentConfig) createEngine := a.makeEngineCreator(agentName, agentConfig.UpgradedToVersion()) charmrepo.CacheDir = filepath.Join(agentConfig.DataDir(), "charmcache") if err := a.createJujudSymlinks(agentConfig.DataDir()); err != nil { return err } a.runner.StartWorker("engine", createEngine) // At this point, all workers will have been configured to start close(a.workersStarted) err = a.runner.Wait() switch errors.Cause(err) { case jworker.ErrTerminateAgent: err = a.uninstallAgent() case jworker.ErrRebootMachine: logger.Infof("Caught reboot error") err = a.executeRebootOrShutdown(params.ShouldReboot) case jworker.ErrShutdownMachine: logger.Infof("Caught shutdown error") err = a.executeRebootOrShutdown(params.ShouldShutdown) } return cmdutil.AgentDone(logger, err) }
[ "func", "(", "a", "*", "MachineAgent", ")", "Run", "(", "*", "cmd", ".", "Context", ")", "(", "err", "error", ")", "{", "defer", "a", ".", "Done", "(", "err", ")", "\n", "useMultipleCPUs", "(", ")", "\n", "if", "err", ":=", "a", ".", "ReadConfig", "(", "a", ".", "Tag", "(", ")", ".", "String", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "setupAgentLogging", "(", "a", ".", "CurrentConfig", "(", ")", ")", "\n\n", "if", "err", ":=", "introspection", ".", "WriteProfileFunctions", "(", ")", ";", "err", "!=", "nil", "{", "// This isn't fatal, just annoying.", "logger", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// When the API server and peergrouper have manifolds, they can", "// have dependencies on a central hub worker.", "a", ".", "centralHub", "=", "centralhub", ".", "New", "(", "a", ".", "Tag", "(", ")", ".", "(", "names", ".", "MachineTag", ")", ")", "\n\n", "// Before doing anything else, we need to make sure the certificate generated for", "// use by mongo to validate controller connections is correct. This needs to be done", "// before any possible restart of the mongo service.", "// See bug http://pad.lv/1434680", "if", "err", ":=", "a", ".", "AgentConfigWriter", ".", "ChangeConfig", "(", "upgradeCertificateDNSNames", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// moved from NewMachineAgent here because the agent config could not be ready yet there.", "if", "err", ":=", "a", ".", "registerPrometheusCollectors", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "agentConfig", ":=", "a", ".", "CurrentConfig", "(", ")", "\n", "agentName", ":=", "a", ".", "Tag", "(", ")", ".", "String", "(", ")", "\n", "machineLock", ",", "err", ":=", "machinelock", ".", "New", "(", "machinelock", ".", "Config", "{", "AgentName", ":", "agentName", ",", "Clock", ":", "clock", ".", "WallClock", ",", "Logger", ":", "loggo", ".", "GetLogger", "(", "\"", "\"", ")", ",", "LogFilename", ":", "agent", ".", "MachineLockLogFilename", "(", "agentConfig", ")", ",", "}", ")", "\n", "// There will only be an error if the required configuration", "// values are not passed in.", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "a", ".", "machineLock", "=", "machineLock", "\n", "a", ".", "upgradeComplete", "=", "upgradesteps", ".", "NewLock", "(", "agentConfig", ")", "\n\n", "createEngine", ":=", "a", ".", "makeEngineCreator", "(", "agentName", ",", "agentConfig", ".", "UpgradedToVersion", "(", ")", ")", "\n", "charmrepo", ".", "CacheDir", "=", "filepath", ".", "Join", "(", "agentConfig", ".", "DataDir", "(", ")", ",", "\"", "\"", ")", "\n", "if", "err", ":=", "a", ".", "createJujudSymlinks", "(", "agentConfig", ".", "DataDir", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "a", ".", "runner", ".", "StartWorker", "(", "\"", "\"", ",", "createEngine", ")", "\n\n", "// At this point, all workers will have been configured to start", "close", "(", "a", ".", "workersStarted", ")", "\n", "err", "=", "a", ".", "runner", ".", "Wait", "(", ")", "\n", "switch", "errors", ".", "Cause", "(", "err", ")", "{", "case", "jworker", ".", "ErrTerminateAgent", ":", "err", "=", "a", ".", "uninstallAgent", "(", ")", "\n", "case", "jworker", ".", "ErrRebootMachine", ":", "logger", ".", "Infof", "(", "\"", "\"", ")", "\n", "err", "=", "a", ".", "executeRebootOrShutdown", "(", "params", ".", "ShouldReboot", ")", "\n", "case", "jworker", ".", "ErrShutdownMachine", ":", "logger", ".", "Infof", "(", "\"", "\"", ")", "\n", "err", "=", "a", ".", "executeRebootOrShutdown", "(", "params", ".", "ShouldShutdown", ")", "\n", "}", "\n", "return", "cmdutil", ".", "AgentDone", "(", "logger", ",", "err", ")", "\n", "}" ]
// Run runs a machine agent.
[ "Run", "runs", "a", "machine", "agent", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/machine.go#L447-L515
155,256
juju/juju
cmd/jujud/agent/machine.go
Restart
func (a *MachineAgent) Restart() error { // TODO(bootstrap): revisit here to make it only invoked by IAAS. name := a.CurrentConfig().Value(agent.AgentServiceName) return service.Restart(name) }
go
func (a *MachineAgent) Restart() error { // TODO(bootstrap): revisit here to make it only invoked by IAAS. name := a.CurrentConfig().Value(agent.AgentServiceName) return service.Restart(name) }
[ "func", "(", "a", "*", "MachineAgent", ")", "Restart", "(", ")", "error", "{", "// TODO(bootstrap): revisit here to make it only invoked by IAAS.", "name", ":=", "a", ".", "CurrentConfig", "(", ")", ".", "Value", "(", "agent", ".", "AgentServiceName", ")", "\n", "return", "service", ".", "Restart", "(", "name", ")", "\n", "}" ]
// Restart restarts the agent's service.
[ "Restart", "restarts", "the", "agent", "s", "service", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/machine.go#L750-L754
155,257
juju/juju
cmd/jujud/agent/machine.go
setupContainerSupport
func (a *MachineAgent) setupContainerSupport(runner *worker.Runner, st api.Connection, agentConfig agent.Config) error { var supportedContainers []instance.ContainerType supportsContainers := container.ContainersSupported() if supportsContainers { supportedContainers = append(supportedContainers, instance.LXD) } supportsKvm, err := kvm.IsKVMSupported() if err != nil { logger.Warningf("determining kvm support: %v\nno kvm containers possible", err) } if err == nil && supportsKvm { supportedContainers = append(supportedContainers, instance.KVM) } return a.updateSupportedContainers(runner, st, supportedContainers, agentConfig) }
go
func (a *MachineAgent) setupContainerSupport(runner *worker.Runner, st api.Connection, agentConfig agent.Config) error { var supportedContainers []instance.ContainerType supportsContainers := container.ContainersSupported() if supportsContainers { supportedContainers = append(supportedContainers, instance.LXD) } supportsKvm, err := kvm.IsKVMSupported() if err != nil { logger.Warningf("determining kvm support: %v\nno kvm containers possible", err) } if err == nil && supportsKvm { supportedContainers = append(supportedContainers, instance.KVM) } return a.updateSupportedContainers(runner, st, supportedContainers, agentConfig) }
[ "func", "(", "a", "*", "MachineAgent", ")", "setupContainerSupport", "(", "runner", "*", "worker", ".", "Runner", ",", "st", "api", ".", "Connection", ",", "agentConfig", "agent", ".", "Config", ")", "error", "{", "var", "supportedContainers", "[", "]", "instance", ".", "ContainerType", "\n", "supportsContainers", ":=", "container", ".", "ContainersSupported", "(", ")", "\n", "if", "supportsContainers", "{", "supportedContainers", "=", "append", "(", "supportedContainers", ",", "instance", ".", "LXD", ")", "\n", "}", "\n\n", "supportsKvm", ",", "err", ":=", "kvm", ".", "IsKVMSupported", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Warningf", "(", "\"", "\\n", "\"", ",", "err", ")", "\n", "}", "\n", "if", "err", "==", "nil", "&&", "supportsKvm", "{", "supportedContainers", "=", "append", "(", "supportedContainers", ",", "instance", ".", "KVM", ")", "\n", "}", "\n\n", "return", "a", ".", "updateSupportedContainers", "(", "runner", ",", "st", ",", "supportedContainers", ",", "agentConfig", ")", "\n", "}" ]
// setupContainerSupport determines what containers can be run on this machine and // initialises suitable infrastructure to support such containers.
[ "setupContainerSupport", "determines", "what", "containers", "can", "be", "run", "on", "this", "machine", "and", "initialises", "suitable", "infrastructure", "to", "support", "such", "containers", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/machine.go#L820-L836
155,258
juju/juju
cmd/jujud/agent/machine.go
updateSupportedContainers
func (a *MachineAgent) updateSupportedContainers( runner *worker.Runner, st api.Connection, containers []instance.ContainerType, agentConfig agent.Config, ) error { pr := apiprovisioner.NewState(st) tag := agentConfig.Tag().(names.MachineTag) result, err := pr.Machines(tag) if err != nil { return errors.Annotatef(err, "cannot load machine %s from state", tag) } if len(result) != 1 { return errors.Errorf("expected 1 result, got %d", len(result)) } if errors.IsNotFound(result[0].Err) || (result[0].Err == nil && result[0].Machine.Life() == params.Dead) { return jworker.ErrTerminateAgent } machine := result[0].Machine if len(containers) == 0 { if err := machine.SupportsNoContainers(); err != nil { return errors.Annotatef(err, "clearing supported containers for %s", tag) } return nil } if err := machine.SetSupportedContainers(containers...); err != nil { return errors.Annotatef(err, "setting supported containers for %s", tag) } // Start the watcher to fire when a container is first requested on the machine. watcherName := fmt.Sprintf("%s-container-watcher", machine.Id()) credentialAPI, err := workercommon.NewCredentialInvalidatorFacade(st) if err != nil { return errors.Annotatef(err, "cannot get credential invalidator facade") } params := provisioner.ContainerSetupParams{ Runner: runner, WorkerName: watcherName, SupportedContainers: containers, Machine: machine, Provisioner: pr, Config: agentConfig, MachineLock: a.machineLock, CredentialAPI: credentialAPI, } handler := provisioner.NewContainerSetupHandler(params) a.startWorkerAfterUpgrade(runner, watcherName, func() (worker.Worker, error) { w, err := watcher.NewStringsWorker(watcher.StringsConfig{ Handler: handler, }) if err != nil { return nil, errors.Annotatef(err, "cannot start %s worker", watcherName) } return w, nil }) return nil }
go
func (a *MachineAgent) updateSupportedContainers( runner *worker.Runner, st api.Connection, containers []instance.ContainerType, agentConfig agent.Config, ) error { pr := apiprovisioner.NewState(st) tag := agentConfig.Tag().(names.MachineTag) result, err := pr.Machines(tag) if err != nil { return errors.Annotatef(err, "cannot load machine %s from state", tag) } if len(result) != 1 { return errors.Errorf("expected 1 result, got %d", len(result)) } if errors.IsNotFound(result[0].Err) || (result[0].Err == nil && result[0].Machine.Life() == params.Dead) { return jworker.ErrTerminateAgent } machine := result[0].Machine if len(containers) == 0 { if err := machine.SupportsNoContainers(); err != nil { return errors.Annotatef(err, "clearing supported containers for %s", tag) } return nil } if err := machine.SetSupportedContainers(containers...); err != nil { return errors.Annotatef(err, "setting supported containers for %s", tag) } // Start the watcher to fire when a container is first requested on the machine. watcherName := fmt.Sprintf("%s-container-watcher", machine.Id()) credentialAPI, err := workercommon.NewCredentialInvalidatorFacade(st) if err != nil { return errors.Annotatef(err, "cannot get credential invalidator facade") } params := provisioner.ContainerSetupParams{ Runner: runner, WorkerName: watcherName, SupportedContainers: containers, Machine: machine, Provisioner: pr, Config: agentConfig, MachineLock: a.machineLock, CredentialAPI: credentialAPI, } handler := provisioner.NewContainerSetupHandler(params) a.startWorkerAfterUpgrade(runner, watcherName, func() (worker.Worker, error) { w, err := watcher.NewStringsWorker(watcher.StringsConfig{ Handler: handler, }) if err != nil { return nil, errors.Annotatef(err, "cannot start %s worker", watcherName) } return w, nil }) return nil }
[ "func", "(", "a", "*", "MachineAgent", ")", "updateSupportedContainers", "(", "runner", "*", "worker", ".", "Runner", ",", "st", "api", ".", "Connection", ",", "containers", "[", "]", "instance", ".", "ContainerType", ",", "agentConfig", "agent", ".", "Config", ",", ")", "error", "{", "pr", ":=", "apiprovisioner", ".", "NewState", "(", "st", ")", "\n", "tag", ":=", "agentConfig", ".", "Tag", "(", ")", ".", "(", "names", ".", "MachineTag", ")", "\n", "result", ",", "err", ":=", "pr", ".", "Machines", "(", "tag", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "tag", ")", "\n", "}", "\n", "if", "len", "(", "result", ")", "!=", "1", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "result", ")", ")", "\n", "}", "\n", "if", "errors", ".", "IsNotFound", "(", "result", "[", "0", "]", ".", "Err", ")", "||", "(", "result", "[", "0", "]", ".", "Err", "==", "nil", "&&", "result", "[", "0", "]", ".", "Machine", ".", "Life", "(", ")", "==", "params", ".", "Dead", ")", "{", "return", "jworker", ".", "ErrTerminateAgent", "\n", "}", "\n", "machine", ":=", "result", "[", "0", "]", ".", "Machine", "\n", "if", "len", "(", "containers", ")", "==", "0", "{", "if", "err", ":=", "machine", ".", "SupportsNoContainers", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "tag", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "if", "err", ":=", "machine", ".", "SetSupportedContainers", "(", "containers", "...", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "tag", ")", "\n", "}", "\n", "// Start the watcher to fire when a container is first requested on the machine.", "watcherName", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "machine", ".", "Id", "(", ")", ")", "\n\n", "credentialAPI", ",", "err", ":=", "workercommon", ".", "NewCredentialInvalidatorFacade", "(", "st", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "params", ":=", "provisioner", ".", "ContainerSetupParams", "{", "Runner", ":", "runner", ",", "WorkerName", ":", "watcherName", ",", "SupportedContainers", ":", "containers", ",", "Machine", ":", "machine", ",", "Provisioner", ":", "pr", ",", "Config", ":", "agentConfig", ",", "MachineLock", ":", "a", ".", "machineLock", ",", "CredentialAPI", ":", "credentialAPI", ",", "}", "\n", "handler", ":=", "provisioner", ".", "NewContainerSetupHandler", "(", "params", ")", "\n", "a", ".", "startWorkerAfterUpgrade", "(", "runner", ",", "watcherName", ",", "func", "(", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "w", ",", "err", ":=", "watcher", ".", "NewStringsWorker", "(", "watcher", ".", "StringsConfig", "{", "Handler", ":", "handler", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "watcherName", ")", "\n", "}", "\n", "return", "w", ",", "nil", "\n", "}", ")", "\n", "return", "nil", "\n", "}" ]
// updateSupportedContainers records in state that a machine can run the specified containers. // It starts a watcher and when a container of a given type is first added to the machine, // the watcher is killed, the machine is set up to be able to start containers of the given type, // and a suitable provisioner is started.
[ "updateSupportedContainers", "records", "in", "state", "that", "a", "machine", "can", "run", "the", "specified", "containers", ".", "It", "starts", "a", "watcher", "and", "when", "a", "container", "of", "a", "given", "type", "is", "first", "added", "to", "the", "machine", "the", "watcher", "is", "killed", "the", "machine", "is", "set", "up", "to", "be", "able", "to", "start", "containers", "of", "the", "given", "type", "and", "a", "suitable", "provisioner", "is", "started", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/machine.go#L842-L898
155,259
juju/juju
cmd/jujud/agent/machine.go
startModelWorkers
func (a *MachineAgent) startModelWorkers(modelUUID string, modelType state.ModelType) (worker.Worker, error) { controllerUUID := a.CurrentConfig().Controller().Id() modelAgent, err := model.WrapAgent(a, controllerUUID, modelUUID) if err != nil { return nil, errors.Trace(err) } config := dependencyEngineConfig() config.IsFatal = model.IsFatal config.WorstError = model.WorstError config.Filter = model.IgnoreErrRemoved engine, err := dependency.NewEngine(config) if err != nil { return nil, errors.Trace(err) } manifoldsCfg := model.ManifoldsConfig{ Agent: modelAgent, AgentConfigChanged: a.configChangedVal, Clock: clock.WallClock, RunFlagDuration: time.Minute, CharmRevisionUpdateInterval: 24 * time.Hour, InstPollerAggregationDelay: 3 * time.Second, StatusHistoryPrunerInterval: 5 * time.Minute, ActionPrunerInterval: 24 * time.Hour, NewEnvironFunc: newEnvirons, NewContainerBrokerFunc: newCAASBroker, NewMigrationMaster: migrationmaster.NewWorker, } var manifolds dependency.Manifolds if modelType == state.ModelTypeIAAS { manifolds = iaasModelManifolds(manifoldsCfg) } else { manifolds = caasModelManifolds(manifoldsCfg) } if err := dependency.Install(engine, manifolds); err != nil { if err := worker.Stop(engine); err != nil { logger.Errorf("while stopping engine with bad manifolds: %v", err) } return nil, errors.Trace(err) } return engine, nil }
go
func (a *MachineAgent) startModelWorkers(modelUUID string, modelType state.ModelType) (worker.Worker, error) { controllerUUID := a.CurrentConfig().Controller().Id() modelAgent, err := model.WrapAgent(a, controllerUUID, modelUUID) if err != nil { return nil, errors.Trace(err) } config := dependencyEngineConfig() config.IsFatal = model.IsFatal config.WorstError = model.WorstError config.Filter = model.IgnoreErrRemoved engine, err := dependency.NewEngine(config) if err != nil { return nil, errors.Trace(err) } manifoldsCfg := model.ManifoldsConfig{ Agent: modelAgent, AgentConfigChanged: a.configChangedVal, Clock: clock.WallClock, RunFlagDuration: time.Minute, CharmRevisionUpdateInterval: 24 * time.Hour, InstPollerAggregationDelay: 3 * time.Second, StatusHistoryPrunerInterval: 5 * time.Minute, ActionPrunerInterval: 24 * time.Hour, NewEnvironFunc: newEnvirons, NewContainerBrokerFunc: newCAASBroker, NewMigrationMaster: migrationmaster.NewWorker, } var manifolds dependency.Manifolds if modelType == state.ModelTypeIAAS { manifolds = iaasModelManifolds(manifoldsCfg) } else { manifolds = caasModelManifolds(manifoldsCfg) } if err := dependency.Install(engine, manifolds); err != nil { if err := worker.Stop(engine); err != nil { logger.Errorf("while stopping engine with bad manifolds: %v", err) } return nil, errors.Trace(err) } return engine, nil }
[ "func", "(", "a", "*", "MachineAgent", ")", "startModelWorkers", "(", "modelUUID", "string", ",", "modelType", "state", ".", "ModelType", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "controllerUUID", ":=", "a", ".", "CurrentConfig", "(", ")", ".", "Controller", "(", ")", ".", "Id", "(", ")", "\n", "modelAgent", ",", "err", ":=", "model", ".", "WrapAgent", "(", "a", ",", "controllerUUID", ",", "modelUUID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "config", ":=", "dependencyEngineConfig", "(", ")", "\n", "config", ".", "IsFatal", "=", "model", ".", "IsFatal", "\n", "config", ".", "WorstError", "=", "model", ".", "WorstError", "\n", "config", ".", "Filter", "=", "model", ".", "IgnoreErrRemoved", "\n", "engine", ",", "err", ":=", "dependency", ".", "NewEngine", "(", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "manifoldsCfg", ":=", "model", ".", "ManifoldsConfig", "{", "Agent", ":", "modelAgent", ",", "AgentConfigChanged", ":", "a", ".", "configChangedVal", ",", "Clock", ":", "clock", ".", "WallClock", ",", "RunFlagDuration", ":", "time", ".", "Minute", ",", "CharmRevisionUpdateInterval", ":", "24", "*", "time", ".", "Hour", ",", "InstPollerAggregationDelay", ":", "3", "*", "time", ".", "Second", ",", "StatusHistoryPrunerInterval", ":", "5", "*", "time", ".", "Minute", ",", "ActionPrunerInterval", ":", "24", "*", "time", ".", "Hour", ",", "NewEnvironFunc", ":", "newEnvirons", ",", "NewContainerBrokerFunc", ":", "newCAASBroker", ",", "NewMigrationMaster", ":", "migrationmaster", ".", "NewWorker", ",", "}", "\n", "var", "manifolds", "dependency", ".", "Manifolds", "\n", "if", "modelType", "==", "state", ".", "ModelTypeIAAS", "{", "manifolds", "=", "iaasModelManifolds", "(", "manifoldsCfg", ")", "\n", "}", "else", "{", "manifolds", "=", "caasModelManifolds", "(", "manifoldsCfg", ")", "\n", "}", "\n", "if", "err", ":=", "dependency", ".", "Install", "(", "engine", ",", "manifolds", ")", ";", "err", "!=", "nil", "{", "if", "err", ":=", "worker", ".", "Stop", "(", "engine", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "engine", ",", "nil", "\n", "}" ]
// startModelWorkers starts the set of workers that run for every model // in each controller, both IAAS and CAAS.
[ "startModelWorkers", "starts", "the", "set", "of", "workers", "that", "run", "for", "every", "model", "in", "each", "controller", "both", "IAAS", "and", "CAAS", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/machine.go#L986-L1027
155,260
juju/juju
cmd/jujud/agent/machine.go
ensureMongoServer
func (a *MachineAgent) ensureMongoServer(agentConfig agent.Config) (err error) { a.mongoInitMutex.Lock() defer a.mongoInitMutex.Unlock() if a.mongoInitialized { logger.Debugf("mongo is already initialized") return nil } defer func() { if err == nil { a.mongoInitialized = true } }() if a.isCaasMachineAgent { return nil } // EnsureMongoServer installs/upgrades the init config as necessary. ensureServerParams, err := cmdutil.NewEnsureServerParams(agentConfig) if err != nil { return err } var mongodVersion mongo.Version if mongodVersion, err = cmdutil.EnsureMongoServer(ensureServerParams); err != nil { return err } logger.Debugf("mongodb service is installed") // update Mongo version. if err = a.ChangeConfig( func(config agent.ConfigSetter) error { config.SetMongoVersion(mongodVersion) return nil }, ); err != nil { return errors.Annotate(err, "cannot set mongo version") } return nil }
go
func (a *MachineAgent) ensureMongoServer(agentConfig agent.Config) (err error) { a.mongoInitMutex.Lock() defer a.mongoInitMutex.Unlock() if a.mongoInitialized { logger.Debugf("mongo is already initialized") return nil } defer func() { if err == nil { a.mongoInitialized = true } }() if a.isCaasMachineAgent { return nil } // EnsureMongoServer installs/upgrades the init config as necessary. ensureServerParams, err := cmdutil.NewEnsureServerParams(agentConfig) if err != nil { return err } var mongodVersion mongo.Version if mongodVersion, err = cmdutil.EnsureMongoServer(ensureServerParams); err != nil { return err } logger.Debugf("mongodb service is installed") // update Mongo version. if err = a.ChangeConfig( func(config agent.ConfigSetter) error { config.SetMongoVersion(mongodVersion) return nil }, ); err != nil { return errors.Annotate(err, "cannot set mongo version") } return nil }
[ "func", "(", "a", "*", "MachineAgent", ")", "ensureMongoServer", "(", "agentConfig", "agent", ".", "Config", ")", "(", "err", "error", ")", "{", "a", ".", "mongoInitMutex", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "mongoInitMutex", ".", "Unlock", "(", ")", "\n", "if", "a", ".", "mongoInitialized", "{", "logger", ".", "Debugf", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "err", "==", "nil", "{", "a", ".", "mongoInitialized", "=", "true", "\n", "}", "\n", "}", "(", ")", "\n\n", "if", "a", ".", "isCaasMachineAgent", "{", "return", "nil", "\n", "}", "\n", "// EnsureMongoServer installs/upgrades the init config as necessary.", "ensureServerParams", ",", "err", ":=", "cmdutil", ".", "NewEnsureServerParams", "(", "agentConfig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "var", "mongodVersion", "mongo", ".", "Version", "\n", "if", "mongodVersion", ",", "err", "=", "cmdutil", ".", "EnsureMongoServer", "(", "ensureServerParams", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ")", "\n", "// update Mongo version.", "if", "err", "=", "a", ".", "ChangeConfig", "(", "func", "(", "config", "agent", ".", "ConfigSetter", ")", "error", "{", "config", ".", "SetMongoVersion", "(", "mongodVersion", ")", "\n", "return", "nil", "\n", "}", ",", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ensureMongoServer ensures that mongo is installed and running, // and ready for opening a state connection.
[ "ensureMongoServer", "ensures", "that", "mongo", "is", "installed", "and", "running", "and", "ready", "for", "opening", "a", "state", "connection", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/machine.go#L1038-L1074
155,261
juju/juju
cmd/jujud/agent/machine.go
startWorkerAfterUpgrade
func (a *MachineAgent) startWorkerAfterUpgrade(runner jworker.Runner, name string, start func() (worker.Worker, error)) { runner.StartWorker(name, func() (worker.Worker, error) { return a.upgradeWaiterWorker(name, start), nil }) }
go
func (a *MachineAgent) startWorkerAfterUpgrade(runner jworker.Runner, name string, start func() (worker.Worker, error)) { runner.StartWorker(name, func() (worker.Worker, error) { return a.upgradeWaiterWorker(name, start), nil }) }
[ "func", "(", "a", "*", "MachineAgent", ")", "startWorkerAfterUpgrade", "(", "runner", "jworker", ".", "Runner", ",", "name", "string", ",", "start", "func", "(", ")", "(", "worker", ".", "Worker", ",", "error", ")", ")", "{", "runner", ".", "StartWorker", "(", "name", ",", "func", "(", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "return", "a", ".", "upgradeWaiterWorker", "(", "name", ",", "start", ")", ",", "nil", "\n", "}", ")", "\n", "}" ]
// startWorkerAfterUpgrade starts a worker to run the specified child worker // but only after waiting for upgrades to complete.
[ "startWorkerAfterUpgrade", "starts", "a", "worker", "to", "run", "the", "specified", "child", "worker", "but", "only", "after", "waiting", "for", "upgrades", "to", "complete", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/machine.go#L1131-L1135
155,262
juju/juju
cmd/jujud/agent/machine.go
upgradeWaiterWorker
func (a *MachineAgent) upgradeWaiterWorker(name string, start func() (worker.Worker, error)) worker.Worker { return jworker.NewSimpleWorker(func(stop <-chan struct{}) error { // Wait for the agent upgrade and upgrade steps to complete (or for us to be stopped). for _, ch := range []<-chan struct{}{ a.upgradeComplete.Unlocked(), a.initialUpgradeCheckComplete.Unlocked(), } { select { case <-stop: return nil case <-ch: } } logger.Debugf("upgrades done, starting worker %q", name) // Upgrades are done, start the worker. w, err := start() if err != nil { return err } // Wait for worker to finish or for us to be stopped. done := make(chan error, 1) go func() { done <- w.Wait() }() select { case err := <-done: return errors.Annotatef(err, "worker %q exited", name) case <-stop: logger.Debugf("stopping so killing worker %q", name) return worker.Stop(w) } }) }
go
func (a *MachineAgent) upgradeWaiterWorker(name string, start func() (worker.Worker, error)) worker.Worker { return jworker.NewSimpleWorker(func(stop <-chan struct{}) error { // Wait for the agent upgrade and upgrade steps to complete (or for us to be stopped). for _, ch := range []<-chan struct{}{ a.upgradeComplete.Unlocked(), a.initialUpgradeCheckComplete.Unlocked(), } { select { case <-stop: return nil case <-ch: } } logger.Debugf("upgrades done, starting worker %q", name) // Upgrades are done, start the worker. w, err := start() if err != nil { return err } // Wait for worker to finish or for us to be stopped. done := make(chan error, 1) go func() { done <- w.Wait() }() select { case err := <-done: return errors.Annotatef(err, "worker %q exited", name) case <-stop: logger.Debugf("stopping so killing worker %q", name) return worker.Stop(w) } }) }
[ "func", "(", "a", "*", "MachineAgent", ")", "upgradeWaiterWorker", "(", "name", "string", ",", "start", "func", "(", ")", "(", "worker", ".", "Worker", ",", "error", ")", ")", "worker", ".", "Worker", "{", "return", "jworker", ".", "NewSimpleWorker", "(", "func", "(", "stop", "<-", "chan", "struct", "{", "}", ")", "error", "{", "// Wait for the agent upgrade and upgrade steps to complete (or for us to be stopped).", "for", "_", ",", "ch", ":=", "range", "[", "]", "<-", "chan", "struct", "{", "}", "{", "a", ".", "upgradeComplete", ".", "Unlocked", "(", ")", ",", "a", ".", "initialUpgradeCheckComplete", ".", "Unlocked", "(", ")", ",", "}", "{", "select", "{", "case", "<-", "stop", ":", "return", "nil", "\n", "case", "<-", "ch", ":", "}", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "name", ")", "\n\n", "// Upgrades are done, start the worker.", "w", ",", "err", ":=", "start", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// Wait for worker to finish or for us to be stopped.", "done", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "go", "func", "(", ")", "{", "done", "<-", "w", ".", "Wait", "(", ")", "\n", "}", "(", ")", "\n", "select", "{", "case", "err", ":=", "<-", "done", ":", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "name", ")", "\n", "case", "<-", "stop", ":", "logger", ".", "Debugf", "(", "\"", "\"", ",", "name", ")", "\n", "return", "worker", ".", "Stop", "(", "w", ")", "\n", "}", "\n", "}", ")", "\n", "}" ]
// upgradeWaiterWorker runs the specified worker after upgrades have completed.
[ "upgradeWaiterWorker", "runs", "the", "specified", "worker", "after", "upgrades", "have", "completed", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/machine.go#L1138-L1171
155,263
juju/juju
worker/uniter/runner/context/relation.go
NewContextRelation
func NewContextRelation(ru *uniter.RelationUnit, cache *RelationCache) *ContextRelation { return &ContextRelation{ ru: ru, relationId: ru.Relation().Id(), endpointName: ru.Endpoint().Name, cache: cache, } }
go
func NewContextRelation(ru *uniter.RelationUnit, cache *RelationCache) *ContextRelation { return &ContextRelation{ ru: ru, relationId: ru.Relation().Id(), endpointName: ru.Endpoint().Name, cache: cache, } }
[ "func", "NewContextRelation", "(", "ru", "*", "uniter", ".", "RelationUnit", ",", "cache", "*", "RelationCache", ")", "*", "ContextRelation", "{", "return", "&", "ContextRelation", "{", "ru", ":", "ru", ",", "relationId", ":", "ru", ".", "Relation", "(", ")", ".", "Id", "(", ")", ",", "endpointName", ":", "ru", ".", "Endpoint", "(", ")", ".", "Name", ",", "cache", ":", "cache", ",", "}", "\n", "}" ]
// NewContextRelation creates a new context for the given relation unit. // The unit-name keys of members supplies the initial membership.
[ "NewContextRelation", "creates", "a", "new", "context", "for", "the", "given", "relation", "unit", ".", "The", "unit", "-", "name", "keys", "of", "members", "supplies", "the", "initial", "membership", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/context/relation.go#L35-L42
155,264
juju/juju
worker/uniter/runner/context/relation.go
WriteSettings
func (ctx *ContextRelation) WriteSettings() (err error) { if ctx.settings != nil { err = ctx.settings.Write() } return }
go
func (ctx *ContextRelation) WriteSettings() (err error) { if ctx.settings != nil { err = ctx.settings.Write() } return }
[ "func", "(", "ctx", "*", "ContextRelation", ")", "WriteSettings", "(", ")", "(", "err", "error", ")", "{", "if", "ctx", ".", "settings", "!=", "nil", "{", "err", "=", "ctx", ".", "settings", ".", "Write", "(", ")", "\n", "}", "\n", "return", "\n", "}" ]
// WriteSettings persists all changes made to the unit's relation settings.
[ "WriteSettings", "persists", "all", "changes", "made", "to", "the", "unit", "s", "relation", "settings", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/context/relation.go#L76-L81
155,265
juju/juju
worker/uniter/runner/context/relation.go
SetStatus
func (ctx *ContextRelation) SetStatus(status relation.Status) error { return ctx.ru.Relation().SetStatus(status) }
go
func (ctx *ContextRelation) SetStatus(status relation.Status) error { return ctx.ru.Relation().SetStatus(status) }
[ "func", "(", "ctx", "*", "ContextRelation", ")", "SetStatus", "(", "status", "relation", ".", "Status", ")", "error", "{", "return", "ctx", ".", "ru", ".", "Relation", "(", ")", ".", "SetStatus", "(", "status", ")", "\n", "}" ]
// SetStatus sets the relation's status.
[ "SetStatus", "sets", "the", "relation", "s", "status", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/runner/context/relation.go#L89-L91
155,266
juju/juju
upgrades/steps_22.go
stateStepsFor22
func stateStepsFor22() []Step { return []Step{ &upgradeStep{ description: "add machineid to non-detachable storage docs", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().AddNonDetachableStorageMachineId() }, }, &upgradeStep{ description: "remove application config settings with nil value", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().RemoveNilValueApplicationSettings() }, }, &upgradeStep{ description: "add controller log collection sizing config settings", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().AddControllerLogCollectionsSizeSettings() }, }, &upgradeStep{ description: "add status history pruning config settings", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().AddStatusHistoryPruneSettings() }, }, &upgradeStep{ description: "add storage constraints to storage instance docs", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().AddStorageInstanceConstraints() }, }, &upgradeStep{ description: "split log collections", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().SplitLogCollections() }, }, } }
go
func stateStepsFor22() []Step { return []Step{ &upgradeStep{ description: "add machineid to non-detachable storage docs", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().AddNonDetachableStorageMachineId() }, }, &upgradeStep{ description: "remove application config settings with nil value", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().RemoveNilValueApplicationSettings() }, }, &upgradeStep{ description: "add controller log collection sizing config settings", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().AddControllerLogCollectionsSizeSettings() }, }, &upgradeStep{ description: "add status history pruning config settings", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().AddStatusHistoryPruneSettings() }, }, &upgradeStep{ description: "add storage constraints to storage instance docs", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().AddStorageInstanceConstraints() }, }, &upgradeStep{ description: "split log collections", targets: []Target{DatabaseMaster}, run: func(context Context) error { return context.State().SplitLogCollections() }, }, } }
[ "func", "stateStepsFor22", "(", ")", "[", "]", "Step", "{", "return", "[", "]", "Step", "{", "&", "upgradeStep", "{", "description", ":", "\"", "\"", ",", "targets", ":", "[", "]", "Target", "{", "DatabaseMaster", "}", ",", "run", ":", "func", "(", "context", "Context", ")", "error", "{", "return", "context", ".", "State", "(", ")", ".", "AddNonDetachableStorageMachineId", "(", ")", "\n", "}", ",", "}", ",", "&", "upgradeStep", "{", "description", ":", "\"", "\"", ",", "targets", ":", "[", "]", "Target", "{", "DatabaseMaster", "}", ",", "run", ":", "func", "(", "context", "Context", ")", "error", "{", "return", "context", ".", "State", "(", ")", ".", "RemoveNilValueApplicationSettings", "(", ")", "\n", "}", ",", "}", ",", "&", "upgradeStep", "{", "description", ":", "\"", "\"", ",", "targets", ":", "[", "]", "Target", "{", "DatabaseMaster", "}", ",", "run", ":", "func", "(", "context", "Context", ")", "error", "{", "return", "context", ".", "State", "(", ")", ".", "AddControllerLogCollectionsSizeSettings", "(", ")", "\n", "}", ",", "}", ",", "&", "upgradeStep", "{", "description", ":", "\"", "\"", ",", "targets", ":", "[", "]", "Target", "{", "DatabaseMaster", "}", ",", "run", ":", "func", "(", "context", "Context", ")", "error", "{", "return", "context", ".", "State", "(", ")", ".", "AddStatusHistoryPruneSettings", "(", ")", "\n", "}", ",", "}", ",", "&", "upgradeStep", "{", "description", ":", "\"", "\"", ",", "targets", ":", "[", "]", "Target", "{", "DatabaseMaster", "}", ",", "run", ":", "func", "(", "context", "Context", ")", "error", "{", "return", "context", ".", "State", "(", ")", ".", "AddStorageInstanceConstraints", "(", ")", "\n", "}", ",", "}", ",", "&", "upgradeStep", "{", "description", ":", "\"", "\"", ",", "targets", ":", "[", "]", "Target", "{", "DatabaseMaster", "}", ",", "run", ":", "func", "(", "context", "Context", ")", "error", "{", "return", "context", ".", "State", "(", ")", ".", "SplitLogCollections", "(", ")", "\n", "}", ",", "}", ",", "}", "\n", "}" ]
// stateStepsFor22 returns upgrade steps for Juju 2.2 that manipulate state directly.
[ "stateStepsFor22", "returns", "upgrade", "steps", "for", "Juju", "2", ".", "2", "that", "manipulate", "state", "directly", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/upgrades/steps_22.go#L12-L57
155,267
juju/juju
upgrades/steps_22.go
stepsFor22
func stepsFor22() []Step { return []Step{ &upgradeStep{ description: "remove meter status file", targets: []Target{AllMachines}, run: removeMeterStatusFile, }, } }
go
func stepsFor22() []Step { return []Step{ &upgradeStep{ description: "remove meter status file", targets: []Target{AllMachines}, run: removeMeterStatusFile, }, } }
[ "func", "stepsFor22", "(", ")", "[", "]", "Step", "{", "return", "[", "]", "Step", "{", "&", "upgradeStep", "{", "description", ":", "\"", "\"", ",", "targets", ":", "[", "]", "Target", "{", "AllMachines", "}", ",", "run", ":", "removeMeterStatusFile", ",", "}", ",", "}", "\n", "}" ]
// stepsFor22 returns upgrade steps for Juju 2.2 that only need the API.
[ "stepsFor22", "returns", "upgrade", "steps", "for", "Juju", "2", ".", "2", "that", "only", "need", "the", "API", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/upgrades/steps_22.go#L60-L68
155,268
juju/juju
upgrades/steps_22.go
removeMeterStatusFile
func removeMeterStatusFile(context Context) error { dataDir := context.AgentConfig().DataDir() meterStatusFile := filepath.Join(dataDir, "meter-status.yaml") return os.RemoveAll(meterStatusFile) }
go
func removeMeterStatusFile(context Context) error { dataDir := context.AgentConfig().DataDir() meterStatusFile := filepath.Join(dataDir, "meter-status.yaml") return os.RemoveAll(meterStatusFile) }
[ "func", "removeMeterStatusFile", "(", "context", "Context", ")", "error", "{", "dataDir", ":=", "context", ".", "AgentConfig", "(", ")", ".", "DataDir", "(", ")", "\n", "meterStatusFile", ":=", "filepath", ".", "Join", "(", "dataDir", ",", "\"", "\"", ")", "\n", "return", "os", ".", "RemoveAll", "(", "meterStatusFile", ")", "\n", "}" ]
// removeMeterStatusFile removes the meter status file from the agent data directory.
[ "removeMeterStatusFile", "removes", "the", "meter", "status", "file", "from", "the", "agent", "data", "directory", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/upgrades/steps_22.go#L71-L75
155,269
juju/juju
provider/azure/internal/azureauth/discovery.go
DiscoverAuthorizationURI
func DiscoverAuthorizationURI(sdkCtx context.Context, client subscriptions.Client, subscriptionID string) (*url.URL, error) { // We make an unauthenticated request to the Azure API, which // responds with the authentication URL with the tenant ID in it. result, err := client.Get(sdkCtx, subscriptionID) if err == nil { return nil, errors.New("expected unauthorized error response") } if result.Response.Response == nil { return nil, errors.Trace(err) } if result.StatusCode != http.StatusUnauthorized { return nil, errors.Annotatef(err, "expected unauthorized error response, got %v", result.StatusCode) } header := result.Header.Get(authenticateHeaderKey) if header == "" { return nil, errors.Errorf("%s header not found", authenticateHeaderKey) } match := authorizationUriRegexp.FindStringSubmatch(header) if match == nil { return nil, errors.Errorf( "authorization_uri not found in %s header (%q)", authenticateHeaderKey, header, ) } return url.Parse(match[1]) }
go
func DiscoverAuthorizationURI(sdkCtx context.Context, client subscriptions.Client, subscriptionID string) (*url.URL, error) { // We make an unauthenticated request to the Azure API, which // responds with the authentication URL with the tenant ID in it. result, err := client.Get(sdkCtx, subscriptionID) if err == nil { return nil, errors.New("expected unauthorized error response") } if result.Response.Response == nil { return nil, errors.Trace(err) } if result.StatusCode != http.StatusUnauthorized { return nil, errors.Annotatef(err, "expected unauthorized error response, got %v", result.StatusCode) } header := result.Header.Get(authenticateHeaderKey) if header == "" { return nil, errors.Errorf("%s header not found", authenticateHeaderKey) } match := authorizationUriRegexp.FindStringSubmatch(header) if match == nil { return nil, errors.Errorf( "authorization_uri not found in %s header (%q)", authenticateHeaderKey, header, ) } return url.Parse(match[1]) }
[ "func", "DiscoverAuthorizationURI", "(", "sdkCtx", "context", ".", "Context", ",", "client", "subscriptions", ".", "Client", ",", "subscriptionID", "string", ")", "(", "*", "url", ".", "URL", ",", "error", ")", "{", "// We make an unauthenticated request to the Azure API, which", "// responds with the authentication URL with the tenant ID in it.", "result", ",", "err", ":=", "client", ".", "Get", "(", "sdkCtx", ",", "subscriptionID", ")", "\n", "if", "err", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "result", ".", "Response", ".", "Response", "==", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "result", ".", "StatusCode", "!=", "http", ".", "StatusUnauthorized", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "result", ".", "StatusCode", ")", "\n", "}", "\n\n", "header", ":=", "result", ".", "Header", ".", "Get", "(", "authenticateHeaderKey", ")", "\n", "if", "header", "==", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "authenticateHeaderKey", ")", "\n", "}", "\n", "match", ":=", "authorizationUriRegexp", ".", "FindStringSubmatch", "(", "header", ")", "\n", "if", "match", "==", "nil", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "authenticateHeaderKey", ",", "header", ",", ")", "\n", "}", "\n", "return", "url", ".", "Parse", "(", "match", "[", "1", "]", ")", "\n", "}" ]
// DiscoverAuthorizationID returns the OAuth authorization URI for the given // subscription ID. This can be used to determine the AD tenant ID.
[ "DiscoverAuthorizationID", "returns", "the", "OAuth", "authorization", "URI", "for", "the", "given", "subscription", "ID", ".", "This", "can", "be", "used", "to", "determine", "the", "AD", "tenant", "ID", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/azure/internal/azureauth/discovery.go#L24-L50
155,270
juju/juju
provider/azure/internal/azureauth/discovery.go
AuthorizationURITenantID
func AuthorizationURITenantID(url *url.URL) (string, error) { path := strings.TrimPrefix(url.Path, "/") if _, err := utils.UUIDFromString(path); err != nil { return "", errors.NotValidf("authorization_uri %q", url) } return path, nil }
go
func AuthorizationURITenantID(url *url.URL) (string, error) { path := strings.TrimPrefix(url.Path, "/") if _, err := utils.UUIDFromString(path); err != nil { return "", errors.NotValidf("authorization_uri %q", url) } return path, nil }
[ "func", "AuthorizationURITenantID", "(", "url", "*", "url", ".", "URL", ")", "(", "string", ",", "error", ")", "{", "path", ":=", "strings", ".", "TrimPrefix", "(", "url", ".", "Path", ",", "\"", "\"", ")", "\n", "if", "_", ",", "err", ":=", "utils", ".", "UUIDFromString", "(", "path", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "url", ")", "\n", "}", "\n", "return", "path", ",", "nil", "\n", "}" ]
// AuthorizationURITenantID returns the tenant ID portion of the given URL, // which is expected to have come from DiscoverAuthorizationURI.
[ "AuthorizationURITenantID", "returns", "the", "tenant", "ID", "portion", "of", "the", "given", "URL", "which", "is", "expected", "to", "have", "come", "from", "DiscoverAuthorizationURI", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/azure/internal/azureauth/discovery.go#L54-L60
155,271
juju/juju
worker/upgradeseries/upgrader.go
NewUpgrader
func NewUpgrader(toSeries string, manager service.SystemdServiceManager, logger Logger) (Upgrader, error) { fromSeries, err := hostSeries() if err != nil { return nil, errors.Trace(err) } fromInit, err := service.VersionInitSystem(fromSeries) if err != nil { return nil, errors.Trace(err) } toInit, err := service.VersionInitSystem(toSeries) if err != nil { return nil, errors.Trace(err) } return &upgrader{ logger: logger, fromSeries: fromSeries, fromInit: fromInit, toSeries: toSeries, toInit: toInit, manager: manager, }, nil }
go
func NewUpgrader(toSeries string, manager service.SystemdServiceManager, logger Logger) (Upgrader, error) { fromSeries, err := hostSeries() if err != nil { return nil, errors.Trace(err) } fromInit, err := service.VersionInitSystem(fromSeries) if err != nil { return nil, errors.Trace(err) } toInit, err := service.VersionInitSystem(toSeries) if err != nil { return nil, errors.Trace(err) } return &upgrader{ logger: logger, fromSeries: fromSeries, fromInit: fromInit, toSeries: toSeries, toInit: toInit, manager: manager, }, nil }
[ "func", "NewUpgrader", "(", "toSeries", "string", ",", "manager", "service", ".", "SystemdServiceManager", ",", "logger", "Logger", ")", "(", "Upgrader", ",", "error", ")", "{", "fromSeries", ",", "err", ":=", "hostSeries", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "fromInit", ",", "err", ":=", "service", ".", "VersionInitSystem", "(", "fromSeries", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "toInit", ",", "err", ":=", "service", ".", "VersionInitSystem", "(", "toSeries", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "upgrader", "{", "logger", ":", "logger", ",", "fromSeries", ":", "fromSeries", ",", "fromInit", ":", "fromInit", ",", "toSeries", ":", "toSeries", ",", "toInit", ":", "toInit", ",", "manager", ":", "manager", ",", "}", ",", "nil", "\n", "}" ]
// NewUpgrader uses the input function to determine the series that should be // supported, and returns a reference to a new Upgrader that supports it.
[ "NewUpgrader", "uses", "the", "input", "function", "to", "determine", "the", "series", "that", "should", "be", "supported", "and", "returns", "a", "reference", "to", "a", "new", "Upgrader", "that", "supports", "it", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/upgrader.go#L48-L71
155,272
juju/juju
worker/upgradeseries/upgrader.go
PerformUpgrade
func (u *upgrader) PerformUpgrade() error { if err := u.populateAgents(); err != nil { return errors.Trace(err) } if err := u.ensureSystemdFiles(); err != nil { return errors.Trace(err) } return errors.Trace(u.ensureAgentBinaries()) }
go
func (u *upgrader) PerformUpgrade() error { if err := u.populateAgents(); err != nil { return errors.Trace(err) } if err := u.ensureSystemdFiles(); err != nil { return errors.Trace(err) } return errors.Trace(u.ensureAgentBinaries()) }
[ "func", "(", "u", "*", "upgrader", ")", "PerformUpgrade", "(", ")", "error", "{", "if", "err", ":=", "u", ".", "populateAgents", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "u", ".", "ensureSystemdFiles", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "errors", ".", "Trace", "(", "u", ".", "ensureAgentBinaries", "(", ")", ")", "\n", "}" ]
// PerformUpgrade writes Juju binaries and service files that allow the machine // and unit agents to run on the target version of Ubuntu.
[ "PerformUpgrade", "writes", "Juju", "binaries", "and", "service", "files", "that", "allow", "the", "machine", "and", "unit", "agents", "to", "run", "on", "the", "target", "version", "of", "Ubuntu", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/upgrader.go#L75-L85
155,273
juju/juju
worker/upgradeseries/upgrader.go
populateAgents
func (u *upgrader) populateAgents() (err error) { var unknown []string u.machineAgent, u.unitAgents, unknown, err = u.manager.FindAgents(paths.NixDataDir) if err != nil { return errors.Trace(err) } if len(unknown) > 0 { u.logger.Warningf("skipping agents not of type machine or unit: %s", strings.Join(unknown, ", ")) } return nil }
go
func (u *upgrader) populateAgents() (err error) { var unknown []string u.machineAgent, u.unitAgents, unknown, err = u.manager.FindAgents(paths.NixDataDir) if err != nil { return errors.Trace(err) } if len(unknown) > 0 { u.logger.Warningf("skipping agents not of type machine or unit: %s", strings.Join(unknown, ", ")) } return nil }
[ "func", "(", "u", "*", "upgrader", ")", "populateAgents", "(", ")", "(", "err", "error", ")", "{", "var", "unknown", "[", "]", "string", "\n", "u", ".", "machineAgent", ",", "u", ".", "unitAgents", ",", "unknown", ",", "err", "=", "u", ".", "manager", ".", "FindAgents", "(", "paths", ".", "NixDataDir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "unknown", ")", ">", "0", "{", "u", ".", "logger", ".", "Warningf", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "unknown", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// populateAgents discovers and sets the names of the machine and unit agents. // If there are any other agents determined, a warning is logged to notify that // they are being skipped from the upgrade process.
[ "populateAgents", "discovers", "and", "sets", "the", "names", "of", "the", "machine", "and", "unit", "agents", ".", "If", "there", "are", "any", "other", "agents", "determined", "a", "warning", "is", "logged", "to", "notify", "that", "they", "are", "being", "skipped", "from", "the", "upgrade", "process", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/upgrader.go#L90-L100
155,274
juju/juju
worker/upgradeseries/upgrader.go
ensureSystemdFiles
func (u *upgrader) ensureSystemdFiles() error { if u.fromInit == service.InitSystemSystemd || u.toInit != service.InitSystemSystemd { return nil } services, links, failed, err := u.manager.WriteSystemdAgents( u.machineAgent, u.unitAgents, paths.NixDataDir, systemdDir, systemdMultiUserDir) if len(services) > 0 { u.logger.Infof("agents written and linked by systemd: %s", strings.Join(services, ", ")) } if len(links) > 0 { u.logger.Infof("agents written and linked by symlink: %s", strings.Join(links, ", ")) } return errors.Annotatef(err, "failed to write agents: %s", strings.Join(failed, ", ")) }
go
func (u *upgrader) ensureSystemdFiles() error { if u.fromInit == service.InitSystemSystemd || u.toInit != service.InitSystemSystemd { return nil } services, links, failed, err := u.manager.WriteSystemdAgents( u.machineAgent, u.unitAgents, paths.NixDataDir, systemdDir, systemdMultiUserDir) if len(services) > 0 { u.logger.Infof("agents written and linked by systemd: %s", strings.Join(services, ", ")) } if len(links) > 0 { u.logger.Infof("agents written and linked by symlink: %s", strings.Join(links, ", ")) } return errors.Annotatef(err, "failed to write agents: %s", strings.Join(failed, ", ")) }
[ "func", "(", "u", "*", "upgrader", ")", "ensureSystemdFiles", "(", ")", "error", "{", "if", "u", ".", "fromInit", "==", "service", ".", "InitSystemSystemd", "||", "u", ".", "toInit", "!=", "service", ".", "InitSystemSystemd", "{", "return", "nil", "\n", "}", "\n\n", "services", ",", "links", ",", "failed", ",", "err", ":=", "u", ".", "manager", ".", "WriteSystemdAgents", "(", "u", ".", "machineAgent", ",", "u", ".", "unitAgents", ",", "paths", ".", "NixDataDir", ",", "systemdDir", ",", "systemdMultiUserDir", ")", "\n\n", "if", "len", "(", "services", ")", ">", "0", "{", "u", ".", "logger", ".", "Infof", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "services", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "if", "len", "(", "links", ")", ">", "0", "{", "u", ".", "logger", ".", "Infof", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "links", ",", "\"", "\"", ")", ")", "\n", "}", "\n\n", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "strings", ".", "Join", "(", "failed", ",", "\"", "\"", ")", ")", "\n", "}" ]
// ensureSystemdFiles determines whether re-writing service files to target // systemd is required. If it is, the necessary changes are invoked via the // service manager.
[ "ensureSystemdFiles", "determines", "whether", "re", "-", "writing", "service", "files", "to", "target", "systemd", "is", "required", ".", "If", "it", "is", "the", "necessary", "changes", "are", "invoked", "via", "the", "service", "manager", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/upgrader.go#L105-L121
155,275
juju/juju
worker/upgradeseries/upgrader.go
ensureAgentBinaries
func (u *upgrader) ensureAgentBinaries() error { if err := u.manager.CopyAgentBinary( u.machineAgent, u.unitAgents, paths.NixDataDir, u.toSeries, u.fromSeries, version.Current); err != nil { return errors.Trace(err) } u.logger.Infof("copied agent binaries for series %q", u.toSeries) return nil }
go
func (u *upgrader) ensureAgentBinaries() error { if err := u.manager.CopyAgentBinary( u.machineAgent, u.unitAgents, paths.NixDataDir, u.toSeries, u.fromSeries, version.Current); err != nil { return errors.Trace(err) } u.logger.Infof("copied agent binaries for series %q", u.toSeries) return nil }
[ "func", "(", "u", "*", "upgrader", ")", "ensureAgentBinaries", "(", ")", "error", "{", "if", "err", ":=", "u", ".", "manager", ".", "CopyAgentBinary", "(", "u", ".", "machineAgent", ",", "u", ".", "unitAgents", ",", "paths", ".", "NixDataDir", ",", "u", ".", "toSeries", ",", "u", ".", "fromSeries", ",", "version", ".", "Current", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "u", ".", "logger", ".", "Infof", "(", "\"", "\"", ",", "u", ".", "toSeries", ")", "\n", "return", "nil", "\n", "}" ]
// ensureAgentBinaries ensures that the jujud binary and links exist in the // right tools path for the target OS series, and that individual agents use // those files.
[ "ensureAgentBinaries", "ensures", "that", "the", "jujud", "binary", "and", "links", "exist", "in", "the", "right", "tools", "path", "for", "the", "target", "OS", "series", "and", "that", "individual", "agents", "use", "those", "files", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/upgradeseries/upgrader.go#L126-L134
155,276
juju/juju
apiserver/facades/client/client/status.go
unitStatusHistory
func (c *Client) unitStatusHistory(unitTag names.UnitTag, filter status.StatusHistoryFilter, kind status.HistoryKind) ([]params.DetailedStatus, error) { unit, err := c.api.stateAccessor.Unit(unitTag.Id()) if err != nil { return nil, errors.Trace(err) } statuses := []params.DetailedStatus{} if kind == status.KindUnit || kind == status.KindWorkload { unitStatuses, err := unit.StatusHistory(filter) if err != nil { return nil, errors.Trace(err) } statuses = agentStatusFromStatusInfo(unitStatuses, status.KindWorkload) } if kind == status.KindUnit || kind == status.KindUnitAgent { agentStatuses, err := unit.AgentHistory().StatusHistory(filter) if err != nil { return nil, errors.Trace(err) } statuses = append(statuses, agentStatusFromStatusInfo(agentStatuses, status.KindUnitAgent)...) } sort.Sort(byTime(statuses)) if kind == status.KindUnit && filter.Size > 0 { if len(statuses) > filter.Size { statuses = statuses[len(statuses)-filter.Size:] } } return statuses, nil }
go
func (c *Client) unitStatusHistory(unitTag names.UnitTag, filter status.StatusHistoryFilter, kind status.HistoryKind) ([]params.DetailedStatus, error) { unit, err := c.api.stateAccessor.Unit(unitTag.Id()) if err != nil { return nil, errors.Trace(err) } statuses := []params.DetailedStatus{} if kind == status.KindUnit || kind == status.KindWorkload { unitStatuses, err := unit.StatusHistory(filter) if err != nil { return nil, errors.Trace(err) } statuses = agentStatusFromStatusInfo(unitStatuses, status.KindWorkload) } if kind == status.KindUnit || kind == status.KindUnitAgent { agentStatuses, err := unit.AgentHistory().StatusHistory(filter) if err != nil { return nil, errors.Trace(err) } statuses = append(statuses, agentStatusFromStatusInfo(agentStatuses, status.KindUnitAgent)...) } sort.Sort(byTime(statuses)) if kind == status.KindUnit && filter.Size > 0 { if len(statuses) > filter.Size { statuses = statuses[len(statuses)-filter.Size:] } } return statuses, nil }
[ "func", "(", "c", "*", "Client", ")", "unitStatusHistory", "(", "unitTag", "names", ".", "UnitTag", ",", "filter", "status", ".", "StatusHistoryFilter", ",", "kind", "status", ".", "HistoryKind", ")", "(", "[", "]", "params", ".", "DetailedStatus", ",", "error", ")", "{", "unit", ",", "err", ":=", "c", ".", "api", ".", "stateAccessor", ".", "Unit", "(", "unitTag", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "statuses", ":=", "[", "]", "params", ".", "DetailedStatus", "{", "}", "\n", "if", "kind", "==", "status", ".", "KindUnit", "||", "kind", "==", "status", ".", "KindWorkload", "{", "unitStatuses", ",", "err", ":=", "unit", ".", "StatusHistory", "(", "filter", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "statuses", "=", "agentStatusFromStatusInfo", "(", "unitStatuses", ",", "status", ".", "KindWorkload", ")", "\n\n", "}", "\n", "if", "kind", "==", "status", ".", "KindUnit", "||", "kind", "==", "status", ".", "KindUnitAgent", "{", "agentStatuses", ",", "err", ":=", "unit", ".", "AgentHistory", "(", ")", ".", "StatusHistory", "(", "filter", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "statuses", "=", "append", "(", "statuses", ",", "agentStatusFromStatusInfo", "(", "agentStatuses", ",", "status", ".", "KindUnitAgent", ")", "...", ")", "\n", "}", "\n\n", "sort", ".", "Sort", "(", "byTime", "(", "statuses", ")", ")", "\n", "if", "kind", "==", "status", ".", "KindUnit", "&&", "filter", ".", "Size", ">", "0", "{", "if", "len", "(", "statuses", ")", ">", "filter", ".", "Size", "{", "statuses", "=", "statuses", "[", "len", "(", "statuses", ")", "-", "filter", ".", "Size", ":", "]", "\n", "}", "\n", "}", "\n\n", "return", "statuses", ",", "nil", "\n", "}" ]
// unitStatusHistory returns a list of status history entries for unit agents or workloads.
[ "unitStatusHistory", "returns", "a", "list", "of", "status", "history", "entries", "for", "unit", "agents", "or", "workloads", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/status.go#L58-L88
155,277
juju/juju
apiserver/facades/client/client/status.go
machineStatusHistory
func (c *Client) machineStatusHistory(machineTag names.MachineTag, filter status.StatusHistoryFilter, kind status.HistoryKind) ([]params.DetailedStatus, error) { machine, err := c.api.stateAccessor.Machine(machineTag.Id()) if err != nil { return nil, errors.Trace(err) } var sInfo []status.StatusInfo if kind == status.KindMachineInstance || kind == status.KindContainerInstance { sInfo, err = machine.InstanceStatusHistory(filter) } else { sInfo, err = machine.StatusHistory(filter) } if err != nil { return nil, errors.Trace(err) } return agentStatusFromStatusInfo(sInfo, kind), nil }
go
func (c *Client) machineStatusHistory(machineTag names.MachineTag, filter status.StatusHistoryFilter, kind status.HistoryKind) ([]params.DetailedStatus, error) { machine, err := c.api.stateAccessor.Machine(machineTag.Id()) if err != nil { return nil, errors.Trace(err) } var sInfo []status.StatusInfo if kind == status.KindMachineInstance || kind == status.KindContainerInstance { sInfo, err = machine.InstanceStatusHistory(filter) } else { sInfo, err = machine.StatusHistory(filter) } if err != nil { return nil, errors.Trace(err) } return agentStatusFromStatusInfo(sInfo, kind), nil }
[ "func", "(", "c", "*", "Client", ")", "machineStatusHistory", "(", "machineTag", "names", ".", "MachineTag", ",", "filter", "status", ".", "StatusHistoryFilter", ",", "kind", "status", ".", "HistoryKind", ")", "(", "[", "]", "params", ".", "DetailedStatus", ",", "error", ")", "{", "machine", ",", "err", ":=", "c", ".", "api", ".", "stateAccessor", ".", "Machine", "(", "machineTag", ".", "Id", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "var", "sInfo", "[", "]", "status", ".", "StatusInfo", "\n", "if", "kind", "==", "status", ".", "KindMachineInstance", "||", "kind", "==", "status", ".", "KindContainerInstance", "{", "sInfo", ",", "err", "=", "machine", ".", "InstanceStatusHistory", "(", "filter", ")", "\n", "}", "else", "{", "sInfo", ",", "err", "=", "machine", ".", "StatusHistory", "(", "filter", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "agentStatusFromStatusInfo", "(", "sInfo", ",", "kind", ")", ",", "nil", "\n", "}" ]
// machineStatusHistory returns status history for the given machine.
[ "machineStatusHistory", "returns", "status", "history", "for", "the", "given", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/status.go#L91-L106
155,278
juju/juju
apiserver/facades/client/client/status.go
StatusHistory
func (c *Client) StatusHistory(request params.StatusHistoryRequests) params.StatusHistoryResults { results := params.StatusHistoryResults{} // TODO(perrito666) the contents of the loop could be split into // a oneHistory method for clarity. for _, request := range request.Requests { filter := status.StatusHistoryFilter{ Size: request.Filter.Size, FromDate: request.Filter.Date, Delta: request.Filter.Delta, Exclude: set.NewStrings(request.Filter.Exclude...), } if err := c.checkCanRead(); err != nil { history := params.StatusHistoryResult{ Error: common.ServerError(err), } results.Results = append(results.Results, history) continue } if err := filter.Validate(); err != nil { history := params.StatusHistoryResult{ Error: common.ServerError(errors.Annotate(err, "cannot validate status history filter")), } results.Results = append(results.Results, history) continue } var ( err error hist []params.DetailedStatus ) kind := status.HistoryKind(request.Kind) err = errors.NotValidf("%q requires a unit, got %T", kind, request.Tag) switch kind { case status.KindUnit, status.KindWorkload, status.KindUnitAgent: var u names.UnitTag if u, err = names.ParseUnitTag(request.Tag); err == nil { hist, err = c.unitStatusHistory(u, filter, kind) } default: var m names.MachineTag if m, err = names.ParseMachineTag(request.Tag); err == nil { hist, err = c.machineStatusHistory(m, filter, kind) } } if err == nil { sort.Sort(byTime(hist)) } results.Results = append(results.Results, params.StatusHistoryResult{ History: params.History{Statuses: hist}, Error: common.ServerError(errors.Annotatef(err, "fetching status history for %q", request.Tag)), }) } return results }
go
func (c *Client) StatusHistory(request params.StatusHistoryRequests) params.StatusHistoryResults { results := params.StatusHistoryResults{} // TODO(perrito666) the contents of the loop could be split into // a oneHistory method for clarity. for _, request := range request.Requests { filter := status.StatusHistoryFilter{ Size: request.Filter.Size, FromDate: request.Filter.Date, Delta: request.Filter.Delta, Exclude: set.NewStrings(request.Filter.Exclude...), } if err := c.checkCanRead(); err != nil { history := params.StatusHistoryResult{ Error: common.ServerError(err), } results.Results = append(results.Results, history) continue } if err := filter.Validate(); err != nil { history := params.StatusHistoryResult{ Error: common.ServerError(errors.Annotate(err, "cannot validate status history filter")), } results.Results = append(results.Results, history) continue } var ( err error hist []params.DetailedStatus ) kind := status.HistoryKind(request.Kind) err = errors.NotValidf("%q requires a unit, got %T", kind, request.Tag) switch kind { case status.KindUnit, status.KindWorkload, status.KindUnitAgent: var u names.UnitTag if u, err = names.ParseUnitTag(request.Tag); err == nil { hist, err = c.unitStatusHistory(u, filter, kind) } default: var m names.MachineTag if m, err = names.ParseMachineTag(request.Tag); err == nil { hist, err = c.machineStatusHistory(m, filter, kind) } } if err == nil { sort.Sort(byTime(hist)) } results.Results = append(results.Results, params.StatusHistoryResult{ History: params.History{Statuses: hist}, Error: common.ServerError(errors.Annotatef(err, "fetching status history for %q", request.Tag)), }) } return results }
[ "func", "(", "c", "*", "Client", ")", "StatusHistory", "(", "request", "params", ".", "StatusHistoryRequests", ")", "params", ".", "StatusHistoryResults", "{", "results", ":=", "params", ".", "StatusHistoryResults", "{", "}", "\n", "// TODO(perrito666) the contents of the loop could be split into", "// a oneHistory method for clarity.", "for", "_", ",", "request", ":=", "range", "request", ".", "Requests", "{", "filter", ":=", "status", ".", "StatusHistoryFilter", "{", "Size", ":", "request", ".", "Filter", ".", "Size", ",", "FromDate", ":", "request", ".", "Filter", ".", "Date", ",", "Delta", ":", "request", ".", "Filter", ".", "Delta", ",", "Exclude", ":", "set", ".", "NewStrings", "(", "request", ".", "Filter", ".", "Exclude", "...", ")", ",", "}", "\n", "if", "err", ":=", "c", ".", "checkCanRead", "(", ")", ";", "err", "!=", "nil", "{", "history", ":=", "params", ".", "StatusHistoryResult", "{", "Error", ":", "common", ".", "ServerError", "(", "err", ")", ",", "}", "\n", "results", ".", "Results", "=", "append", "(", "results", ".", "Results", ",", "history", ")", "\n", "continue", "\n\n", "}", "\n\n", "if", "err", ":=", "filter", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "history", ":=", "params", ".", "StatusHistoryResult", "{", "Error", ":", "common", ".", "ServerError", "(", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ")", ",", "}", "\n", "results", ".", "Results", "=", "append", "(", "results", ".", "Results", ",", "history", ")", "\n", "continue", "\n", "}", "\n\n", "var", "(", "err", "error", "\n", "hist", "[", "]", "params", ".", "DetailedStatus", "\n", ")", "\n", "kind", ":=", "status", ".", "HistoryKind", "(", "request", ".", "Kind", ")", "\n", "err", "=", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "kind", ",", "request", ".", "Tag", ")", "\n", "switch", "kind", "{", "case", "status", ".", "KindUnit", ",", "status", ".", "KindWorkload", ",", "status", ".", "KindUnitAgent", ":", "var", "u", "names", ".", "UnitTag", "\n", "if", "u", ",", "err", "=", "names", ".", "ParseUnitTag", "(", "request", ".", "Tag", ")", ";", "err", "==", "nil", "{", "hist", ",", "err", "=", "c", ".", "unitStatusHistory", "(", "u", ",", "filter", ",", "kind", ")", "\n", "}", "\n", "default", ":", "var", "m", "names", ".", "MachineTag", "\n", "if", "m", ",", "err", "=", "names", ".", "ParseMachineTag", "(", "request", ".", "Tag", ")", ";", "err", "==", "nil", "{", "hist", ",", "err", "=", "c", ".", "machineStatusHistory", "(", "m", ",", "filter", ",", "kind", ")", "\n", "}", "\n", "}", "\n\n", "if", "err", "==", "nil", "{", "sort", ".", "Sort", "(", "byTime", "(", "hist", ")", ")", "\n", "}", "\n\n", "results", ".", "Results", "=", "append", "(", "results", ".", "Results", ",", "params", ".", "StatusHistoryResult", "{", "History", ":", "params", ".", "History", "{", "Statuses", ":", "hist", "}", ",", "Error", ":", "common", ".", "ServerError", "(", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "request", ".", "Tag", ")", ")", ",", "}", ")", "\n", "}", "\n", "return", "results", "\n", "}" ]
// StatusHistory returns a slice of past statuses for several entities.
[ "StatusHistory", "returns", "a", "slice", "of", "past", "statuses", "for", "several", "entities", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/status.go#L109-L167
155,279
juju/juju
apiserver/facades/client/client/status.go
modelStatus
func (c *Client) modelStatus() (params.ModelStatusInfo, error) { var info params.ModelStatusInfo m, err := c.api.stateAccessor.Model() if err != nil { return info, errors.Annotate(err, "cannot get model") } info.Name = m.Name() info.Type = string(m.Type()) info.CloudTag = names.NewCloudTag(m.Cloud()).String() info.CloudRegion = m.CloudRegion() cfg, err := m.Config() if err != nil { return params.ModelStatusInfo{}, errors.Annotate(err, "cannot obtain current model config") } latestVersion := m.LatestToolsVersion() current, ok := cfg.AgentVersion() if ok { info.Version = current.String() if current.Compare(latestVersion) < 0 { info.AvailableVersion = latestVersion.String() } } status, err := m.Status() if err != nil { return params.ModelStatusInfo{}, errors.Annotate(err, "cannot obtain model status info") } info.SLA = m.SLALevel() info.ModelStatus = params.DetailedStatus{ Status: status.Status.String(), Info: status.Message, Since: status.Since, Data: status.Data, } if info.SLA != "unsupported" { ms := m.MeterStatus() if isColorStatus(ms.Code) { info.MeterStatus = params.MeterStatus{Color: strings.ToLower(ms.Code.String()), Message: ms.Info} } } return info, nil }
go
func (c *Client) modelStatus() (params.ModelStatusInfo, error) { var info params.ModelStatusInfo m, err := c.api.stateAccessor.Model() if err != nil { return info, errors.Annotate(err, "cannot get model") } info.Name = m.Name() info.Type = string(m.Type()) info.CloudTag = names.NewCloudTag(m.Cloud()).String() info.CloudRegion = m.CloudRegion() cfg, err := m.Config() if err != nil { return params.ModelStatusInfo{}, errors.Annotate(err, "cannot obtain current model config") } latestVersion := m.LatestToolsVersion() current, ok := cfg.AgentVersion() if ok { info.Version = current.String() if current.Compare(latestVersion) < 0 { info.AvailableVersion = latestVersion.String() } } status, err := m.Status() if err != nil { return params.ModelStatusInfo{}, errors.Annotate(err, "cannot obtain model status info") } info.SLA = m.SLALevel() info.ModelStatus = params.DetailedStatus{ Status: status.Status.String(), Info: status.Message, Since: status.Since, Data: status.Data, } if info.SLA != "unsupported" { ms := m.MeterStatus() if isColorStatus(ms.Code) { info.MeterStatus = params.MeterStatus{Color: strings.ToLower(ms.Code.String()), Message: ms.Info} } } return info, nil }
[ "func", "(", "c", "*", "Client", ")", "modelStatus", "(", ")", "(", "params", ".", "ModelStatusInfo", ",", "error", ")", "{", "var", "info", "params", ".", "ModelStatusInfo", "\n\n", "m", ",", "err", ":=", "c", ".", "api", ".", "stateAccessor", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "info", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "info", ".", "Name", "=", "m", ".", "Name", "(", ")", "\n", "info", ".", "Type", "=", "string", "(", "m", ".", "Type", "(", ")", ")", "\n", "info", ".", "CloudTag", "=", "names", ".", "NewCloudTag", "(", "m", ".", "Cloud", "(", ")", ")", ".", "String", "(", ")", "\n", "info", ".", "CloudRegion", "=", "m", ".", "CloudRegion", "(", ")", "\n\n", "cfg", ",", "err", ":=", "m", ".", "Config", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "ModelStatusInfo", "{", "}", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "latestVersion", ":=", "m", ".", "LatestToolsVersion", "(", ")", "\n", "current", ",", "ok", ":=", "cfg", ".", "AgentVersion", "(", ")", "\n", "if", "ok", "{", "info", ".", "Version", "=", "current", ".", "String", "(", ")", "\n", "if", "current", ".", "Compare", "(", "latestVersion", ")", "<", "0", "{", "info", ".", "AvailableVersion", "=", "latestVersion", ".", "String", "(", ")", "\n", "}", "\n", "}", "\n\n", "status", ",", "err", ":=", "m", ".", "Status", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "ModelStatusInfo", "{", "}", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "info", ".", "SLA", "=", "m", ".", "SLALevel", "(", ")", "\n\n", "info", ".", "ModelStatus", "=", "params", ".", "DetailedStatus", "{", "Status", ":", "status", ".", "Status", ".", "String", "(", ")", ",", "Info", ":", "status", ".", "Message", ",", "Since", ":", "status", ".", "Since", ",", "Data", ":", "status", ".", "Data", ",", "}", "\n\n", "if", "info", ".", "SLA", "!=", "\"", "\"", "{", "ms", ":=", "m", ".", "MeterStatus", "(", ")", "\n", "if", "isColorStatus", "(", "ms", ".", "Code", ")", "{", "info", ".", "MeterStatus", "=", "params", ".", "MeterStatus", "{", "Color", ":", "strings", ".", "ToLower", "(", "ms", ".", "Code", ".", "String", "(", ")", ")", ",", "Message", ":", "ms", ".", "Info", "}", "\n", "}", "\n", "}", "\n\n", "return", "info", ",", "nil", "\n", "}" ]
// newToolsVersionAvailable will return a string representing a tools // version only if the latest check is newer than current tools.
[ "newToolsVersionAvailable", "will", "return", "a", "string", "representing", "a", "tools", "version", "only", "if", "the", "latest", "check", "is", "newer", "than", "current", "tools", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/status.go#L378-L426
155,280
juju/juju
apiserver/facades/client/client/status.go
fetchNetworkInterfaces
func fetchNetworkInterfaces(st Backend) (map[string][]*state.Address, map[string]map[string]set.Strings, map[string][]*state.LinkLayerDevice, error) { ipAddresses := make(map[string][]*state.Address) spaces := make(map[string]map[string]set.Strings) subnets, err := st.AllSubnets() if err != nil { return nil, nil, nil, err } subnetsByCIDR := make(map[string]*state.Subnet) for _, subnet := range subnets { subnetsByCIDR[subnet.CIDR()] = subnet } // For every machine, track what devices have addresses so we can filter linklayerdevices later devicesWithAddresses := make(map[string]set.Strings) ipAddrs, err := st.AllIPAddresses() if err != nil { return nil, nil, nil, err } for _, ipAddr := range ipAddrs { if ipAddr.LoopbackConfigMethod() { continue } machineID := ipAddr.MachineID() ipAddresses[machineID] = append(ipAddresses[machineID], ipAddr) if subnet, ok := subnetsByCIDR[ipAddr.SubnetCIDR()]; ok { if spaceName := subnet.SpaceName(); spaceName != "" { devices, ok := spaces[machineID] if !ok { devices = make(map[string]set.Strings) spaces[machineID] = devices } deviceName := ipAddr.DeviceName() spacesSet, ok := devices[deviceName] if !ok { spacesSet = make(set.Strings) devices[deviceName] = spacesSet } spacesSet.Add(spaceName) } } deviceSet, ok := devicesWithAddresses[machineID] if ok { deviceSet.Add(ipAddr.DeviceName()) } else { devicesWithAddresses[machineID] = set.NewStrings(ipAddr.DeviceName()) } } linkLayerDevices := make(map[string][]*state.LinkLayerDevice) llDevs, err := st.AllLinkLayerDevices() if err != nil { return nil, nil, nil, err } for _, llDev := range llDevs { if llDev.IsLoopbackDevice() { continue } machineID := llDev.MachineID() machineDevs, ok := devicesWithAddresses[machineID] if !ok { // This machine ID doesn't seem to have any devices with IP Addresses continue } if !machineDevs.Contains(llDev.Name()) { // this device did not have any IP Addresses continue } // This device had an IP Address, so include it in the list of devices for this machine linkLayerDevices[machineID] = append(linkLayerDevices[machineID], llDev) } return ipAddresses, spaces, linkLayerDevices, nil }
go
func fetchNetworkInterfaces(st Backend) (map[string][]*state.Address, map[string]map[string]set.Strings, map[string][]*state.LinkLayerDevice, error) { ipAddresses := make(map[string][]*state.Address) spaces := make(map[string]map[string]set.Strings) subnets, err := st.AllSubnets() if err != nil { return nil, nil, nil, err } subnetsByCIDR := make(map[string]*state.Subnet) for _, subnet := range subnets { subnetsByCIDR[subnet.CIDR()] = subnet } // For every machine, track what devices have addresses so we can filter linklayerdevices later devicesWithAddresses := make(map[string]set.Strings) ipAddrs, err := st.AllIPAddresses() if err != nil { return nil, nil, nil, err } for _, ipAddr := range ipAddrs { if ipAddr.LoopbackConfigMethod() { continue } machineID := ipAddr.MachineID() ipAddresses[machineID] = append(ipAddresses[machineID], ipAddr) if subnet, ok := subnetsByCIDR[ipAddr.SubnetCIDR()]; ok { if spaceName := subnet.SpaceName(); spaceName != "" { devices, ok := spaces[machineID] if !ok { devices = make(map[string]set.Strings) spaces[machineID] = devices } deviceName := ipAddr.DeviceName() spacesSet, ok := devices[deviceName] if !ok { spacesSet = make(set.Strings) devices[deviceName] = spacesSet } spacesSet.Add(spaceName) } } deviceSet, ok := devicesWithAddresses[machineID] if ok { deviceSet.Add(ipAddr.DeviceName()) } else { devicesWithAddresses[machineID] = set.NewStrings(ipAddr.DeviceName()) } } linkLayerDevices := make(map[string][]*state.LinkLayerDevice) llDevs, err := st.AllLinkLayerDevices() if err != nil { return nil, nil, nil, err } for _, llDev := range llDevs { if llDev.IsLoopbackDevice() { continue } machineID := llDev.MachineID() machineDevs, ok := devicesWithAddresses[machineID] if !ok { // This machine ID doesn't seem to have any devices with IP Addresses continue } if !machineDevs.Contains(llDev.Name()) { // this device did not have any IP Addresses continue } // This device had an IP Address, so include it in the list of devices for this machine linkLayerDevices[machineID] = append(linkLayerDevices[machineID], llDev) } return ipAddresses, spaces, linkLayerDevices, nil }
[ "func", "fetchNetworkInterfaces", "(", "st", "Backend", ")", "(", "map", "[", "string", "]", "[", "]", "*", "state", ".", "Address", ",", "map", "[", "string", "]", "map", "[", "string", "]", "set", ".", "Strings", ",", "map", "[", "string", "]", "[", "]", "*", "state", ".", "LinkLayerDevice", ",", "error", ")", "{", "ipAddresses", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "*", "state", ".", "Address", ")", "\n", "spaces", ":=", "make", "(", "map", "[", "string", "]", "map", "[", "string", "]", "set", ".", "Strings", ")", "\n", "subnets", ",", "err", ":=", "st", ".", "AllSubnets", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "subnetsByCIDR", ":=", "make", "(", "map", "[", "string", "]", "*", "state", ".", "Subnet", ")", "\n", "for", "_", ",", "subnet", ":=", "range", "subnets", "{", "subnetsByCIDR", "[", "subnet", ".", "CIDR", "(", ")", "]", "=", "subnet", "\n", "}", "\n", "// For every machine, track what devices have addresses so we can filter linklayerdevices later", "devicesWithAddresses", ":=", "make", "(", "map", "[", "string", "]", "set", ".", "Strings", ")", "\n", "ipAddrs", ",", "err", ":=", "st", ".", "AllIPAddresses", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "ipAddr", ":=", "range", "ipAddrs", "{", "if", "ipAddr", ".", "LoopbackConfigMethod", "(", ")", "{", "continue", "\n", "}", "\n", "machineID", ":=", "ipAddr", ".", "MachineID", "(", ")", "\n", "ipAddresses", "[", "machineID", "]", "=", "append", "(", "ipAddresses", "[", "machineID", "]", ",", "ipAddr", ")", "\n", "if", "subnet", ",", "ok", ":=", "subnetsByCIDR", "[", "ipAddr", ".", "SubnetCIDR", "(", ")", "]", ";", "ok", "{", "if", "spaceName", ":=", "subnet", ".", "SpaceName", "(", ")", ";", "spaceName", "!=", "\"", "\"", "{", "devices", ",", "ok", ":=", "spaces", "[", "machineID", "]", "\n", "if", "!", "ok", "{", "devices", "=", "make", "(", "map", "[", "string", "]", "set", ".", "Strings", ")", "\n", "spaces", "[", "machineID", "]", "=", "devices", "\n", "}", "\n", "deviceName", ":=", "ipAddr", ".", "DeviceName", "(", ")", "\n", "spacesSet", ",", "ok", ":=", "devices", "[", "deviceName", "]", "\n", "if", "!", "ok", "{", "spacesSet", "=", "make", "(", "set", ".", "Strings", ")", "\n", "devices", "[", "deviceName", "]", "=", "spacesSet", "\n", "}", "\n", "spacesSet", ".", "Add", "(", "spaceName", ")", "\n", "}", "\n", "}", "\n", "deviceSet", ",", "ok", ":=", "devicesWithAddresses", "[", "machineID", "]", "\n", "if", "ok", "{", "deviceSet", ".", "Add", "(", "ipAddr", ".", "DeviceName", "(", ")", ")", "\n", "}", "else", "{", "devicesWithAddresses", "[", "machineID", "]", "=", "set", ".", "NewStrings", "(", "ipAddr", ".", "DeviceName", "(", ")", ")", "\n", "}", "\n", "}", "\n\n", "linkLayerDevices", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "*", "state", ".", "LinkLayerDevice", ")", "\n", "llDevs", ",", "err", ":=", "st", ".", "AllLinkLayerDevices", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "llDev", ":=", "range", "llDevs", "{", "if", "llDev", ".", "IsLoopbackDevice", "(", ")", "{", "continue", "\n", "}", "\n", "machineID", ":=", "llDev", ".", "MachineID", "(", ")", "\n", "machineDevs", ",", "ok", ":=", "devicesWithAddresses", "[", "machineID", "]", "\n", "if", "!", "ok", "{", "// This machine ID doesn't seem to have any devices with IP Addresses", "continue", "\n", "}", "\n", "if", "!", "machineDevs", ".", "Contains", "(", "llDev", ".", "Name", "(", ")", ")", "{", "// this device did not have any IP Addresses", "continue", "\n", "}", "\n", "// This device had an IP Address, so include it in the list of devices for this machine", "linkLayerDevices", "[", "machineID", "]", "=", "append", "(", "linkLayerDevices", "[", "machineID", "]", ",", "llDev", ")", "\n", "}", "\n\n", "return", "ipAddresses", ",", "spaces", ",", "linkLayerDevices", ",", "nil", "\n", "}" ]
// fetchNetworkInterfaces returns maps from machine id to ip.addresses, machine // id to a map of interface names from space names, and machine id to // linklayerdevices. // // All are required to determine a machine's network interfaces configuration, // so we want all or none.
[ "fetchNetworkInterfaces", "returns", "maps", "from", "machine", "id", "to", "ip", ".", "addresses", "machine", "id", "to", "a", "map", "of", "interface", "names", "from", "space", "names", "and", "machine", "id", "to", "linklayerdevices", ".", "All", "are", "required", "to", "determine", "a", "machine", "s", "network", "interfaces", "configuration", "so", "we", "want", "all", "or", "none", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/status.go#L519-L590
155,281
juju/juju
apiserver/facades/client/client/status.go
fetchAllApplicationsAndUnits
func fetchAllApplicationsAndUnits( st Backend, model *state.Model, ) (applicationStatusInfo, error) { appMap := make(map[string]*state.Application) unitMap := make(map[string]map[string]*state.Unit) latestCharms := make(map[charm.URL]*state.Charm) applications, err := st.AllApplications() units, err := model.AllUnits() if err != nil { return applicationStatusInfo{}, err } allUnitsByApp := make(map[string]map[string]*state.Unit) for _, unit := range units { appName := unit.ApplicationName() if inner, found := allUnitsByApp[appName]; found { inner[unit.Name()] = unit } else { allUnitsByApp[appName] = map[string]*state.Unit{ unit.Name(): unit, } } } endpointBindings, err := model.AllEndpointBindings() if err != nil { return applicationStatusInfo{}, err } allBindingsByApp := make(map[string]map[string]string) for _, bindings := range endpointBindings { allBindingsByApp[bindings.AppName] = bindings.Bindings } lxdProfiles := make(map[string]*charm.LXDProfile) for _, app := range applications { appMap[app.Name()] = app appUnits := allUnitsByApp[app.Name()] charmURL, _ := app.CharmURL() if len(appUnits) > 0 { unitMap[app.Name()] = appUnits // Record the base URL for the application's charm so that // the latest store revision can be looked up. if charmURL.Schema == "cs" { latestCharms[*charmURL.WithRevision(-1)] = nil } } ch, _, err := app.Charm() if err != nil { continue } chName := lxdprofile.Name(model.Name(), app.Name(), ch.Revision()) if profile := ch.LXDProfile(); profile != nil { lxdProfiles[chName] = profile } } for baseURL := range latestCharms { ch, err := st.LatestPlaceholderCharm(&baseURL) if errors.IsNotFound(err) { continue } if err != nil { return applicationStatusInfo{}, err } latestCharms[baseURL] = ch } return applicationStatusInfo{ applications: appMap, units: unitMap, latestCharms: latestCharms, endpointBindings: allBindingsByApp, lxdProfiles: lxdProfiles, }, nil }
go
func fetchAllApplicationsAndUnits( st Backend, model *state.Model, ) (applicationStatusInfo, error) { appMap := make(map[string]*state.Application) unitMap := make(map[string]map[string]*state.Unit) latestCharms := make(map[charm.URL]*state.Charm) applications, err := st.AllApplications() units, err := model.AllUnits() if err != nil { return applicationStatusInfo{}, err } allUnitsByApp := make(map[string]map[string]*state.Unit) for _, unit := range units { appName := unit.ApplicationName() if inner, found := allUnitsByApp[appName]; found { inner[unit.Name()] = unit } else { allUnitsByApp[appName] = map[string]*state.Unit{ unit.Name(): unit, } } } endpointBindings, err := model.AllEndpointBindings() if err != nil { return applicationStatusInfo{}, err } allBindingsByApp := make(map[string]map[string]string) for _, bindings := range endpointBindings { allBindingsByApp[bindings.AppName] = bindings.Bindings } lxdProfiles := make(map[string]*charm.LXDProfile) for _, app := range applications { appMap[app.Name()] = app appUnits := allUnitsByApp[app.Name()] charmURL, _ := app.CharmURL() if len(appUnits) > 0 { unitMap[app.Name()] = appUnits // Record the base URL for the application's charm so that // the latest store revision can be looked up. if charmURL.Schema == "cs" { latestCharms[*charmURL.WithRevision(-1)] = nil } } ch, _, err := app.Charm() if err != nil { continue } chName := lxdprofile.Name(model.Name(), app.Name(), ch.Revision()) if profile := ch.LXDProfile(); profile != nil { lxdProfiles[chName] = profile } } for baseURL := range latestCharms { ch, err := st.LatestPlaceholderCharm(&baseURL) if errors.IsNotFound(err) { continue } if err != nil { return applicationStatusInfo{}, err } latestCharms[baseURL] = ch } return applicationStatusInfo{ applications: appMap, units: unitMap, latestCharms: latestCharms, endpointBindings: allBindingsByApp, lxdProfiles: lxdProfiles, }, nil }
[ "func", "fetchAllApplicationsAndUnits", "(", "st", "Backend", ",", "model", "*", "state", ".", "Model", ",", ")", "(", "applicationStatusInfo", ",", "error", ")", "{", "appMap", ":=", "make", "(", "map", "[", "string", "]", "*", "state", ".", "Application", ")", "\n", "unitMap", ":=", "make", "(", "map", "[", "string", "]", "map", "[", "string", "]", "*", "state", ".", "Unit", ")", "\n", "latestCharms", ":=", "make", "(", "map", "[", "charm", ".", "URL", "]", "*", "state", ".", "Charm", ")", "\n", "applications", ",", "err", ":=", "st", ".", "AllApplications", "(", ")", "\n", "units", ",", "err", ":=", "model", ".", "AllUnits", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "applicationStatusInfo", "{", "}", ",", "err", "\n", "}", "\n", "allUnitsByApp", ":=", "make", "(", "map", "[", "string", "]", "map", "[", "string", "]", "*", "state", ".", "Unit", ")", "\n", "for", "_", ",", "unit", ":=", "range", "units", "{", "appName", ":=", "unit", ".", "ApplicationName", "(", ")", "\n\n", "if", "inner", ",", "found", ":=", "allUnitsByApp", "[", "appName", "]", ";", "found", "{", "inner", "[", "unit", ".", "Name", "(", ")", "]", "=", "unit", "\n", "}", "else", "{", "allUnitsByApp", "[", "appName", "]", "=", "map", "[", "string", "]", "*", "state", ".", "Unit", "{", "unit", ".", "Name", "(", ")", ":", "unit", ",", "}", "\n", "}", "\n", "}", "\n\n", "endpointBindings", ",", "err", ":=", "model", ".", "AllEndpointBindings", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "applicationStatusInfo", "{", "}", ",", "err", "\n", "}", "\n", "allBindingsByApp", ":=", "make", "(", "map", "[", "string", "]", "map", "[", "string", "]", "string", ")", "\n", "for", "_", ",", "bindings", ":=", "range", "endpointBindings", "{", "allBindingsByApp", "[", "bindings", ".", "AppName", "]", "=", "bindings", ".", "Bindings", "\n", "}", "\n\n", "lxdProfiles", ":=", "make", "(", "map", "[", "string", "]", "*", "charm", ".", "LXDProfile", ")", "\n", "for", "_", ",", "app", ":=", "range", "applications", "{", "appMap", "[", "app", ".", "Name", "(", ")", "]", "=", "app", "\n", "appUnits", ":=", "allUnitsByApp", "[", "app", ".", "Name", "(", ")", "]", "\n", "charmURL", ",", "_", ":=", "app", ".", "CharmURL", "(", ")", "\n\n", "if", "len", "(", "appUnits", ")", ">", "0", "{", "unitMap", "[", "app", ".", "Name", "(", ")", "]", "=", "appUnits", "\n", "// Record the base URL for the application's charm so that", "// the latest store revision can be looked up.", "if", "charmURL", ".", "Schema", "==", "\"", "\"", "{", "latestCharms", "[", "*", "charmURL", ".", "WithRevision", "(", "-", "1", ")", "]", "=", "nil", "\n", "}", "\n", "}", "\n\n", "ch", ",", "_", ",", "err", ":=", "app", ".", "Charm", "(", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "chName", ":=", "lxdprofile", ".", "Name", "(", "model", ".", "Name", "(", ")", ",", "app", ".", "Name", "(", ")", ",", "ch", ".", "Revision", "(", ")", ")", "\n", "if", "profile", ":=", "ch", ".", "LXDProfile", "(", ")", ";", "profile", "!=", "nil", "{", "lxdProfiles", "[", "chName", "]", "=", "profile", "\n", "}", "\n", "}", "\n\n", "for", "baseURL", ":=", "range", "latestCharms", "{", "ch", ",", "err", ":=", "st", ".", "LatestPlaceholderCharm", "(", "&", "baseURL", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "continue", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "applicationStatusInfo", "{", "}", ",", "err", "\n", "}", "\n", "latestCharms", "[", "baseURL", "]", "=", "ch", "\n", "}", "\n\n", "return", "applicationStatusInfo", "{", "applications", ":", "appMap", ",", "units", ":", "unitMap", ",", "latestCharms", ":", "latestCharms", ",", "endpointBindings", ":", "allBindingsByApp", ",", "lxdProfiles", ":", "lxdProfiles", ",", "}", ",", "nil", "\n", "}" ]
// fetchAllApplicationsAndUnits returns a map from application name to application, // a map from application name to unit name to unit, and a map from base charm URL to latest URL.
[ "fetchAllApplicationsAndUnits", "returns", "a", "map", "from", "application", "name", "to", "application", "a", "map", "from", "application", "name", "to", "unit", "name", "to", "unit", "and", "a", "map", "from", "base", "charm", "URL", "to", "latest", "URL", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/status.go#L594-L671
155,282
juju/juju
apiserver/facades/client/client/status.go
fetchConsumerRemoteApplications
func fetchConsumerRemoteApplications(st Backend) (map[string]*state.RemoteApplication, error) { appMap := make(map[string]*state.RemoteApplication) applications, err := st.AllRemoteApplications() if err != nil { return nil, err } for _, a := range applications { if _, ok := a.URL(); !ok { continue } appMap[a.Name()] = a } return appMap, nil }
go
func fetchConsumerRemoteApplications(st Backend) (map[string]*state.RemoteApplication, error) { appMap := make(map[string]*state.RemoteApplication) applications, err := st.AllRemoteApplications() if err != nil { return nil, err } for _, a := range applications { if _, ok := a.URL(); !ok { continue } appMap[a.Name()] = a } return appMap, nil }
[ "func", "fetchConsumerRemoteApplications", "(", "st", "Backend", ")", "(", "map", "[", "string", "]", "*", "state", ".", "RemoteApplication", ",", "error", ")", "{", "appMap", ":=", "make", "(", "map", "[", "string", "]", "*", "state", ".", "RemoteApplication", ")", "\n", "applications", ",", "err", ":=", "st", ".", "AllRemoteApplications", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "a", ":=", "range", "applications", "{", "if", "_", ",", "ok", ":=", "a", ".", "URL", "(", ")", ";", "!", "ok", "{", "continue", "\n", "}", "\n", "appMap", "[", "a", ".", "Name", "(", ")", "]", "=", "a", "\n", "}", "\n", "return", "appMap", ",", "nil", "\n", "}" ]
// fetchConsumerRemoteApplications returns a map from application name to remote application.
[ "fetchConsumerRemoteApplications", "returns", "a", "map", "from", "application", "name", "to", "remote", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/status.go#L674-L687
155,283
juju/juju
apiserver/facades/client/client/status.go
fetchOffers
func fetchOffers(st Backend, applications map[string]*state.Application) (map[string]offerStatus, error) { offersMap := make(map[string]offerStatus) offers, err := st.AllApplicationOffers() if err != nil { return nil, err } for _, offer := range offers { offerInfo := offerStatus{ ApplicationOffer: crossmodel.ApplicationOffer{ OfferName: offer.OfferName, OfferUUID: offer.OfferUUID, ApplicationName: offer.ApplicationName, Endpoints: offer.Endpoints, }, } app, ok := applications[offer.ApplicationName] if !ok { continue } curl, _ := app.CharmURL() offerInfo.charmURL = curl.String() rc, err := st.RemoteConnectionStatus(offer.OfferUUID) if err != nil && !errors.IsNotFound(err) { offerInfo.err = err continue } else if err == nil { offerInfo.totalConnectedCount = rc.TotalConnectionCount() offerInfo.activeConnectedCount = rc.ActiveConnectionCount() } offersMap[offer.OfferName] = offerInfo } return offersMap, nil }
go
func fetchOffers(st Backend, applications map[string]*state.Application) (map[string]offerStatus, error) { offersMap := make(map[string]offerStatus) offers, err := st.AllApplicationOffers() if err != nil { return nil, err } for _, offer := range offers { offerInfo := offerStatus{ ApplicationOffer: crossmodel.ApplicationOffer{ OfferName: offer.OfferName, OfferUUID: offer.OfferUUID, ApplicationName: offer.ApplicationName, Endpoints: offer.Endpoints, }, } app, ok := applications[offer.ApplicationName] if !ok { continue } curl, _ := app.CharmURL() offerInfo.charmURL = curl.String() rc, err := st.RemoteConnectionStatus(offer.OfferUUID) if err != nil && !errors.IsNotFound(err) { offerInfo.err = err continue } else if err == nil { offerInfo.totalConnectedCount = rc.TotalConnectionCount() offerInfo.activeConnectedCount = rc.ActiveConnectionCount() } offersMap[offer.OfferName] = offerInfo } return offersMap, nil }
[ "func", "fetchOffers", "(", "st", "Backend", ",", "applications", "map", "[", "string", "]", "*", "state", ".", "Application", ")", "(", "map", "[", "string", "]", "offerStatus", ",", "error", ")", "{", "offersMap", ":=", "make", "(", "map", "[", "string", "]", "offerStatus", ")", "\n", "offers", ",", "err", ":=", "st", ".", "AllApplicationOffers", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "offer", ":=", "range", "offers", "{", "offerInfo", ":=", "offerStatus", "{", "ApplicationOffer", ":", "crossmodel", ".", "ApplicationOffer", "{", "OfferName", ":", "offer", ".", "OfferName", ",", "OfferUUID", ":", "offer", ".", "OfferUUID", ",", "ApplicationName", ":", "offer", ".", "ApplicationName", ",", "Endpoints", ":", "offer", ".", "Endpoints", ",", "}", ",", "}", "\n", "app", ",", "ok", ":=", "applications", "[", "offer", ".", "ApplicationName", "]", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "curl", ",", "_", ":=", "app", ".", "CharmURL", "(", ")", "\n", "offerInfo", ".", "charmURL", "=", "curl", ".", "String", "(", ")", "\n", "rc", ",", "err", ":=", "st", ".", "RemoteConnectionStatus", "(", "offer", ".", "OfferUUID", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "errors", ".", "IsNotFound", "(", "err", ")", "{", "offerInfo", ".", "err", "=", "err", "\n", "continue", "\n", "}", "else", "if", "err", "==", "nil", "{", "offerInfo", ".", "totalConnectedCount", "=", "rc", ".", "TotalConnectionCount", "(", ")", "\n", "offerInfo", ".", "activeConnectedCount", "=", "rc", ".", "ActiveConnectionCount", "(", ")", "\n", "}", "\n", "offersMap", "[", "offer", ".", "OfferName", "]", "=", "offerInfo", "\n", "}", "\n", "return", "offersMap", ",", "nil", "\n", "}" ]
// fetchOfferConnections returns a map from relation id to offer connection.
[ "fetchOfferConnections", "returns", "a", "map", "from", "relation", "id", "to", "offer", "connection", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/status.go#L690-L722
155,284
juju/juju
apiserver/facades/client/client/status.go
getAllRelations
func (context *statusContext) getAllRelations() []*state.Relation { var out []*state.Relation seenRelations := make(map[int]bool) for _, relations := range context.relations { for _, relation := range relations { if _, found := seenRelations[relation.Id()]; !found { out = append(out, relation) seenRelations[relation.Id()] = true } } } return out }
go
func (context *statusContext) getAllRelations() []*state.Relation { var out []*state.Relation seenRelations := make(map[int]bool) for _, relations := range context.relations { for _, relation := range relations { if _, found := seenRelations[relation.Id()]; !found { out = append(out, relation) seenRelations[relation.Id()] = true } } } return out }
[ "func", "(", "context", "*", "statusContext", ")", "getAllRelations", "(", ")", "[", "]", "*", "state", ".", "Relation", "{", "var", "out", "[", "]", "*", "state", ".", "Relation", "\n", "seenRelations", ":=", "make", "(", "map", "[", "int", "]", "bool", ")", "\n", "for", "_", ",", "relations", ":=", "range", "context", ".", "relations", "{", "for", "_", ",", "relation", ":=", "range", "relations", "{", "if", "_", ",", "found", ":=", "seenRelations", "[", "relation", ".", "Id", "(", ")", "]", ";", "!", "found", "{", "out", "=", "append", "(", "out", ",", "relation", ")", "\n", "seenRelations", "[", "relation", ".", "Id", "(", ")", "]", "=", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "out", "\n", "}" ]
// This method exists only to dedup the loaded relations as they will // appear multiple times in context.relations.
[ "This", "method", "exists", "only", "to", "dedup", "the", "loaded", "relations", "as", "they", "will", "appear", "multiple", "times", "in", "context", ".", "relations", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/status.go#L968-L980
155,285
juju/juju
apiserver/facades/client/client/status.go
paramsJobsFromJobs
func paramsJobsFromJobs(jobs []state.MachineJob) []multiwatcher.MachineJob { paramsJobs := make([]multiwatcher.MachineJob, len(jobs)) for i, machineJob := range jobs { paramsJobs[i] = machineJob.ToParams() } return paramsJobs }
go
func paramsJobsFromJobs(jobs []state.MachineJob) []multiwatcher.MachineJob { paramsJobs := make([]multiwatcher.MachineJob, len(jobs)) for i, machineJob := range jobs { paramsJobs[i] = machineJob.ToParams() } return paramsJobs }
[ "func", "paramsJobsFromJobs", "(", "jobs", "[", "]", "state", ".", "MachineJob", ")", "[", "]", "multiwatcher", ".", "MachineJob", "{", "paramsJobs", ":=", "make", "(", "[", "]", "multiwatcher", ".", "MachineJob", ",", "len", "(", "jobs", ")", ")", "\n", "for", "i", ",", "machineJob", ":=", "range", "jobs", "{", "paramsJobs", "[", "i", "]", "=", "machineJob", ".", "ToParams", "(", ")", "\n", "}", "\n", "return", "paramsJobs", "\n", "}" ]
// paramsJobsFromJobs converts state jobs to params jobs.
[ "paramsJobsFromJobs", "converts", "state", "jobs", "to", "params", "jobs", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/status.go#L995-L1001
155,286
juju/juju
apiserver/facades/client/client/status.go
AgentStatus
func (c *contextUnit) AgentStatus() (status.StatusInfo, error) { return c.context.status.UnitAgent(c.Name()) }
go
func (c *contextUnit) AgentStatus() (status.StatusInfo, error) { return c.context.status.UnitAgent(c.Name()) }
[ "func", "(", "c", "*", "contextUnit", ")", "AgentStatus", "(", ")", "(", "status", ".", "StatusInfo", ",", "error", ")", "{", "return", "c", ".", "context", ".", "status", ".", "UnitAgent", "(", "c", ".", "Name", "(", ")", ")", "\n", "}" ]
// AgentStatus implements UnitStatusGetter.
[ "AgentStatus", "implements", "UnitStatusGetter", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/status.go#L1376-L1378
155,287
juju/juju
apiserver/facades/client/client/status.go
Status
func (c *contextUnit) Status() (status.StatusInfo, error) { return c.context.status.UnitWorkload(c.Name(), c.expectWorkload) }
go
func (c *contextUnit) Status() (status.StatusInfo, error) { return c.context.status.UnitWorkload(c.Name(), c.expectWorkload) }
[ "func", "(", "c", "*", "contextUnit", ")", "Status", "(", ")", "(", "status", ".", "StatusInfo", ",", "error", ")", "{", "return", "c", ".", "context", ".", "status", ".", "UnitWorkload", "(", "c", ".", "Name", "(", ")", ",", "c", ".", "expectWorkload", ")", "\n", "}" ]
// Status implements UnitStatusGetter.
[ "Status", "implements", "UnitStatusGetter", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/status.go#L1381-L1383
155,288
juju/juju
apiserver/facades/client/client/status.go
processUnitAndAgentStatus
func (c *statusContext) processUnitAndAgentStatus(unit *state.Unit, expectWorkload bool) (agentStatus, workloadStatus params.DetailedStatus) { wrapped := &contextUnit{unit, expectWorkload, c} agent, workload := c.presence.UnitStatus(wrapped) populateStatusFromStatusInfoAndErr(&agentStatus, agent.Status, agent.Err) populateStatusFromStatusInfoAndErr(&workloadStatus, workload.Status, workload.Err) agentStatus.Life = processLife(unit) if t, err := unit.AgentTools(); err == nil { agentStatus.Version = t.Version.Number.String() } return }
go
func (c *statusContext) processUnitAndAgentStatus(unit *state.Unit, expectWorkload bool) (agentStatus, workloadStatus params.DetailedStatus) { wrapped := &contextUnit{unit, expectWorkload, c} agent, workload := c.presence.UnitStatus(wrapped) populateStatusFromStatusInfoAndErr(&agentStatus, agent.Status, agent.Err) populateStatusFromStatusInfoAndErr(&workloadStatus, workload.Status, workload.Err) agentStatus.Life = processLife(unit) if t, err := unit.AgentTools(); err == nil { agentStatus.Version = t.Version.Number.String() } return }
[ "func", "(", "c", "*", "statusContext", ")", "processUnitAndAgentStatus", "(", "unit", "*", "state", ".", "Unit", ",", "expectWorkload", "bool", ")", "(", "agentStatus", ",", "workloadStatus", "params", ".", "DetailedStatus", ")", "{", "wrapped", ":=", "&", "contextUnit", "{", "unit", ",", "expectWorkload", ",", "c", "}", "\n", "agent", ",", "workload", ":=", "c", ".", "presence", ".", "UnitStatus", "(", "wrapped", ")", "\n", "populateStatusFromStatusInfoAndErr", "(", "&", "agentStatus", ",", "agent", ".", "Status", ",", "agent", ".", "Err", ")", "\n", "populateStatusFromStatusInfoAndErr", "(", "&", "workloadStatus", ",", "workload", ".", "Status", ",", "workload", ".", "Err", ")", "\n\n", "agentStatus", ".", "Life", "=", "processLife", "(", "unit", ")", "\n\n", "if", "t", ",", "err", ":=", "unit", ".", "AgentTools", "(", ")", ";", "err", "==", "nil", "{", "agentStatus", ".", "Version", "=", "t", ".", "Version", ".", "Number", ".", "String", "(", ")", "\n", "}", "\n", "return", "\n", "}" ]
// processUnitAndAgentStatus retrieves status information for both unit and unitAgents.
[ "processUnitAndAgentStatus", "retrieves", "status", "information", "for", "both", "unit", "and", "unitAgents", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/status.go#L1386-L1398
155,289
juju/juju
apiserver/facades/client/client/status.go
Status
func (c *contextMachine) Status() (status.StatusInfo, error) { return c.context.status.MachineAgent(c.Id()) }
go
func (c *contextMachine) Status() (status.StatusInfo, error) { return c.context.status.MachineAgent(c.Id()) }
[ "func", "(", "c", "*", "contextMachine", ")", "Status", "(", ")", "(", "status", ".", "StatusInfo", ",", "error", ")", "{", "return", "c", ".", "context", ".", "status", ".", "MachineAgent", "(", "c", ".", "Id", "(", ")", ")", "\n", "}" ]
// Return the agent status for the machine.
[ "Return", "the", "agent", "status", "for", "the", "machine", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/status.go#L1420-L1422
155,290
juju/juju
apiserver/facades/client/client/status.go
processMachine
func (c *statusContext) processMachine(machine *state.Machine) (out params.DetailedStatus) { wrapped := &contextMachine{machine, c} statusInfo, err := c.presence.MachineStatus(wrapped) populateStatusFromStatusInfoAndErr(&out, statusInfo, err) out.Life = processLife(machine) if t, err := machine.AgentTools(); err == nil { out.Version = t.Version.Number.String() } return }
go
func (c *statusContext) processMachine(machine *state.Machine) (out params.DetailedStatus) { wrapped := &contextMachine{machine, c} statusInfo, err := c.presence.MachineStatus(wrapped) populateStatusFromStatusInfoAndErr(&out, statusInfo, err) out.Life = processLife(machine) if t, err := machine.AgentTools(); err == nil { out.Version = t.Version.Number.String() } return }
[ "func", "(", "c", "*", "statusContext", ")", "processMachine", "(", "machine", "*", "state", ".", "Machine", ")", "(", "out", "params", ".", "DetailedStatus", ")", "{", "wrapped", ":=", "&", "contextMachine", "{", "machine", ",", "c", "}", "\n", "statusInfo", ",", "err", ":=", "c", ".", "presence", ".", "MachineStatus", "(", "wrapped", ")", "\n", "populateStatusFromStatusInfoAndErr", "(", "&", "out", ",", "statusInfo", ",", "err", ")", "\n\n", "out", ".", "Life", "=", "processLife", "(", "machine", ")", "\n\n", "if", "t", ",", "err", ":=", "machine", ".", "AgentTools", "(", ")", ";", "err", "==", "nil", "{", "out", ".", "Version", "=", "t", ".", "Version", ".", "Number", ".", "String", "(", ")", "\n", "}", "\n", "return", "\n", "}" ]
// processMachine retrieves version and status information for the given machine. // It also returns deprecated legacy status information.
[ "processMachine", "retrieves", "version", "and", "status", "information", "for", "the", "given", "machine", ".", "It", "also", "returns", "deprecated", "legacy", "status", "information", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/status.go#L1426-L1437
155,291
juju/juju
apiserver/facades/client/client/status.go
filterStatusData
func filterStatusData(status map[string]interface{}) map[string]interface{} { out := make(map[string]interface{}) for name, value := range status { // use a set here if we end up with a larger whitelist if name == "relation-id" { out[name] = value } } return out }
go
func filterStatusData(status map[string]interface{}) map[string]interface{} { out := make(map[string]interface{}) for name, value := range status { // use a set here if we end up with a larger whitelist if name == "relation-id" { out[name] = value } } return out }
[ "func", "filterStatusData", "(", "status", "map", "[", "string", "]", "interface", "{", "}", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "out", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "for", "name", ",", "value", ":=", "range", "status", "{", "// use a set here if we end up with a larger whitelist", "if", "name", "==", "\"", "\"", "{", "out", "[", "name", "]", "=", "value", "\n", "}", "\n", "}", "\n", "return", "out", "\n", "}" ]
// filterStatusData limits what agent StatusData data is passed over // the API. This prevents unintended leakage of internal-only data.
[ "filterStatusData", "limits", "what", "agent", "StatusData", "data", "is", "passed", "over", "the", "API", ".", "This", "prevents", "unintended", "leakage", "of", "internal", "-", "only", "data", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/client/status.go#L1441-L1450
155,292
juju/juju
apiserver/httpcontext.go
stateForRequestUnauthenticated
func (ctxt *httpContext) stateForRequestUnauthenticated(r *http.Request) (*state.PooledState, error) { modelUUID := httpcontext.RequestModelUUID(r) st, err := ctxt.srv.shared.statePool.Get(modelUUID) if err != nil { return nil, errors.Trace(err) } return st, nil }
go
func (ctxt *httpContext) stateForRequestUnauthenticated(r *http.Request) (*state.PooledState, error) { modelUUID := httpcontext.RequestModelUUID(r) st, err := ctxt.srv.shared.statePool.Get(modelUUID) if err != nil { return nil, errors.Trace(err) } return st, nil }
[ "func", "(", "ctxt", "*", "httpContext", ")", "stateForRequestUnauthenticated", "(", "r", "*", "http", ".", "Request", ")", "(", "*", "state", ".", "PooledState", ",", "error", ")", "{", "modelUUID", ":=", "httpcontext", ".", "RequestModelUUID", "(", "r", ")", "\n", "st", ",", "err", ":=", "ctxt", ".", "srv", ".", "shared", ".", "statePool", ".", "Get", "(", "modelUUID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "st", ",", "nil", "\n", "}" ]
// stateForRequestUnauthenticated returns a state instance appropriate for // using for the model implicit in the given request // without checking any authentication information.
[ "stateForRequestUnauthenticated", "returns", "a", "state", "instance", "appropriate", "for", "using", "for", "the", "model", "implicit", "in", "the", "given", "request", "without", "checking", "any", "authentication", "information", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/httpcontext.go#L29-L36
155,293
juju/juju
apiserver/httpcontext.go
stateForRequestAuthenticated
func (ctxt *httpContext) stateForRequestAuthenticated(r *http.Request) ( resultSt *state.PooledState, resultEntity state.Entity, err error, ) { authInfo, ok := httpcontext.RequestAuthInfo(r) if !ok { return nil, nil, common.ErrPerm } st, err := ctxt.stateForRequestUnauthenticated(r) if err != nil { return nil, nil, errors.Trace(err) } defer func() { // Here err is the named return arg. if err != nil { st.Release() } }() return st, authInfo.Entity, nil }
go
func (ctxt *httpContext) stateForRequestAuthenticated(r *http.Request) ( resultSt *state.PooledState, resultEntity state.Entity, err error, ) { authInfo, ok := httpcontext.RequestAuthInfo(r) if !ok { return nil, nil, common.ErrPerm } st, err := ctxt.stateForRequestUnauthenticated(r) if err != nil { return nil, nil, errors.Trace(err) } defer func() { // Here err is the named return arg. if err != nil { st.Release() } }() return st, authInfo.Entity, nil }
[ "func", "(", "ctxt", "*", "httpContext", ")", "stateForRequestAuthenticated", "(", "r", "*", "http", ".", "Request", ")", "(", "resultSt", "*", "state", ".", "PooledState", ",", "resultEntity", "state", ".", "Entity", ",", "err", "error", ",", ")", "{", "authInfo", ",", "ok", ":=", "httpcontext", ".", "RequestAuthInfo", "(", "r", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "nil", ",", "common", ".", "ErrPerm", "\n", "}", "\n", "st", ",", "err", ":=", "ctxt", ".", "stateForRequestUnauthenticated", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "defer", "func", "(", ")", "{", "// Here err is the named return arg.", "if", "err", "!=", "nil", "{", "st", ".", "Release", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "return", "st", ",", "authInfo", ".", "Entity", ",", "nil", "\n", "}" ]
// stateForRequestAuthenticated returns a state instance appropriate for // using for the model implicit in the given request. // It also returns the authenticated entity.
[ "stateForRequestAuthenticated", "returns", "a", "state", "instance", "appropriate", "for", "using", "for", "the", "model", "implicit", "in", "the", "given", "request", ".", "It", "also", "returns", "the", "authenticated", "entity", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/httpcontext.go#L41-L61
155,294
juju/juju
apiserver/httpcontext.go
checkPermissions
func checkPermissions(tag names.Tag, acceptFunc common.GetAuthFunc) (bool, error) { accept, err := acceptFunc() if err != nil { return false, errors.Trace(err) } if accept(tag) { return true, nil } return false, errors.NotValidf("tag kind %v", tag.Kind()) }
go
func checkPermissions(tag names.Tag, acceptFunc common.GetAuthFunc) (bool, error) { accept, err := acceptFunc() if err != nil { return false, errors.Trace(err) } if accept(tag) { return true, nil } return false, errors.NotValidf("tag kind %v", tag.Kind()) }
[ "func", "checkPermissions", "(", "tag", "names", ".", "Tag", ",", "acceptFunc", "common", ".", "GetAuthFunc", ")", "(", "bool", ",", "error", ")", "{", "accept", ",", "err", ":=", "acceptFunc", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "accept", "(", "tag", ")", "{", "return", "true", ",", "nil", "\n", "}", "\n", "return", "false", ",", "errors", ".", "NotValidf", "(", "\"", "\"", ",", "tag", ".", "Kind", "(", ")", ")", "\n", "}" ]
// checkPermissions verifies that given tag passes authentication check. // For example, if only user tags are accepted, all other tags will be denied access.
[ "checkPermissions", "verifies", "that", "given", "tag", "passes", "authentication", "check", ".", "For", "example", "if", "only", "user", "tags", "are", "accepted", "all", "other", "tags", "will", "be", "denied", "access", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/httpcontext.go#L65-L74
155,295
juju/juju
apiserver/httpcontext.go
stateForMigration
func (ctxt *httpContext) stateForMigration( r *http.Request, requiredMode state.MigrationMode, ) (_ *state.PooledState, err error) { modelUUID := r.Header.Get(params.MigrationModelHTTPHeader) migrationSt, err := ctxt.srv.shared.statePool.Get(modelUUID) if err != nil { return nil, errors.Trace(err) } defer func() { // Here err is the named return arg. if err != nil { migrationSt.Release() } }() model, err := migrationSt.Model() if errors.IsNotFound(err) { return nil, errors.Wrap(err, common.UnknownModelError(modelUUID)) } if err != nil { return nil, errors.Trace(err) } if model.MigrationMode() != requiredMode { return nil, errors.BadRequestf( "model migration mode is %q instead of %q", model.MigrationMode(), requiredMode) } return migrationSt, nil }
go
func (ctxt *httpContext) stateForMigration( r *http.Request, requiredMode state.MigrationMode, ) (_ *state.PooledState, err error) { modelUUID := r.Header.Get(params.MigrationModelHTTPHeader) migrationSt, err := ctxt.srv.shared.statePool.Get(modelUUID) if err != nil { return nil, errors.Trace(err) } defer func() { // Here err is the named return arg. if err != nil { migrationSt.Release() } }() model, err := migrationSt.Model() if errors.IsNotFound(err) { return nil, errors.Wrap(err, common.UnknownModelError(modelUUID)) } if err != nil { return nil, errors.Trace(err) } if model.MigrationMode() != requiredMode { return nil, errors.BadRequestf( "model migration mode is %q instead of %q", model.MigrationMode(), requiredMode) } return migrationSt, nil }
[ "func", "(", "ctxt", "*", "httpContext", ")", "stateForMigration", "(", "r", "*", "http", ".", "Request", ",", "requiredMode", "state", ".", "MigrationMode", ",", ")", "(", "_", "*", "state", ".", "PooledState", ",", "err", "error", ")", "{", "modelUUID", ":=", "r", ".", "Header", ".", "Get", "(", "params", ".", "MigrationModelHTTPHeader", ")", "\n", "migrationSt", ",", "err", ":=", "ctxt", ".", "srv", ".", "shared", ".", "statePool", ".", "Get", "(", "modelUUID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "defer", "func", "(", ")", "{", "// Here err is the named return arg.", "if", "err", "!=", "nil", "{", "migrationSt", ".", "Release", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "model", ",", "err", ":=", "migrationSt", ".", "Model", "(", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "common", ".", "UnknownModelError", "(", "modelUUID", ")", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "model", ".", "MigrationMode", "(", ")", "!=", "requiredMode", "{", "return", "nil", ",", "errors", ".", "BadRequestf", "(", "\"", "\"", ",", "model", ".", "MigrationMode", "(", ")", ",", "requiredMode", ")", "\n", "}", "\n", "return", "migrationSt", ",", "nil", "\n", "}" ]
// stateForMigration asserts that the incoming connection is from a user that // has admin permissions on the controller model. The method also gets the // model uuid for the model being migrated from a request header, and returns // the state instance for that model.
[ "stateForMigration", "asserts", "that", "the", "incoming", "connection", "is", "from", "a", "user", "that", "has", "admin", "permissions", "on", "the", "controller", "model", ".", "The", "method", "also", "gets", "the", "model", "uuid", "for", "the", "model", "being", "migrated", "from", "a", "request", "header", "and", "returns", "the", "state", "instance", "for", "that", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/httpcontext.go#L80-L107
155,296
juju/juju
apiserver/httpcontext.go
stateForRequestAuthenticatedUser
func (ctxt *httpContext) stateForRequestAuthenticatedUser(r *http.Request) (*state.PooledState, error) { st, _, err := ctxt.stateAndEntityForRequestAuthenticatedUser(r) return st, err }
go
func (ctxt *httpContext) stateForRequestAuthenticatedUser(r *http.Request) (*state.PooledState, error) { st, _, err := ctxt.stateAndEntityForRequestAuthenticatedUser(r) return st, err }
[ "func", "(", "ctxt", "*", "httpContext", ")", "stateForRequestAuthenticatedUser", "(", "r", "*", "http", ".", "Request", ")", "(", "*", "state", ".", "PooledState", ",", "error", ")", "{", "st", ",", "_", ",", "err", ":=", "ctxt", ".", "stateAndEntityForRequestAuthenticatedUser", "(", "r", ")", "\n", "return", "st", ",", "err", "\n", "}" ]
// stateForRequestAuthenticatedUser is like stateAndEntityForRequestAuthenticatedUser // but doesn't return the entity.
[ "stateForRequestAuthenticatedUser", "is", "like", "stateAndEntityForRequestAuthenticatedUser", "but", "doesn", "t", "return", "the", "entity", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/httpcontext.go#L115-L118
155,297
juju/juju
apiserver/httpcontext.go
stateAndEntityForRequestAuthenticatedUser
func (ctxt *httpContext) stateAndEntityForRequestAuthenticatedUser(r *http.Request) ( *state.PooledState, state.Entity, error, ) { return ctxt.stateForRequestAuthenticatedTag(r, names.UserTagKind) }
go
func (ctxt *httpContext) stateAndEntityForRequestAuthenticatedUser(r *http.Request) ( *state.PooledState, state.Entity, error, ) { return ctxt.stateForRequestAuthenticatedTag(r, names.UserTagKind) }
[ "func", "(", "ctxt", "*", "httpContext", ")", "stateAndEntityForRequestAuthenticatedUser", "(", "r", "*", "http", ".", "Request", ")", "(", "*", "state", ".", "PooledState", ",", "state", ".", "Entity", ",", "error", ",", ")", "{", "return", "ctxt", ".", "stateForRequestAuthenticatedTag", "(", "r", ",", "names", ".", "UserTagKind", ")", "\n", "}" ]
// stateAndEntityForRequestAuthenticatedUser is like stateForRequestAuthenticated // except that it also verifies that the authenticated entity is a user.
[ "stateAndEntityForRequestAuthenticatedUser", "is", "like", "stateForRequestAuthenticated", "except", "that", "it", "also", "verifies", "that", "the", "authenticated", "entity", "is", "a", "user", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/httpcontext.go#L122-L126
155,298
juju/juju
apiserver/httpcontext.go
stateForRequestAuthenticatedAgent
func (ctxt *httpContext) stateForRequestAuthenticatedAgent(r *http.Request) ( *state.PooledState, state.Entity, error, ) { return ctxt.stateForRequestAuthenticatedTag(r, names.MachineTagKind, names.UnitTagKind, names.ApplicationTagKind) }
go
func (ctxt *httpContext) stateForRequestAuthenticatedAgent(r *http.Request) ( *state.PooledState, state.Entity, error, ) { return ctxt.stateForRequestAuthenticatedTag(r, names.MachineTagKind, names.UnitTagKind, names.ApplicationTagKind) }
[ "func", "(", "ctxt", "*", "httpContext", ")", "stateForRequestAuthenticatedAgent", "(", "r", "*", "http", ".", "Request", ")", "(", "*", "state", ".", "PooledState", ",", "state", ".", "Entity", ",", "error", ",", ")", "{", "return", "ctxt", ".", "stateForRequestAuthenticatedTag", "(", "r", ",", "names", ".", "MachineTagKind", ",", "names", ".", "UnitTagKind", ",", "names", ".", "ApplicationTagKind", ")", "\n", "}" ]
// stateForRequestAuthenticatedAgent is like stateForRequestAuthenticated // except that it also verifies that the authenticated entity is an agent.
[ "stateForRequestAuthenticatedAgent", "is", "like", "stateForRequestAuthenticated", "except", "that", "it", "also", "verifies", "that", "the", "authenticated", "entity", "is", "an", "agent", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/httpcontext.go#L130-L134
155,299
juju/juju
apiserver/httpcontext.go
stateForRequestAuthenticatedTag
func (ctxt *httpContext) stateForRequestAuthenticatedTag(r *http.Request, kinds ...string) ( *state.PooledState, state.Entity, error, ) { funcs := make([]common.GetAuthFunc, len(kinds)) for i, kind := range kinds { funcs[i] = common.AuthFuncForTagKind(kind) } st, entity, err := ctxt.stateForRequestAuthenticated(r) if err != nil { return nil, nil, errors.Trace(err) } if ok, err := checkPermissions(entity.Tag(), common.AuthAny(funcs...)); !ok { st.Release() return nil, nil, err } return st, entity, nil }
go
func (ctxt *httpContext) stateForRequestAuthenticatedTag(r *http.Request, kinds ...string) ( *state.PooledState, state.Entity, error, ) { funcs := make([]common.GetAuthFunc, len(kinds)) for i, kind := range kinds { funcs[i] = common.AuthFuncForTagKind(kind) } st, entity, err := ctxt.stateForRequestAuthenticated(r) if err != nil { return nil, nil, errors.Trace(err) } if ok, err := checkPermissions(entity.Tag(), common.AuthAny(funcs...)); !ok { st.Release() return nil, nil, err } return st, entity, nil }
[ "func", "(", "ctxt", "*", "httpContext", ")", "stateForRequestAuthenticatedTag", "(", "r", "*", "http", ".", "Request", ",", "kinds", "...", "string", ")", "(", "*", "state", ".", "PooledState", ",", "state", ".", "Entity", ",", "error", ",", ")", "{", "funcs", ":=", "make", "(", "[", "]", "common", ".", "GetAuthFunc", ",", "len", "(", "kinds", ")", ")", "\n", "for", "i", ",", "kind", ":=", "range", "kinds", "{", "funcs", "[", "i", "]", "=", "common", ".", "AuthFuncForTagKind", "(", "kind", ")", "\n", "}", "\n", "st", ",", "entity", ",", "err", ":=", "ctxt", ".", "stateForRequestAuthenticated", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "ok", ",", "err", ":=", "checkPermissions", "(", "entity", ".", "Tag", "(", ")", ",", "common", ".", "AuthAny", "(", "funcs", "...", ")", ")", ";", "!", "ok", "{", "st", ".", "Release", "(", ")", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "return", "st", ",", "entity", ",", "nil", "\n", "}" ]
// stateForRequestAuthenticatedTag checks that the request is // correctly authenticated, and that the authenticated entity making // the request is of one of the specified kinds.
[ "stateForRequestAuthenticatedTag", "checks", "that", "the", "request", "is", "correctly", "authenticated", "and", "that", "the", "authenticated", "entity", "making", "the", "request", "is", "of", "one", "of", "the", "specified", "kinds", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/httpcontext.go#L139-L155