id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
3,900
juju/juju
caas/kubernetes/provider/k8s.go
Destroy
func (k *kubernetesClient) Destroy(callbacks context.ProviderCallContext) error { watcher, err := k.WatchNamespace() if err != nil { return errors.Trace(err) } defer watcher.Kill() if err := k.deleteNamespace(); err != nil { return errors.Annotate(err, "deleting model namespace") } // Delete any storage classes created as part of this model. // Storage classes live outside the namespace so need to be deleted separately. modelSelector := fmt.Sprintf("%s==%s", labelModel, k.namespace) err = k.client().StorageV1().StorageClasses().DeleteCollection(&v1.DeleteOptions{ PropagationPolicy: &defaultPropagationPolicy, }, v1.ListOptions{ LabelSelector: modelSelector, }) if err != nil && !k8serrors.IsNotFound(err) { return errors.Annotate(err, "deleting model storage classes") } for { select { case <-callbacks.Dying(): return nil case <-watcher.Changes(): // ensure namespace has been deleted - notfound error expected. _, err := k.GetNamespace(k.namespace) if errors.IsNotFound(err) { // namespace ha been deleted. return nil } if err != nil { return errors.Trace(err) } logger.Debugf("namespace %q is still been terminating", k.namespace) } } }
go
func (k *kubernetesClient) Destroy(callbacks context.ProviderCallContext) error { watcher, err := k.WatchNamespace() if err != nil { return errors.Trace(err) } defer watcher.Kill() if err := k.deleteNamespace(); err != nil { return errors.Annotate(err, "deleting model namespace") } // Delete any storage classes created as part of this model. // Storage classes live outside the namespace so need to be deleted separately. modelSelector := fmt.Sprintf("%s==%s", labelModel, k.namespace) err = k.client().StorageV1().StorageClasses().DeleteCollection(&v1.DeleteOptions{ PropagationPolicy: &defaultPropagationPolicy, }, v1.ListOptions{ LabelSelector: modelSelector, }) if err != nil && !k8serrors.IsNotFound(err) { return errors.Annotate(err, "deleting model storage classes") } for { select { case <-callbacks.Dying(): return nil case <-watcher.Changes(): // ensure namespace has been deleted - notfound error expected. _, err := k.GetNamespace(k.namespace) if errors.IsNotFound(err) { // namespace ha been deleted. return nil } if err != nil { return errors.Trace(err) } logger.Debugf("namespace %q is still been terminating", k.namespace) } } }
[ "func", "(", "k", "*", "kubernetesClient", ")", "Destroy", "(", "callbacks", "context", ".", "ProviderCallContext", ")", "error", "{", "watcher", ",", "err", ":=", "k", ".", "WatchNamespace", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "defer", "watcher", ".", "Kill", "(", ")", "\n\n", "if", "err", ":=", "k", ".", "deleteNamespace", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Delete any storage classes created as part of this model.", "// Storage classes live outside the namespace so need to be deleted separately.", "modelSelector", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "labelModel", ",", "k", ".", "namespace", ")", "\n", "err", "=", "k", ".", "client", "(", ")", ".", "StorageV1", "(", ")", ".", "StorageClasses", "(", ")", ".", "DeleteCollection", "(", "&", "v1", ".", "DeleteOptions", "{", "PropagationPolicy", ":", "&", "defaultPropagationPolicy", ",", "}", ",", "v1", ".", "ListOptions", "{", "LabelSelector", ":", "modelSelector", ",", "}", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "k8serrors", ".", "IsNotFound", "(", "err", ")", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "for", "{", "select", "{", "case", "<-", "callbacks", ".", "Dying", "(", ")", ":", "return", "nil", "\n", "case", "<-", "watcher", ".", "Changes", "(", ")", ":", "// ensure namespace has been deleted - notfound error expected.", "_", ",", "err", ":=", "k", ".", "GetNamespace", "(", "k", ".", "namespace", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "// namespace ha been deleted.", "return", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "k", ".", "namespace", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Destroy is part of the Broker interface.
[ "Destroy", "is", "part", "of", "the", "Broker", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L379-L418
3,901
juju/juju
caas/kubernetes/provider/k8s.go
APIVersion
func (k *kubernetesClient) APIVersion() (string, error) { body, err := k.client().CoreV1().RESTClient().Get().AbsPath("/version").Do().Raw() if err != nil { return "", err } var info apimachineryversion.Info err = json.Unmarshal(body, &info) if err != nil { return "", errors.Annotatef(err, "got '%s' querying API version", string(body)) } version := info.GitVersion // git version is "vX.Y.Z", strip the "v" version = strings.Trim(version, "v") return version, nil }
go
func (k *kubernetesClient) APIVersion() (string, error) { body, err := k.client().CoreV1().RESTClient().Get().AbsPath("/version").Do().Raw() if err != nil { return "", err } var info apimachineryversion.Info err = json.Unmarshal(body, &info) if err != nil { return "", errors.Annotatef(err, "got '%s' querying API version", string(body)) } version := info.GitVersion // git version is "vX.Y.Z", strip the "v" version = strings.Trim(version, "v") return version, nil }
[ "func", "(", "k", "*", "kubernetesClient", ")", "APIVersion", "(", ")", "(", "string", ",", "error", ")", "{", "body", ",", "err", ":=", "k", ".", "client", "(", ")", ".", "CoreV1", "(", ")", ".", "RESTClient", "(", ")", ".", "Get", "(", ")", ".", "AbsPath", "(", "\"", "\"", ")", ".", "Do", "(", ")", ".", "Raw", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "var", "info", "apimachineryversion", ".", "Info", "\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "&", "info", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "string", "(", "body", ")", ")", "\n", "}", "\n", "version", ":=", "info", ".", "GitVersion", "\n", "// git version is \"vX.Y.Z\", strip the \"v\"", "version", "=", "strings", ".", "Trim", "(", "version", ",", "\"", "\"", ")", "\n", "return", "version", ",", "nil", "\n", "}" ]
// APIVersion returns the version info for the cluster.
[ "APIVersion", "returns", "the", "version", "info", "for", "the", "cluster", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L421-L435
3,902
juju/juju
caas/kubernetes/provider/k8s.go
ensureOCIImageSecret
func (k *kubernetesClient) ensureOCIImageSecret( imageSecretName, appName string, imageDetails *caas.ImageDetails, annotations k8sannotations.Annotation, ) error { if imageDetails.Password == "" { return errors.New("attempting to create a secret with no password") } secretData, err := createDockerConfigJSON(imageDetails) if err != nil { return errors.Trace(err) } newSecret := &core.Secret{ ObjectMeta: v1.ObjectMeta{ Name: imageSecretName, Namespace: k.namespace, Labels: map[string]string{labelApplication: appName}, Annotations: annotations.ToMap()}, Type: core.SecretTypeDockerConfigJson, Data: map[string][]byte{ core.DockerConfigJsonKey: secretData, }, } return errors.Trace(k.ensureSecret(newSecret)) }
go
func (k *kubernetesClient) ensureOCIImageSecret( imageSecretName, appName string, imageDetails *caas.ImageDetails, annotations k8sannotations.Annotation, ) error { if imageDetails.Password == "" { return errors.New("attempting to create a secret with no password") } secretData, err := createDockerConfigJSON(imageDetails) if err != nil { return errors.Trace(err) } newSecret := &core.Secret{ ObjectMeta: v1.ObjectMeta{ Name: imageSecretName, Namespace: k.namespace, Labels: map[string]string{labelApplication: appName}, Annotations: annotations.ToMap()}, Type: core.SecretTypeDockerConfigJson, Data: map[string][]byte{ core.DockerConfigJsonKey: secretData, }, } return errors.Trace(k.ensureSecret(newSecret)) }
[ "func", "(", "k", "*", "kubernetesClient", ")", "ensureOCIImageSecret", "(", "imageSecretName", ",", "appName", "string", ",", "imageDetails", "*", "caas", ".", "ImageDetails", ",", "annotations", "k8sannotations", ".", "Annotation", ",", ")", "error", "{", "if", "imageDetails", ".", "Password", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "secretData", ",", "err", ":=", "createDockerConfigJSON", "(", "imageDetails", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "newSecret", ":=", "&", "core", ".", "Secret", "{", "ObjectMeta", ":", "v1", ".", "ObjectMeta", "{", "Name", ":", "imageSecretName", ",", "Namespace", ":", "k", ".", "namespace", ",", "Labels", ":", "map", "[", "string", "]", "string", "{", "labelApplication", ":", "appName", "}", ",", "Annotations", ":", "annotations", ".", "ToMap", "(", ")", "}", ",", "Type", ":", "core", ".", "SecretTypeDockerConfigJson", ",", "Data", ":", "map", "[", "string", "]", "[", "]", "byte", "{", "core", ".", "DockerConfigJsonKey", ":", "secretData", ",", "}", ",", "}", "\n", "return", "errors", ".", "Trace", "(", "k", ".", "ensureSecret", "(", "newSecret", ")", ")", "\n", "}" ]
// ensureOCIImageSecret ensures a secret exists for use with retrieving images from private registries
[ "ensureOCIImageSecret", "ensures", "a", "secret", "exists", "for", "use", "with", "retrieving", "images", "from", "private", "registries" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L438-L464
3,903
juju/juju
caas/kubernetes/provider/k8s.go
updateSecret
func (k *kubernetesClient) updateSecret(sec *core.Secret) error { _, err := k.client().CoreV1().Secrets(k.namespace).Update(sec) return errors.Trace(err) }
go
func (k *kubernetesClient) updateSecret(sec *core.Secret) error { _, err := k.client().CoreV1().Secrets(k.namespace).Update(sec) return errors.Trace(err) }
[ "func", "(", "k", "*", "kubernetesClient", ")", "updateSecret", "(", "sec", "*", "core", ".", "Secret", ")", "error", "{", "_", ",", "err", ":=", "k", ".", "client", "(", ")", ".", "CoreV1", "(", ")", ".", "Secrets", "(", "k", ".", "namespace", ")", ".", "Update", "(", "sec", ")", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// updateSecret updates a secret resource.
[ "updateSecret", "updates", "a", "secret", "resource", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L476-L479
3,904
juju/juju
caas/kubernetes/provider/k8s.go
getSecret
func (k *kubernetesClient) getSecret(secretName string) (*core.Secret, error) { secret, err := k.client().CoreV1().Secrets(k.namespace).Get(secretName, v1.GetOptions{IncludeUninitialized: true}) if err != nil { if k8serrors.IsNotFound(err) { return nil, errors.NotFoundf("secret %q", secretName) } return nil, errors.Trace(err) } return secret, nil }
go
func (k *kubernetesClient) getSecret(secretName string) (*core.Secret, error) { secret, err := k.client().CoreV1().Secrets(k.namespace).Get(secretName, v1.GetOptions{IncludeUninitialized: true}) if err != nil { if k8serrors.IsNotFound(err) { return nil, errors.NotFoundf("secret %q", secretName) } return nil, errors.Trace(err) } return secret, nil }
[ "func", "(", "k", "*", "kubernetesClient", ")", "getSecret", "(", "secretName", "string", ")", "(", "*", "core", ".", "Secret", ",", "error", ")", "{", "secret", ",", "err", ":=", "k", ".", "client", "(", ")", ".", "CoreV1", "(", ")", ".", "Secrets", "(", "k", ".", "namespace", ")", ".", "Get", "(", "secretName", ",", "v1", ".", "GetOptions", "{", "IncludeUninitialized", ":", "true", "}", ")", "\n", "if", "err", "!=", "nil", "{", "if", "k8serrors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "secretName", ")", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "secret", ",", "nil", "\n", "}" ]
// getSecret return a secret resource.
[ "getSecret", "return", "a", "secret", "resource", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L482-L491
3,905
juju/juju
caas/kubernetes/provider/k8s.go
createSecret
func (k *kubernetesClient) createSecret(secret *core.Secret) error { _, err := k.client().CoreV1().Secrets(k.namespace).Create(secret) return errors.Trace(err) }
go
func (k *kubernetesClient) createSecret(secret *core.Secret) error { _, err := k.client().CoreV1().Secrets(k.namespace).Create(secret) return errors.Trace(err) }
[ "func", "(", "k", "*", "kubernetesClient", ")", "createSecret", "(", "secret", "*", "core", ".", "Secret", ")", "error", "{", "_", ",", "err", ":=", "k", ".", "client", "(", ")", ".", "CoreV1", "(", ")", ".", "Secrets", "(", "k", ".", "namespace", ")", ".", "Create", "(", "secret", ")", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// createSecret creates a secret resource.
[ "createSecret", "creates", "a", "secret", "resource", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L494-L497
3,906
juju/juju
caas/kubernetes/provider/k8s.go
deleteSecret
func (k *kubernetesClient) deleteSecret(secretName string) error { secrets := k.client().CoreV1().Secrets(k.namespace) err := secrets.Delete(secretName, &v1.DeleteOptions{ PropagationPolicy: &defaultPropagationPolicy, }) if k8serrors.IsNotFound(err) { return nil } return errors.Trace(err) }
go
func (k *kubernetesClient) deleteSecret(secretName string) error { secrets := k.client().CoreV1().Secrets(k.namespace) err := secrets.Delete(secretName, &v1.DeleteOptions{ PropagationPolicy: &defaultPropagationPolicy, }) if k8serrors.IsNotFound(err) { return nil } return errors.Trace(err) }
[ "func", "(", "k", "*", "kubernetesClient", ")", "deleteSecret", "(", "secretName", "string", ")", "error", "{", "secrets", ":=", "k", ".", "client", "(", ")", ".", "CoreV1", "(", ")", ".", "Secrets", "(", "k", ".", "namespace", ")", "\n", "err", ":=", "secrets", ".", "Delete", "(", "secretName", ",", "&", "v1", ".", "DeleteOptions", "{", "PropagationPolicy", ":", "&", "defaultPropagationPolicy", ",", "}", ")", "\n", "if", "k8serrors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// deleteSecret deletes a secret resource.
[ "deleteSecret", "deletes", "a", "secret", "resource", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L500-L509
3,907
juju/juju
caas/kubernetes/provider/k8s.go
OperatorExists
func (k *kubernetesClient) OperatorExists(appName string) (caas.OperatorState, error) { var result caas.OperatorState statefulsets := k.client().AppsV1().StatefulSets(k.namespace) operator, err := statefulsets.Get(k.operatorName(appName), v1.GetOptions{IncludeUninitialized: true}) if k8serrors.IsNotFound(err) { return result, nil } if err != nil { return result, errors.Trace(err) } result.Exists = true result.Terminating = operator.DeletionTimestamp != nil return result, nil }
go
func (k *kubernetesClient) OperatorExists(appName string) (caas.OperatorState, error) { var result caas.OperatorState statefulsets := k.client().AppsV1().StatefulSets(k.namespace) operator, err := statefulsets.Get(k.operatorName(appName), v1.GetOptions{IncludeUninitialized: true}) if k8serrors.IsNotFound(err) { return result, nil } if err != nil { return result, errors.Trace(err) } result.Exists = true result.Terminating = operator.DeletionTimestamp != nil return result, nil }
[ "func", "(", "k", "*", "kubernetesClient", ")", "OperatorExists", "(", "appName", "string", ")", "(", "caas", ".", "OperatorState", ",", "error", ")", "{", "var", "result", "caas", ".", "OperatorState", "\n\n", "statefulsets", ":=", "k", ".", "client", "(", ")", ".", "AppsV1", "(", ")", ".", "StatefulSets", "(", "k", ".", "namespace", ")", "\n", "operator", ",", "err", ":=", "statefulsets", ".", "Get", "(", "k", ".", "operatorName", "(", "appName", ")", ",", "v1", ".", "GetOptions", "{", "IncludeUninitialized", ":", "true", "}", ")", "\n", "if", "k8serrors", ".", "IsNotFound", "(", "err", ")", "{", "return", "result", ",", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "result", ".", "Exists", "=", "true", "\n", "result", ".", "Terminating", "=", "operator", ".", "DeletionTimestamp", "!=", "nil", "\n", "return", "result", ",", "nil", "\n", "}" ]
// OperatorExists indicates if the operator for the specified // application exists, and whether the operator is terminating.
[ "OperatorExists", "indicates", "if", "the", "operator", "for", "the", "specified", "application", "exists", "and", "whether", "the", "operator", "is", "terminating", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L513-L527
3,908
juju/juju
caas/kubernetes/provider/k8s.go
ValidateStorageClass
func (k *kubernetesClient) ValidateStorageClass(config map[string]interface{}) error { cfg, err := newStorageConfig(config) if err != nil { return errors.Trace(err) } sc, err := k.getStorageClass(cfg.storageClass) if err != nil { return errors.NewNotValid(err, fmt.Sprintf("storage class %q", cfg.storageClass)) } if cfg.storageProvisioner == "" { return nil } if sc.Provisioner != cfg.storageProvisioner { return errors.NewNotValid( nil, fmt.Sprintf("storage class %q has provisoner %q, not %q", cfg.storageClass, sc.Provisioner, cfg.storageProvisioner)) } return nil }
go
func (k *kubernetesClient) ValidateStorageClass(config map[string]interface{}) error { cfg, err := newStorageConfig(config) if err != nil { return errors.Trace(err) } sc, err := k.getStorageClass(cfg.storageClass) if err != nil { return errors.NewNotValid(err, fmt.Sprintf("storage class %q", cfg.storageClass)) } if cfg.storageProvisioner == "" { return nil } if sc.Provisioner != cfg.storageProvisioner { return errors.NewNotValid( nil, fmt.Sprintf("storage class %q has provisoner %q, not %q", cfg.storageClass, sc.Provisioner, cfg.storageProvisioner)) } return nil }
[ "func", "(", "k", "*", "kubernetesClient", ")", "ValidateStorageClass", "(", "config", "map", "[", "string", "]", "interface", "{", "}", ")", "error", "{", "cfg", ",", "err", ":=", "newStorageConfig", "(", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "sc", ",", "err", ":=", "k", ".", "getStorageClass", "(", "cfg", ".", "storageClass", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "NewNotValid", "(", "err", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cfg", ".", "storageClass", ")", ")", "\n", "}", "\n", "if", "cfg", ".", "storageProvisioner", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n", "if", "sc", ".", "Provisioner", "!=", "cfg", ".", "storageProvisioner", "{", "return", "errors", ".", "NewNotValid", "(", "nil", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cfg", ".", "storageClass", ",", "sc", ".", "Provisioner", ",", "cfg", ".", "storageProvisioner", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ValidateStorageClass returns an error if the storage config is not valid.
[ "ValidateStorageClass", "returns", "an", "error", "if", "the", "storage", "config", "is", "not", "valid", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L638-L656
3,909
juju/juju
caas/kubernetes/provider/k8s.go
maybeGetVolumeClaimSpec
func (k *kubernetesClient) maybeGetVolumeClaimSpec(params volumeParams) (*core.PersistentVolumeClaimSpec, error) { storageClassName := params.storageConfig.storageClass haveStorageClass := false if storageClassName == "" { return nil, errors.New("cannot create a volume claim spec without a storage class") } // See if the requested storage class exists already. sc, err := k.getStorageClass(storageClassName) if err != nil && !k8serrors.IsNotFound(err) { return nil, errors.Annotatef(err, "looking for storage class %q", storageClassName) } if err == nil { haveStorageClass = true storageClassName = sc.Name } if !haveStorageClass { params.storageConfig.storageClass = storageClassName sc, err := k.EnsureStorageProvisioner(caas.StorageProvisioner{ Name: params.storageConfig.storageClass, Namespace: k.namespace, Provisioner: params.storageConfig.storageProvisioner, Parameters: params.storageConfig.parameters, ReclaimPolicy: string(params.storageConfig.reclaimPolicy), }) if err != nil && !errors.IsNotFound(err) { return nil, errors.Trace(err) } if err == nil { haveStorageClass = true storageClassName = sc.Name } } if !haveStorageClass { return nil, errors.NewNotFound(nil, fmt.Sprintf( "cannot create persistent volume as storage class %q cannot be found", storageClassName)) } accessMode := params.accessMode if accessMode == "" { accessMode = core.ReadWriteOnce } return &core.PersistentVolumeClaimSpec{ StorageClassName: &storageClassName, Resources: core.ResourceRequirements{ Requests: core.ResourceList{ core.ResourceStorage: params.requestedVolumeSize, }, }, AccessModes: []core.PersistentVolumeAccessMode{accessMode}, }, nil }
go
func (k *kubernetesClient) maybeGetVolumeClaimSpec(params volumeParams) (*core.PersistentVolumeClaimSpec, error) { storageClassName := params.storageConfig.storageClass haveStorageClass := false if storageClassName == "" { return nil, errors.New("cannot create a volume claim spec without a storage class") } // See if the requested storage class exists already. sc, err := k.getStorageClass(storageClassName) if err != nil && !k8serrors.IsNotFound(err) { return nil, errors.Annotatef(err, "looking for storage class %q", storageClassName) } if err == nil { haveStorageClass = true storageClassName = sc.Name } if !haveStorageClass { params.storageConfig.storageClass = storageClassName sc, err := k.EnsureStorageProvisioner(caas.StorageProvisioner{ Name: params.storageConfig.storageClass, Namespace: k.namespace, Provisioner: params.storageConfig.storageProvisioner, Parameters: params.storageConfig.parameters, ReclaimPolicy: string(params.storageConfig.reclaimPolicy), }) if err != nil && !errors.IsNotFound(err) { return nil, errors.Trace(err) } if err == nil { haveStorageClass = true storageClassName = sc.Name } } if !haveStorageClass { return nil, errors.NewNotFound(nil, fmt.Sprintf( "cannot create persistent volume as storage class %q cannot be found", storageClassName)) } accessMode := params.accessMode if accessMode == "" { accessMode = core.ReadWriteOnce } return &core.PersistentVolumeClaimSpec{ StorageClassName: &storageClassName, Resources: core.ResourceRequirements{ Requests: core.ResourceList{ core.ResourceStorage: params.requestedVolumeSize, }, }, AccessModes: []core.PersistentVolumeAccessMode{accessMode}, }, nil }
[ "func", "(", "k", "*", "kubernetesClient", ")", "maybeGetVolumeClaimSpec", "(", "params", "volumeParams", ")", "(", "*", "core", ".", "PersistentVolumeClaimSpec", ",", "error", ")", "{", "storageClassName", ":=", "params", ".", "storageConfig", ".", "storageClass", "\n", "haveStorageClass", ":=", "false", "\n", "if", "storageClassName", "==", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "// See if the requested storage class exists already.", "sc", ",", "err", ":=", "k", ".", "getStorageClass", "(", "storageClassName", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "k8serrors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "storageClassName", ")", "\n", "}", "\n", "if", "err", "==", "nil", "{", "haveStorageClass", "=", "true", "\n", "storageClassName", "=", "sc", ".", "Name", "\n", "}", "\n", "if", "!", "haveStorageClass", "{", "params", ".", "storageConfig", ".", "storageClass", "=", "storageClassName", "\n", "sc", ",", "err", ":=", "k", ".", "EnsureStorageProvisioner", "(", "caas", ".", "StorageProvisioner", "{", "Name", ":", "params", ".", "storageConfig", ".", "storageClass", ",", "Namespace", ":", "k", ".", "namespace", ",", "Provisioner", ":", "params", ".", "storageConfig", ".", "storageProvisioner", ",", "Parameters", ":", "params", ".", "storageConfig", ".", "parameters", ",", "ReclaimPolicy", ":", "string", "(", "params", ".", "storageConfig", ".", "reclaimPolicy", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", "==", "nil", "{", "haveStorageClass", "=", "true", "\n", "storageClassName", "=", "sc", ".", "Name", "\n", "}", "\n", "}", "\n", "if", "!", "haveStorageClass", "{", "return", "nil", ",", "errors", ".", "NewNotFound", "(", "nil", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "storageClassName", ")", ")", "\n", "}", "\n", "accessMode", ":=", "params", ".", "accessMode", "\n", "if", "accessMode", "==", "\"", "\"", "{", "accessMode", "=", "core", ".", "ReadWriteOnce", "\n", "}", "\n", "return", "&", "core", ".", "PersistentVolumeClaimSpec", "{", "StorageClassName", ":", "&", "storageClassName", ",", "Resources", ":", "core", ".", "ResourceRequirements", "{", "Requests", ":", "core", ".", "ResourceList", "{", "core", ".", "ResourceStorage", ":", "params", ".", "requestedVolumeSize", ",", "}", ",", "}", ",", "AccessModes", ":", "[", "]", "core", ".", "PersistentVolumeAccessMode", "{", "accessMode", "}", ",", "}", ",", "nil", "\n", "}" ]
// maybeGetVolumeClaimSpec returns a persistent volume claim spec for the given // parameters. If no suitable storage class is available, return a NotFound error.
[ "maybeGetVolumeClaimSpec", "returns", "a", "persistent", "volume", "claim", "spec", "for", "the", "given", "parameters", ".", "If", "no", "suitable", "storage", "class", "is", "available", "return", "a", "NotFound", "error", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L667-L716
3,910
juju/juju
caas/kubernetes/provider/k8s.go
getStorageClass
func (k *kubernetesClient) getStorageClass(name string) (*k8sstorage.StorageClass, error) { storageClasses := k.client().StorageV1().StorageClasses() qualifiedName := qualifiedStorageClassName(k.namespace, name) sc, err := storageClasses.Get(qualifiedName, v1.GetOptions{}) if err == nil { return sc, nil } if !k8serrors.IsNotFound(err) { return nil, errors.Trace(err) } return storageClasses.Get(name, v1.GetOptions{}) }
go
func (k *kubernetesClient) getStorageClass(name string) (*k8sstorage.StorageClass, error) { storageClasses := k.client().StorageV1().StorageClasses() qualifiedName := qualifiedStorageClassName(k.namespace, name) sc, err := storageClasses.Get(qualifiedName, v1.GetOptions{}) if err == nil { return sc, nil } if !k8serrors.IsNotFound(err) { return nil, errors.Trace(err) } return storageClasses.Get(name, v1.GetOptions{}) }
[ "func", "(", "k", "*", "kubernetesClient", ")", "getStorageClass", "(", "name", "string", ")", "(", "*", "k8sstorage", ".", "StorageClass", ",", "error", ")", "{", "storageClasses", ":=", "k", ".", "client", "(", ")", ".", "StorageV1", "(", ")", ".", "StorageClasses", "(", ")", "\n", "qualifiedName", ":=", "qualifiedStorageClassName", "(", "k", ".", "namespace", ",", "name", ")", "\n", "sc", ",", "err", ":=", "storageClasses", ".", "Get", "(", "qualifiedName", ",", "v1", ".", "GetOptions", "{", "}", ")", "\n", "if", "err", "==", "nil", "{", "return", "sc", ",", "nil", "\n", "}", "\n", "if", "!", "k8serrors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "storageClasses", ".", "Get", "(", "name", ",", "v1", ".", "GetOptions", "{", "}", ")", "\n", "}" ]
// getStorageClass returns a named storage class, first looking for // one which is qualified by the current namespace if it's available.
[ "getStorageClass", "returns", "a", "named", "storage", "class", "first", "looking", "for", "one", "which", "is", "qualified", "by", "the", "current", "namespace", "if", "it", "s", "available", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L720-L731
3,911
juju/juju
caas/kubernetes/provider/k8s.go
EnsureStorageProvisioner
func (k *kubernetesClient) EnsureStorageProvisioner(cfg caas.StorageProvisioner) (*caas.StorageProvisioner, error) { // First see if the named storage class exists. sc, err := k.getStorageClass(cfg.Name) if err == nil { return &caas.StorageProvisioner{ Name: sc.Name, Provisioner: sc.Provisioner, Parameters: sc.Parameters, }, nil } if !k8serrors.IsNotFound(err) { return nil, errors.Annotatef(err, "getting storage class %q", cfg.Name) } // If it's not found but there's no provisioner specified, we can't // create it so just return not found. if cfg.Provisioner == "" { return nil, errors.NewNotFound(nil, fmt.Sprintf("storage class %q doesn't exist, but no storage provisioner has been specified", cfg.Name)) } // Create the storage class with the specified provisioner. var reclaimPolicy *core.PersistentVolumeReclaimPolicy if cfg.ReclaimPolicy != "" { policy := core.PersistentVolumeReclaimPolicy(cfg.ReclaimPolicy) reclaimPolicy = &policy } storageClasses := k.client().StorageV1().StorageClasses() sc = &k8sstorage.StorageClass{ ObjectMeta: v1.ObjectMeta{ Name: qualifiedStorageClassName(cfg.Namespace, cfg.Name), }, Provisioner: cfg.Provisioner, ReclaimPolicy: reclaimPolicy, Parameters: cfg.Parameters, } if cfg.Namespace != "" { sc.Labels = map[string]string{labelModel: k.namespace} } _, err = storageClasses.Create(sc) if err != nil { return nil, errors.Annotatef(err, "creating storage class %q", cfg.Name) } return &caas.StorageProvisioner{ Name: sc.Name, Provisioner: sc.Provisioner, Parameters: sc.Parameters, }, nil }
go
func (k *kubernetesClient) EnsureStorageProvisioner(cfg caas.StorageProvisioner) (*caas.StorageProvisioner, error) { // First see if the named storage class exists. sc, err := k.getStorageClass(cfg.Name) if err == nil { return &caas.StorageProvisioner{ Name: sc.Name, Provisioner: sc.Provisioner, Parameters: sc.Parameters, }, nil } if !k8serrors.IsNotFound(err) { return nil, errors.Annotatef(err, "getting storage class %q", cfg.Name) } // If it's not found but there's no provisioner specified, we can't // create it so just return not found. if cfg.Provisioner == "" { return nil, errors.NewNotFound(nil, fmt.Sprintf("storage class %q doesn't exist, but no storage provisioner has been specified", cfg.Name)) } // Create the storage class with the specified provisioner. var reclaimPolicy *core.PersistentVolumeReclaimPolicy if cfg.ReclaimPolicy != "" { policy := core.PersistentVolumeReclaimPolicy(cfg.ReclaimPolicy) reclaimPolicy = &policy } storageClasses := k.client().StorageV1().StorageClasses() sc = &k8sstorage.StorageClass{ ObjectMeta: v1.ObjectMeta{ Name: qualifiedStorageClassName(cfg.Namespace, cfg.Name), }, Provisioner: cfg.Provisioner, ReclaimPolicy: reclaimPolicy, Parameters: cfg.Parameters, } if cfg.Namespace != "" { sc.Labels = map[string]string{labelModel: k.namespace} } _, err = storageClasses.Create(sc) if err != nil { return nil, errors.Annotatef(err, "creating storage class %q", cfg.Name) } return &caas.StorageProvisioner{ Name: sc.Name, Provisioner: sc.Provisioner, Parameters: sc.Parameters, }, nil }
[ "func", "(", "k", "*", "kubernetesClient", ")", "EnsureStorageProvisioner", "(", "cfg", "caas", ".", "StorageProvisioner", ")", "(", "*", "caas", ".", "StorageProvisioner", ",", "error", ")", "{", "// First see if the named storage class exists.", "sc", ",", "err", ":=", "k", ".", "getStorageClass", "(", "cfg", ".", "Name", ")", "\n", "if", "err", "==", "nil", "{", "return", "&", "caas", ".", "StorageProvisioner", "{", "Name", ":", "sc", ".", "Name", ",", "Provisioner", ":", "sc", ".", "Provisioner", ",", "Parameters", ":", "sc", ".", "Parameters", ",", "}", ",", "nil", "\n", "}", "\n", "if", "!", "k8serrors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "cfg", ".", "Name", ")", "\n", "}", "\n", "// If it's not found but there's no provisioner specified, we can't", "// create it so just return not found.", "if", "cfg", ".", "Provisioner", "==", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "NewNotFound", "(", "nil", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cfg", ".", "Name", ")", ")", "\n", "}", "\n\n", "// Create the storage class with the specified provisioner.", "var", "reclaimPolicy", "*", "core", ".", "PersistentVolumeReclaimPolicy", "\n", "if", "cfg", ".", "ReclaimPolicy", "!=", "\"", "\"", "{", "policy", ":=", "core", ".", "PersistentVolumeReclaimPolicy", "(", "cfg", ".", "ReclaimPolicy", ")", "\n", "reclaimPolicy", "=", "&", "policy", "\n", "}", "\n", "storageClasses", ":=", "k", ".", "client", "(", ")", ".", "StorageV1", "(", ")", ".", "StorageClasses", "(", ")", "\n", "sc", "=", "&", "k8sstorage", ".", "StorageClass", "{", "ObjectMeta", ":", "v1", ".", "ObjectMeta", "{", "Name", ":", "qualifiedStorageClassName", "(", "cfg", ".", "Namespace", ",", "cfg", ".", "Name", ")", ",", "}", ",", "Provisioner", ":", "cfg", ".", "Provisioner", ",", "ReclaimPolicy", ":", "reclaimPolicy", ",", "Parameters", ":", "cfg", ".", "Parameters", ",", "}", "\n", "if", "cfg", ".", "Namespace", "!=", "\"", "\"", "{", "sc", ".", "Labels", "=", "map", "[", "string", "]", "string", "{", "labelModel", ":", "k", ".", "namespace", "}", "\n", "}", "\n", "_", ",", "err", "=", "storageClasses", ".", "Create", "(", "sc", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "cfg", ".", "Name", ")", "\n", "}", "\n", "return", "&", "caas", ".", "StorageProvisioner", "{", "Name", ":", "sc", ".", "Name", ",", "Provisioner", ":", "sc", ".", "Provisioner", ",", "Parameters", ":", "sc", ".", "Parameters", ",", "}", ",", "nil", "\n", "}" ]
// EnsureStorageProvisioner creates a storage class with the specified config, or returns an existing one.
[ "EnsureStorageProvisioner", "creates", "a", "storage", "class", "with", "the", "specified", "config", "or", "returns", "an", "existing", "one", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L734-L782
3,912
juju/juju
caas/kubernetes/provider/k8s.go
DeleteOperator
func (k *kubernetesClient) DeleteOperator(appName string) (err error) { logger.Debugf("deleting %s operator", appName) operatorName := k.operatorName(appName) legacy := isLegacyName(operatorName) // First delete the config map(s). configMaps := k.client().CoreV1().ConfigMaps(k.namespace) configMapName := operatorConfigMapName(operatorName) err = configMaps.Delete(configMapName, &v1.DeleteOptions{ PropagationPolicy: &defaultPropagationPolicy, }) if err != nil && !k8serrors.IsNotFound(err) { return nil } // Delete artefacts created by k8s itself. configMapName = appName + "-configurations-config" if legacy { configMapName = "juju-" + configMapName } err = configMaps.Delete(configMapName, &v1.DeleteOptions{ PropagationPolicy: &defaultPropagationPolicy, }) if err != nil && !k8serrors.IsNotFound(err) { return nil } // Finally the operator itself. if err := k.deleteStatefulSet(operatorName); err != nil { return errors.Trace(err) } pods := k.client().CoreV1().Pods(k.namespace) podsList, err := pods.List(v1.ListOptions{ LabelSelector: operatorSelector(appName), }) if err != nil { return errors.Trace(err) } deploymentName := appName if legacy { deploymentName = "juju-" + appName } pvs := k.client().CoreV1().PersistentVolumes() for _, p := range podsList.Items { // Delete secrets. for _, c := range p.Spec.Containers { secretName := appSecretName(deploymentName, c.Name) if err := k.deleteSecret(secretName); err != nil { return errors.Annotatef(err, "deleting %s secret for container %s", appName, c.Name) } } // Delete operator storage volumes. volumeNames, err := k.deleteVolumeClaims(appName, &p) if err != nil { return errors.Trace(err) } // Just in case the volume reclaim policy is retain, we force deletion // for operators as the volume is an inseparable part of the operator. for _, volName := range volumeNames { err = pvs.Delete(volName, &v1.DeleteOptions{ PropagationPolicy: &defaultPropagationPolicy, }) if err != nil && !k8serrors.IsNotFound(err) { return errors.Annotatef(err, "deleting operator persistent volume %v for %v", volName, appName) } } } return errors.Trace(k.deleteDeployment(operatorName)) }
go
func (k *kubernetesClient) DeleteOperator(appName string) (err error) { logger.Debugf("deleting %s operator", appName) operatorName := k.operatorName(appName) legacy := isLegacyName(operatorName) // First delete the config map(s). configMaps := k.client().CoreV1().ConfigMaps(k.namespace) configMapName := operatorConfigMapName(operatorName) err = configMaps.Delete(configMapName, &v1.DeleteOptions{ PropagationPolicy: &defaultPropagationPolicy, }) if err != nil && !k8serrors.IsNotFound(err) { return nil } // Delete artefacts created by k8s itself. configMapName = appName + "-configurations-config" if legacy { configMapName = "juju-" + configMapName } err = configMaps.Delete(configMapName, &v1.DeleteOptions{ PropagationPolicy: &defaultPropagationPolicy, }) if err != nil && !k8serrors.IsNotFound(err) { return nil } // Finally the operator itself. if err := k.deleteStatefulSet(operatorName); err != nil { return errors.Trace(err) } pods := k.client().CoreV1().Pods(k.namespace) podsList, err := pods.List(v1.ListOptions{ LabelSelector: operatorSelector(appName), }) if err != nil { return errors.Trace(err) } deploymentName := appName if legacy { deploymentName = "juju-" + appName } pvs := k.client().CoreV1().PersistentVolumes() for _, p := range podsList.Items { // Delete secrets. for _, c := range p.Spec.Containers { secretName := appSecretName(deploymentName, c.Name) if err := k.deleteSecret(secretName); err != nil { return errors.Annotatef(err, "deleting %s secret for container %s", appName, c.Name) } } // Delete operator storage volumes. volumeNames, err := k.deleteVolumeClaims(appName, &p) if err != nil { return errors.Trace(err) } // Just in case the volume reclaim policy is retain, we force deletion // for operators as the volume is an inseparable part of the operator. for _, volName := range volumeNames { err = pvs.Delete(volName, &v1.DeleteOptions{ PropagationPolicy: &defaultPropagationPolicy, }) if err != nil && !k8serrors.IsNotFound(err) { return errors.Annotatef(err, "deleting operator persistent volume %v for %v", volName, appName) } } } return errors.Trace(k.deleteDeployment(operatorName)) }
[ "func", "(", "k", "*", "kubernetesClient", ")", "DeleteOperator", "(", "appName", "string", ")", "(", "err", "error", ")", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "appName", ")", "\n\n", "operatorName", ":=", "k", ".", "operatorName", "(", "appName", ")", "\n", "legacy", ":=", "isLegacyName", "(", "operatorName", ")", "\n\n", "// First delete the config map(s).", "configMaps", ":=", "k", ".", "client", "(", ")", ".", "CoreV1", "(", ")", ".", "ConfigMaps", "(", "k", ".", "namespace", ")", "\n", "configMapName", ":=", "operatorConfigMapName", "(", "operatorName", ")", "\n", "err", "=", "configMaps", ".", "Delete", "(", "configMapName", ",", "&", "v1", ".", "DeleteOptions", "{", "PropagationPolicy", ":", "&", "defaultPropagationPolicy", ",", "}", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "k8serrors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", "\n", "}", "\n\n", "// Delete artefacts created by k8s itself.", "configMapName", "=", "appName", "+", "\"", "\"", "\n", "if", "legacy", "{", "configMapName", "=", "\"", "\"", "+", "configMapName", "\n", "}", "\n", "err", "=", "configMaps", ".", "Delete", "(", "configMapName", ",", "&", "v1", ".", "DeleteOptions", "{", "PropagationPolicy", ":", "&", "defaultPropagationPolicy", ",", "}", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "k8serrors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", "\n", "}", "\n\n", "// Finally the operator itself.", "if", "err", ":=", "k", ".", "deleteStatefulSet", "(", "operatorName", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "pods", ":=", "k", ".", "client", "(", ")", ".", "CoreV1", "(", ")", ".", "Pods", "(", "k", ".", "namespace", ")", "\n", "podsList", ",", "err", ":=", "pods", ".", "List", "(", "v1", ".", "ListOptions", "{", "LabelSelector", ":", "operatorSelector", "(", "appName", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "deploymentName", ":=", "appName", "\n", "if", "legacy", "{", "deploymentName", "=", "\"", "\"", "+", "appName", "\n", "}", "\n", "pvs", ":=", "k", ".", "client", "(", ")", ".", "CoreV1", "(", ")", ".", "PersistentVolumes", "(", ")", "\n", "for", "_", ",", "p", ":=", "range", "podsList", ".", "Items", "{", "// Delete secrets.", "for", "_", ",", "c", ":=", "range", "p", ".", "Spec", ".", "Containers", "{", "secretName", ":=", "appSecretName", "(", "deploymentName", ",", "c", ".", "Name", ")", "\n", "if", "err", ":=", "k", ".", "deleteSecret", "(", "secretName", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "appName", ",", "c", ".", "Name", ")", "\n", "}", "\n", "}", "\n", "// Delete operator storage volumes.", "volumeNames", ",", "err", ":=", "k", ".", "deleteVolumeClaims", "(", "appName", ",", "&", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "// Just in case the volume reclaim policy is retain, we force deletion", "// for operators as the volume is an inseparable part of the operator.", "for", "_", ",", "volName", ":=", "range", "volumeNames", "{", "err", "=", "pvs", ".", "Delete", "(", "volName", ",", "&", "v1", ".", "DeleteOptions", "{", "PropagationPolicy", ":", "&", "defaultPropagationPolicy", ",", "}", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "k8serrors", ".", "IsNotFound", "(", "err", ")", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "volName", ",", "appName", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "k", ".", "deleteDeployment", "(", "operatorName", ")", ")", "\n", "}" ]
// DeleteOperator deletes the specified operator.
[ "DeleteOperator", "deletes", "the", "specified", "operator", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L785-L856
3,913
juju/juju
caas/kubernetes/provider/k8s.go
GetService
func (k *kubernetesClient) GetService(appName string, includeClusterIP bool) (*caas.Service, error) { services := k.client().CoreV1().Services(k.namespace) servicesList, err := services.List(v1.ListOptions{ LabelSelector: applicationSelector(appName), IncludeUninitialized: true, }) if err != nil { return nil, errors.Trace(err) } var result caas.Service // We may have the stateful set or deployment but service not done yet. if len(servicesList.Items) > 0 { service := servicesList.Items[0] result.Id = string(service.GetUID()) result.Addresses = getSvcAddresses(&service, includeClusterIP) } deploymentName := k.deploymentName(appName) statefulsets := k.client().AppsV1().StatefulSets(k.namespace) ss, err := statefulsets.Get(deploymentName, v1.GetOptions{}) if err == nil { if ss.Spec.Replicas != nil { scale := int(*ss.Spec.Replicas) result.Scale = &scale } message, ssStatus, err := k.getStatefulSetStatus(ss) if err != nil { return nil, errors.Annotatef(err, "getting status for %s", ss.Name) } result.Status = status.StatusInfo{ Status: ssStatus, Message: message, } return &result, nil } if !k8serrors.IsNotFound(err) { return nil, errors.Trace(err) } deployments := k.client().AppsV1().Deployments(k.namespace) deployment, err := deployments.Get(deploymentName, v1.GetOptions{}) if err != nil && !k8serrors.IsNotFound(err) { return nil, errors.Trace(err) } if err == nil { if deployment.Spec.Replicas != nil { scale := int(*deployment.Spec.Replicas) result.Scale = &scale } message, ssStatus, err := k.getDeploymentStatus(deployment) if err != nil { return nil, errors.Annotatef(err, "getting status for %s", ss.Name) } result.Status = status.StatusInfo{ Status: ssStatus, Message: message, } } return &result, nil }
go
func (k *kubernetesClient) GetService(appName string, includeClusterIP bool) (*caas.Service, error) { services := k.client().CoreV1().Services(k.namespace) servicesList, err := services.List(v1.ListOptions{ LabelSelector: applicationSelector(appName), IncludeUninitialized: true, }) if err != nil { return nil, errors.Trace(err) } var result caas.Service // We may have the stateful set or deployment but service not done yet. if len(servicesList.Items) > 0 { service := servicesList.Items[0] result.Id = string(service.GetUID()) result.Addresses = getSvcAddresses(&service, includeClusterIP) } deploymentName := k.deploymentName(appName) statefulsets := k.client().AppsV1().StatefulSets(k.namespace) ss, err := statefulsets.Get(deploymentName, v1.GetOptions{}) if err == nil { if ss.Spec.Replicas != nil { scale := int(*ss.Spec.Replicas) result.Scale = &scale } message, ssStatus, err := k.getStatefulSetStatus(ss) if err != nil { return nil, errors.Annotatef(err, "getting status for %s", ss.Name) } result.Status = status.StatusInfo{ Status: ssStatus, Message: message, } return &result, nil } if !k8serrors.IsNotFound(err) { return nil, errors.Trace(err) } deployments := k.client().AppsV1().Deployments(k.namespace) deployment, err := deployments.Get(deploymentName, v1.GetOptions{}) if err != nil && !k8serrors.IsNotFound(err) { return nil, errors.Trace(err) } if err == nil { if deployment.Spec.Replicas != nil { scale := int(*deployment.Spec.Replicas) result.Scale = &scale } message, ssStatus, err := k.getDeploymentStatus(deployment) if err != nil { return nil, errors.Annotatef(err, "getting status for %s", ss.Name) } result.Status = status.StatusInfo{ Status: ssStatus, Message: message, } } return &result, nil }
[ "func", "(", "k", "*", "kubernetesClient", ")", "GetService", "(", "appName", "string", ",", "includeClusterIP", "bool", ")", "(", "*", "caas", ".", "Service", ",", "error", ")", "{", "services", ":=", "k", ".", "client", "(", ")", ".", "CoreV1", "(", ")", ".", "Services", "(", "k", ".", "namespace", ")", "\n", "servicesList", ",", "err", ":=", "services", ".", "List", "(", "v1", ".", "ListOptions", "{", "LabelSelector", ":", "applicationSelector", "(", "appName", ")", ",", "IncludeUninitialized", ":", "true", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "var", "result", "caas", ".", "Service", "\n", "// We may have the stateful set or deployment but service not done yet.", "if", "len", "(", "servicesList", ".", "Items", ")", ">", "0", "{", "service", ":=", "servicesList", ".", "Items", "[", "0", "]", "\n", "result", ".", "Id", "=", "string", "(", "service", ".", "GetUID", "(", ")", ")", "\n", "result", ".", "Addresses", "=", "getSvcAddresses", "(", "&", "service", ",", "includeClusterIP", ")", "\n", "}", "\n\n", "deploymentName", ":=", "k", ".", "deploymentName", "(", "appName", ")", "\n", "statefulsets", ":=", "k", ".", "client", "(", ")", ".", "AppsV1", "(", ")", ".", "StatefulSets", "(", "k", ".", "namespace", ")", "\n", "ss", ",", "err", ":=", "statefulsets", ".", "Get", "(", "deploymentName", ",", "v1", ".", "GetOptions", "{", "}", ")", "\n", "if", "err", "==", "nil", "{", "if", "ss", ".", "Spec", ".", "Replicas", "!=", "nil", "{", "scale", ":=", "int", "(", "*", "ss", ".", "Spec", ".", "Replicas", ")", "\n", "result", ".", "Scale", "=", "&", "scale", "\n", "}", "\n", "message", ",", "ssStatus", ",", "err", ":=", "k", ".", "getStatefulSetStatus", "(", "ss", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "ss", ".", "Name", ")", "\n", "}", "\n", "result", ".", "Status", "=", "status", ".", "StatusInfo", "{", "Status", ":", "ssStatus", ",", "Message", ":", "message", ",", "}", "\n", "return", "&", "result", ",", "nil", "\n", "}", "\n", "if", "!", "k8serrors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "deployments", ":=", "k", ".", "client", "(", ")", ".", "AppsV1", "(", ")", ".", "Deployments", "(", "k", ".", "namespace", ")", "\n", "deployment", ",", "err", ":=", "deployments", ".", "Get", "(", "deploymentName", ",", "v1", ".", "GetOptions", "{", "}", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "k8serrors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", "==", "nil", "{", "if", "deployment", ".", "Spec", ".", "Replicas", "!=", "nil", "{", "scale", ":=", "int", "(", "*", "deployment", ".", "Spec", ".", "Replicas", ")", "\n", "result", ".", "Scale", "=", "&", "scale", "\n", "}", "\n", "message", ",", "ssStatus", ",", "err", ":=", "k", ".", "getDeploymentStatus", "(", "deployment", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "ss", ".", "Name", ")", "\n", "}", "\n", "result", ".", "Status", "=", "status", ".", "StatusInfo", "{", "Status", ":", "ssStatus", ",", "Message", ":", "message", ",", "}", "\n", "}", "\n\n", "return", "&", "result", ",", "nil", "\n", "}" ]
// GetService returns the service for the specified application.
[ "GetService", "returns", "the", "service", "for", "the", "specified", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L925-L985
3,914
juju/juju
caas/kubernetes/provider/k8s.go
DeleteService
func (k *kubernetesClient) DeleteService(appName string) (err error) { logger.Debugf("deleting application %s", appName) deploymentName := k.deploymentName(appName) if err := k.deleteService(deploymentName); err != nil { return errors.Trace(err) } if err := k.deleteStatefulSet(deploymentName); err != nil { return errors.Trace(err) } if err := k.deleteDeployment(deploymentName); err != nil { return errors.Trace(err) } secrets := k.client().CoreV1().Secrets(k.namespace) secretList, err := secrets.List(v1.ListOptions{ LabelSelector: applicationSelector(appName), }) if err != nil { return errors.Trace(err) } for _, s := range secretList.Items { if err := k.deleteSecret(s.Name); err != nil { return errors.Trace(err) } } return nil }
go
func (k *kubernetesClient) DeleteService(appName string) (err error) { logger.Debugf("deleting application %s", appName) deploymentName := k.deploymentName(appName) if err := k.deleteService(deploymentName); err != nil { return errors.Trace(err) } if err := k.deleteStatefulSet(deploymentName); err != nil { return errors.Trace(err) } if err := k.deleteDeployment(deploymentName); err != nil { return errors.Trace(err) } secrets := k.client().CoreV1().Secrets(k.namespace) secretList, err := secrets.List(v1.ListOptions{ LabelSelector: applicationSelector(appName), }) if err != nil { return errors.Trace(err) } for _, s := range secretList.Items { if err := k.deleteSecret(s.Name); err != nil { return errors.Trace(err) } } return nil }
[ "func", "(", "k", "*", "kubernetesClient", ")", "DeleteService", "(", "appName", "string", ")", "(", "err", "error", ")", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "appName", ")", "\n\n", "deploymentName", ":=", "k", ".", "deploymentName", "(", "appName", ")", "\n", "if", "err", ":=", "k", ".", "deleteService", "(", "deploymentName", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "k", ".", "deleteStatefulSet", "(", "deploymentName", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "k", ".", "deleteDeployment", "(", "deploymentName", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "secrets", ":=", "k", ".", "client", "(", ")", ".", "CoreV1", "(", ")", ".", "Secrets", "(", "k", ".", "namespace", ")", "\n", "secretList", ",", "err", ":=", "secrets", ".", "List", "(", "v1", ".", "ListOptions", "{", "LabelSelector", ":", "applicationSelector", "(", "appName", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "for", "_", ",", "s", ":=", "range", "secretList", ".", "Items", "{", "if", "err", ":=", "k", ".", "deleteSecret", "(", "s", ".", "Name", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DeleteService deletes the specified service with all related resources.
[ "DeleteService", "deletes", "the", "specified", "service", "with", "all", "related", "resources", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L988-L1014
3,915
juju/juju
caas/kubernetes/provider/k8s.go
EnsureCustomResourceDefinition
func (k *kubernetesClient) EnsureCustomResourceDefinition(appName string, podSpec *caas.PodSpec) error { for name, crd := range podSpec.CustomResourceDefinitions { crd, err := k.ensureCustomResourceDefinitionTemplate(name, crd) if err != nil { return errors.Annotate(err, fmt.Sprintf("ensure custom resource definition %q", name)) } logger.Debugf("ensured custom resource definition %q", crd.ObjectMeta.Name) } return nil }
go
func (k *kubernetesClient) EnsureCustomResourceDefinition(appName string, podSpec *caas.PodSpec) error { for name, crd := range podSpec.CustomResourceDefinitions { crd, err := k.ensureCustomResourceDefinitionTemplate(name, crd) if err != nil { return errors.Annotate(err, fmt.Sprintf("ensure custom resource definition %q", name)) } logger.Debugf("ensured custom resource definition %q", crd.ObjectMeta.Name) } return nil }
[ "func", "(", "k", "*", "kubernetesClient", ")", "EnsureCustomResourceDefinition", "(", "appName", "string", ",", "podSpec", "*", "caas", ".", "PodSpec", ")", "error", "{", "for", "name", ",", "crd", ":=", "range", "podSpec", ".", "CustomResourceDefinitions", "{", "crd", ",", "err", ":=", "k", ".", "ensureCustomResourceDefinitionTemplate", "(", "name", ",", "crd", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ")", ")", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "crd", ".", "ObjectMeta", ".", "Name", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// EnsureCustomResourceDefinition creates or updates a custom resource definition resource.
[ "EnsureCustomResourceDefinition", "creates", "or", "updates", "a", "custom", "resource", "definition", "resource", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L1017-L1026
3,916
juju/juju
caas/kubernetes/provider/k8s.go
Upgrade
func (k *kubernetesClient) Upgrade(appName string, vers version.Number) error { var resourceName string if appName == JujuControllerStackName { // upgrading controller. resourceName = appName } else { // upgrading operator. resourceName = k.operatorName(appName) } logger.Debugf("Upgrading %q", resourceName) statefulsets := k.client().AppsV1().StatefulSets(k.namespace) existingStatefulSet, err := statefulsets.Get(resourceName, v1.GetOptions{IncludeUninitialized: true}) if err != nil && !k8serrors.IsNotFound(err) { return errors.Trace(err) } // TODO(wallyworld) - only support stateful set at the moment if err != nil { return errors.NotSupportedf("upgrading %v", appName) } for i, c := range existingStatefulSet.Spec.Template.Spec.Containers { if !podcfg.IsJujuOCIImage(c.Image) { continue } tagSep := strings.LastIndex(c.Image, ":") c.Image = fmt.Sprintf("%s:%s", c.Image[:tagSep], vers.String()) existingStatefulSet.Spec.Template.Spec.Containers[i] = c } _, err = statefulsets.Update(existingStatefulSet) return errors.Trace(err) }
go
func (k *kubernetesClient) Upgrade(appName string, vers version.Number) error { var resourceName string if appName == JujuControllerStackName { // upgrading controller. resourceName = appName } else { // upgrading operator. resourceName = k.operatorName(appName) } logger.Debugf("Upgrading %q", resourceName) statefulsets := k.client().AppsV1().StatefulSets(k.namespace) existingStatefulSet, err := statefulsets.Get(resourceName, v1.GetOptions{IncludeUninitialized: true}) if err != nil && !k8serrors.IsNotFound(err) { return errors.Trace(err) } // TODO(wallyworld) - only support stateful set at the moment if err != nil { return errors.NotSupportedf("upgrading %v", appName) } for i, c := range existingStatefulSet.Spec.Template.Spec.Containers { if !podcfg.IsJujuOCIImage(c.Image) { continue } tagSep := strings.LastIndex(c.Image, ":") c.Image = fmt.Sprintf("%s:%s", c.Image[:tagSep], vers.String()) existingStatefulSet.Spec.Template.Spec.Containers[i] = c } _, err = statefulsets.Update(existingStatefulSet) return errors.Trace(err) }
[ "func", "(", "k", "*", "kubernetesClient", ")", "Upgrade", "(", "appName", "string", ",", "vers", "version", ".", "Number", ")", "error", "{", "var", "resourceName", "string", "\n", "if", "appName", "==", "JujuControllerStackName", "{", "// upgrading controller.", "resourceName", "=", "appName", "\n", "}", "else", "{", "// upgrading operator.", "resourceName", "=", "k", ".", "operatorName", "(", "appName", ")", "\n", "}", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "resourceName", ")", "\n\n", "statefulsets", ":=", "k", ".", "client", "(", ")", ".", "AppsV1", "(", ")", ".", "StatefulSets", "(", "k", ".", "namespace", ")", "\n", "existingStatefulSet", ",", "err", ":=", "statefulsets", ".", "Get", "(", "resourceName", ",", "v1", ".", "GetOptions", "{", "IncludeUninitialized", ":", "true", "}", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "k8serrors", ".", "IsNotFound", "(", "err", ")", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "// TODO(wallyworld) - only support stateful set at the moment", "if", "err", "!=", "nil", "{", "return", "errors", ".", "NotSupportedf", "(", "\"", "\"", ",", "appName", ")", "\n", "}", "\n", "for", "i", ",", "c", ":=", "range", "existingStatefulSet", ".", "Spec", ".", "Template", ".", "Spec", ".", "Containers", "{", "if", "!", "podcfg", ".", "IsJujuOCIImage", "(", "c", ".", "Image", ")", "{", "continue", "\n", "}", "\n", "tagSep", ":=", "strings", ".", "LastIndex", "(", "c", ".", "Image", ",", "\"", "\"", ")", "\n", "c", ".", "Image", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ".", "Image", "[", ":", "tagSep", "]", ",", "vers", ".", "String", "(", ")", ")", "\n", "existingStatefulSet", ".", "Spec", ".", "Template", ".", "Spec", ".", "Containers", "[", "i", "]", "=", "c", "\n", "}", "\n", "_", ",", "err", "=", "statefulsets", ".", "Update", "(", "existingStatefulSet", ")", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// Upgrade sets the OCI image for the app's operator to the specified version.
[ "Upgrade", "sets", "the", "OCI", "image", "for", "the", "app", "s", "operator", "to", "the", "specified", "version", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L1296-L1326
3,917
juju/juju
caas/kubernetes/provider/k8s.go
createStatefulSet
func (k *kubernetesClient) createStatefulSet(spec *apps.StatefulSet) error { _, err := k.client().AppsV1().StatefulSets(k.namespace).Create(spec) return errors.Trace(err) }
go
func (k *kubernetesClient) createStatefulSet(spec *apps.StatefulSet) error { _, err := k.client().AppsV1().StatefulSets(k.namespace).Create(spec) return errors.Trace(err) }
[ "func", "(", "k", "*", "kubernetesClient", ")", "createStatefulSet", "(", "spec", "*", "apps", ".", "StatefulSet", ")", "error", "{", "_", ",", "err", ":=", "k", ".", "client", "(", ")", ".", "AppsV1", "(", ")", ".", "StatefulSets", "(", "k", ".", "namespace", ")", ".", "Create", "(", "spec", ")", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// createStatefulSet deletes a statefulset resource.
[ "createStatefulSet", "deletes", "a", "statefulset", "resource", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L1651-L1654
3,918
juju/juju
caas/kubernetes/provider/k8s.go
deleteStatefulSet
func (k *kubernetesClient) deleteStatefulSet(name string) error { deployments := k.client().AppsV1().StatefulSets(k.namespace) err := deployments.Delete(name, &v1.DeleteOptions{ PropagationPolicy: &defaultPropagationPolicy, }) if k8serrors.IsNotFound(err) { return nil } return errors.Trace(err) }
go
func (k *kubernetesClient) deleteStatefulSet(name string) error { deployments := k.client().AppsV1().StatefulSets(k.namespace) err := deployments.Delete(name, &v1.DeleteOptions{ PropagationPolicy: &defaultPropagationPolicy, }) if k8serrors.IsNotFound(err) { return nil } return errors.Trace(err) }
[ "func", "(", "k", "*", "kubernetesClient", ")", "deleteStatefulSet", "(", "name", "string", ")", "error", "{", "deployments", ":=", "k", ".", "client", "(", ")", ".", "AppsV1", "(", ")", ".", "StatefulSets", "(", "k", ".", "namespace", ")", "\n", "err", ":=", "deployments", ".", "Delete", "(", "name", ",", "&", "v1", ".", "DeleteOptions", "{", "PropagationPolicy", ":", "&", "defaultPropagationPolicy", ",", "}", ")", "\n", "if", "k8serrors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", "\n", "}", "\n\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// deleteStatefulSet deletes a statefulset resource.
[ "deleteStatefulSet", "deletes", "a", "statefulset", "resource", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L1657-L1667
3,919
juju/juju
caas/kubernetes/provider/k8s.go
ensureK8sService
func (k *kubernetesClient) ensureK8sService(spec *core.Service) error { services := k.client().CoreV1().Services(k.namespace) // Set any immutable fields if the service already exists. existing, err := services.Get(spec.Name, v1.GetOptions{IncludeUninitialized: true}) if err == nil { spec.Spec.ClusterIP = existing.Spec.ClusterIP spec.ObjectMeta.ResourceVersion = existing.ObjectMeta.ResourceVersion } _, err = services.Update(spec) if k8serrors.IsNotFound(err) { _, err = services.Create(spec) } return errors.Trace(err) }
go
func (k *kubernetesClient) ensureK8sService(spec *core.Service) error { services := k.client().CoreV1().Services(k.namespace) // Set any immutable fields if the service already exists. existing, err := services.Get(spec.Name, v1.GetOptions{IncludeUninitialized: true}) if err == nil { spec.Spec.ClusterIP = existing.Spec.ClusterIP spec.ObjectMeta.ResourceVersion = existing.ObjectMeta.ResourceVersion } _, err = services.Update(spec) if k8serrors.IsNotFound(err) { _, err = services.Create(spec) } return errors.Trace(err) }
[ "func", "(", "k", "*", "kubernetesClient", ")", "ensureK8sService", "(", "spec", "*", "core", ".", "Service", ")", "error", "{", "services", ":=", "k", ".", "client", "(", ")", ".", "CoreV1", "(", ")", ".", "Services", "(", "k", ".", "namespace", ")", "\n", "// Set any immutable fields if the service already exists.", "existing", ",", "err", ":=", "services", ".", "Get", "(", "spec", ".", "Name", ",", "v1", ".", "GetOptions", "{", "IncludeUninitialized", ":", "true", "}", ")", "\n", "if", "err", "==", "nil", "{", "spec", ".", "Spec", ".", "ClusterIP", "=", "existing", ".", "Spec", ".", "ClusterIP", "\n", "spec", ".", "ObjectMeta", ".", "ResourceVersion", "=", "existing", ".", "ObjectMeta", ".", "ResourceVersion", "\n", "}", "\n", "_", ",", "err", "=", "services", ".", "Update", "(", "spec", ")", "\n", "if", "k8serrors", ".", "IsNotFound", "(", "err", ")", "{", "_", ",", "err", "=", "services", ".", "Create", "(", "spec", ")", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// ensureK8sService ensures a k8s service resource.
[ "ensureK8sService", "ensures", "a", "k8s", "service", "resource", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L1762-L1775
3,920
juju/juju
caas/kubernetes/provider/k8s.go
deleteService
func (k *kubernetesClient) deleteService(deploymentName string) error { services := k.client().CoreV1().Services(k.namespace) err := services.Delete(deploymentName, &v1.DeleteOptions{ PropagationPolicy: &defaultPropagationPolicy, }) if k8serrors.IsNotFound(err) { return nil } return errors.Trace(err) }
go
func (k *kubernetesClient) deleteService(deploymentName string) error { services := k.client().CoreV1().Services(k.namespace) err := services.Delete(deploymentName, &v1.DeleteOptions{ PropagationPolicy: &defaultPropagationPolicy, }) if k8serrors.IsNotFound(err) { return nil } return errors.Trace(err) }
[ "func", "(", "k", "*", "kubernetesClient", ")", "deleteService", "(", "deploymentName", "string", ")", "error", "{", "services", ":=", "k", ".", "client", "(", ")", ".", "CoreV1", "(", ")", ".", "Services", "(", "k", ".", "namespace", ")", "\n", "err", ":=", "services", ".", "Delete", "(", "deploymentName", ",", "&", "v1", ".", "DeleteOptions", "{", "PropagationPolicy", ":", "&", "defaultPropagationPolicy", ",", "}", ")", "\n", "if", "k8serrors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// deleteService deletes a service resource.
[ "deleteService", "deletes", "a", "service", "resource", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L1778-L1787
3,921
juju/juju
caas/kubernetes/provider/k8s.go
ExposeService
func (k *kubernetesClient) ExposeService(appName string, resourceTags map[string]string, config application.ConfigAttributes) error { logger.Debugf("creating/updating ingress resource for %s", appName) host := config.GetString(caas.JujuExternalHostNameKey, "") if host == "" { return errors.Errorf("external hostname required") } ingressClass := config.GetString(ingressClassKey, defaultIngressClass) ingressSSLRedirect := config.GetBool(ingressSSLRedirectKey, defaultIngressSSLRedirect) ingressSSLPassthrough := config.GetBool(ingressSSLPassthroughKey, defaultIngressSSLPassthrough) ingressAllowHTTP := config.GetBool(ingressAllowHTTPKey, defaultIngressAllowHTTPKey) httpPath := config.GetString(caas.JujuApplicationPath, caas.JujuDefaultApplicationPath) if httpPath == "$appname" { httpPath = appName } if !strings.HasPrefix(httpPath, "/") { httpPath = "/" + httpPath } deploymentName := k.deploymentName(appName) svc, err := k.client().CoreV1().Services(k.namespace).Get(deploymentName, v1.GetOptions{}) if err != nil { return errors.Trace(err) } if len(svc.Spec.Ports) == 0 { return errors.Errorf("cannot create ingress rule for service %q without a port", svc.Name) } spec := &v1beta1.Ingress{ ObjectMeta: v1.ObjectMeta{ Name: deploymentName, Labels: resourceTags, Annotations: map[string]string{ "ingress.kubernetes.io/rewrite-target": "", "ingress.kubernetes.io/ssl-redirect": strconv.FormatBool(ingressSSLRedirect), "kubernetes.io/ingress.class": ingressClass, "kubernetes.io/ingress.allow-http": strconv.FormatBool(ingressAllowHTTP), "ingress.kubernetes.io/ssl-passthrough": strconv.FormatBool(ingressSSLPassthrough), }, }, Spec: v1beta1.IngressSpec{ Rules: []v1beta1.IngressRule{{ Host: host, IngressRuleValue: v1beta1.IngressRuleValue{ HTTP: &v1beta1.HTTPIngressRuleValue{ Paths: []v1beta1.HTTPIngressPath{{ Path: httpPath, Backend: v1beta1.IngressBackend{ ServiceName: svc.Name, ServicePort: svc.Spec.Ports[0].TargetPort}, }}}, }}}, }, } return k.ensureIngress(spec) }
go
func (k *kubernetesClient) ExposeService(appName string, resourceTags map[string]string, config application.ConfigAttributes) error { logger.Debugf("creating/updating ingress resource for %s", appName) host := config.GetString(caas.JujuExternalHostNameKey, "") if host == "" { return errors.Errorf("external hostname required") } ingressClass := config.GetString(ingressClassKey, defaultIngressClass) ingressSSLRedirect := config.GetBool(ingressSSLRedirectKey, defaultIngressSSLRedirect) ingressSSLPassthrough := config.GetBool(ingressSSLPassthroughKey, defaultIngressSSLPassthrough) ingressAllowHTTP := config.GetBool(ingressAllowHTTPKey, defaultIngressAllowHTTPKey) httpPath := config.GetString(caas.JujuApplicationPath, caas.JujuDefaultApplicationPath) if httpPath == "$appname" { httpPath = appName } if !strings.HasPrefix(httpPath, "/") { httpPath = "/" + httpPath } deploymentName := k.deploymentName(appName) svc, err := k.client().CoreV1().Services(k.namespace).Get(deploymentName, v1.GetOptions{}) if err != nil { return errors.Trace(err) } if len(svc.Spec.Ports) == 0 { return errors.Errorf("cannot create ingress rule for service %q without a port", svc.Name) } spec := &v1beta1.Ingress{ ObjectMeta: v1.ObjectMeta{ Name: deploymentName, Labels: resourceTags, Annotations: map[string]string{ "ingress.kubernetes.io/rewrite-target": "", "ingress.kubernetes.io/ssl-redirect": strconv.FormatBool(ingressSSLRedirect), "kubernetes.io/ingress.class": ingressClass, "kubernetes.io/ingress.allow-http": strconv.FormatBool(ingressAllowHTTP), "ingress.kubernetes.io/ssl-passthrough": strconv.FormatBool(ingressSSLPassthrough), }, }, Spec: v1beta1.IngressSpec{ Rules: []v1beta1.IngressRule{{ Host: host, IngressRuleValue: v1beta1.IngressRuleValue{ HTTP: &v1beta1.HTTPIngressRuleValue{ Paths: []v1beta1.HTTPIngressPath{{ Path: httpPath, Backend: v1beta1.IngressBackend{ ServiceName: svc.Name, ServicePort: svc.Spec.Ports[0].TargetPort}, }}}, }}}, }, } return k.ensureIngress(spec) }
[ "func", "(", "k", "*", "kubernetesClient", ")", "ExposeService", "(", "appName", "string", ",", "resourceTags", "map", "[", "string", "]", "string", ",", "config", "application", ".", "ConfigAttributes", ")", "error", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "appName", ")", "\n\n", "host", ":=", "config", ".", "GetString", "(", "caas", ".", "JujuExternalHostNameKey", ",", "\"", "\"", ")", "\n", "if", "host", "==", "\"", "\"", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "ingressClass", ":=", "config", ".", "GetString", "(", "ingressClassKey", ",", "defaultIngressClass", ")", "\n", "ingressSSLRedirect", ":=", "config", ".", "GetBool", "(", "ingressSSLRedirectKey", ",", "defaultIngressSSLRedirect", ")", "\n", "ingressSSLPassthrough", ":=", "config", ".", "GetBool", "(", "ingressSSLPassthroughKey", ",", "defaultIngressSSLPassthrough", ")", "\n", "ingressAllowHTTP", ":=", "config", ".", "GetBool", "(", "ingressAllowHTTPKey", ",", "defaultIngressAllowHTTPKey", ")", "\n", "httpPath", ":=", "config", ".", "GetString", "(", "caas", ".", "JujuApplicationPath", ",", "caas", ".", "JujuDefaultApplicationPath", ")", "\n", "if", "httpPath", "==", "\"", "\"", "{", "httpPath", "=", "appName", "\n", "}", "\n", "if", "!", "strings", ".", "HasPrefix", "(", "httpPath", ",", "\"", "\"", ")", "{", "httpPath", "=", "\"", "\"", "+", "httpPath", "\n", "}", "\n\n", "deploymentName", ":=", "k", ".", "deploymentName", "(", "appName", ")", "\n", "svc", ",", "err", ":=", "k", ".", "client", "(", ")", ".", "CoreV1", "(", ")", ".", "Services", "(", "k", ".", "namespace", ")", ".", "Get", "(", "deploymentName", ",", "v1", ".", "GetOptions", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "svc", ".", "Spec", ".", "Ports", ")", "==", "0", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "svc", ".", "Name", ")", "\n", "}", "\n", "spec", ":=", "&", "v1beta1", ".", "Ingress", "{", "ObjectMeta", ":", "v1", ".", "ObjectMeta", "{", "Name", ":", "deploymentName", ",", "Labels", ":", "resourceTags", ",", "Annotations", ":", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "strconv", ".", "FormatBool", "(", "ingressSSLRedirect", ")", ",", "\"", "\"", ":", "ingressClass", ",", "\"", "\"", ":", "strconv", ".", "FormatBool", "(", "ingressAllowHTTP", ")", ",", "\"", "\"", ":", "strconv", ".", "FormatBool", "(", "ingressSSLPassthrough", ")", ",", "}", ",", "}", ",", "Spec", ":", "v1beta1", ".", "IngressSpec", "{", "Rules", ":", "[", "]", "v1beta1", ".", "IngressRule", "{", "{", "Host", ":", "host", ",", "IngressRuleValue", ":", "v1beta1", ".", "IngressRuleValue", "{", "HTTP", ":", "&", "v1beta1", ".", "HTTPIngressRuleValue", "{", "Paths", ":", "[", "]", "v1beta1", ".", "HTTPIngressPath", "{", "{", "Path", ":", "httpPath", ",", "Backend", ":", "v1beta1", ".", "IngressBackend", "{", "ServiceName", ":", "svc", ".", "Name", ",", "ServicePort", ":", "svc", ".", "Spec", ".", "Ports", "[", "0", "]", ".", "TargetPort", "}", ",", "}", "}", "}", ",", "}", "}", "}", ",", "}", ",", "}", "\n", "return", "k", ".", "ensureIngress", "(", "spec", ")", "\n", "}" ]
// ExposeService sets up external access to the specified application.
[ "ExposeService", "sets", "up", "external", "access", "to", "the", "specified", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L1790-L1843
3,922
juju/juju
caas/kubernetes/provider/k8s.go
UnexposeService
func (k *kubernetesClient) UnexposeService(appName string) error { logger.Debugf("deleting ingress resource for %s", appName) return k.deleteIngress(appName) }
go
func (k *kubernetesClient) UnexposeService(appName string) error { logger.Debugf("deleting ingress resource for %s", appName) return k.deleteIngress(appName) }
[ "func", "(", "k", "*", "kubernetesClient", ")", "UnexposeService", "(", "appName", "string", ")", "error", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "appName", ")", "\n", "return", "k", ".", "deleteIngress", "(", "appName", ")", "\n", "}" ]
// UnexposeService removes external access to the specified service.
[ "UnexposeService", "removes", "external", "access", "to", "the", "specified", "service", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L1846-L1849
3,923
juju/juju
caas/kubernetes/provider/k8s.go
WatchUnits
func (k *kubernetesClient) WatchUnits(appName string) (watcher.NotifyWatcher, error) { selector := applicationSelector(appName) logger.Debugf("selecting units %q to watch", selector) w, err := k.client().CoreV1().Pods(k.namespace).Watch(v1.ListOptions{ LabelSelector: selector, Watch: true, IncludeUninitialized: true, }) if err != nil { return nil, errors.Trace(err) } return k.newWatcher(w, appName, k.clock) }
go
func (k *kubernetesClient) WatchUnits(appName string) (watcher.NotifyWatcher, error) { selector := applicationSelector(appName) logger.Debugf("selecting units %q to watch", selector) w, err := k.client().CoreV1().Pods(k.namespace).Watch(v1.ListOptions{ LabelSelector: selector, Watch: true, IncludeUninitialized: true, }) if err != nil { return nil, errors.Trace(err) } return k.newWatcher(w, appName, k.clock) }
[ "func", "(", "k", "*", "kubernetesClient", ")", "WatchUnits", "(", "appName", "string", ")", "(", "watcher", ".", "NotifyWatcher", ",", "error", ")", "{", "selector", ":=", "applicationSelector", "(", "appName", ")", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ",", "selector", ")", "\n", "w", ",", "err", ":=", "k", ".", "client", "(", ")", ".", "CoreV1", "(", ")", ".", "Pods", "(", "k", ".", "namespace", ")", ".", "Watch", "(", "v1", ".", "ListOptions", "{", "LabelSelector", ":", "selector", ",", "Watch", ":", "true", ",", "IncludeUninitialized", ":", "true", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "k", ".", "newWatcher", "(", "w", ",", "appName", ",", "k", ".", "clock", ")", "\n", "}" ]
// WatchUnits returns a watcher which notifies when there // are changes to units of the specified application.
[ "WatchUnits", "returns", "a", "watcher", "which", "notifies", "when", "there", "are", "changes", "to", "units", "of", "the", "specified", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L1882-L1894
3,924
juju/juju
caas/kubernetes/provider/k8s.go
WatchService
func (k *kubernetesClient) WatchService(appName string) (watcher.NotifyWatcher, error) { // Application may be a statefulset or deployment. It may not have // been set up when the watcher is started so we don't know which it // is ahead of time. So use a multi-watcher to cover both cases. statefulsets := k.client().AppsV1().StatefulSets(k.namespace) sswatcher, err := statefulsets.Watch(v1.ListOptions{ LabelSelector: applicationSelector(appName), Watch: true, }) if err != nil { return nil, errors.Trace(err) } w1, err := k.newWatcher(sswatcher, appName, k.clock) if err != nil { return nil, errors.Trace(err) } deployments := k.client().AppsV1().Deployments(k.namespace) dwatcher, err := deployments.Watch(v1.ListOptions{ LabelSelector: applicationSelector(appName), Watch: true, }) if err != nil { return nil, errors.Trace(err) } w2, err := k.newWatcher(dwatcher, appName, k.clock) if err != nil { return nil, errors.Trace(err) } return watcher.NewMultiNotifyWatcher(w1, w2), nil }
go
func (k *kubernetesClient) WatchService(appName string) (watcher.NotifyWatcher, error) { // Application may be a statefulset or deployment. It may not have // been set up when the watcher is started so we don't know which it // is ahead of time. So use a multi-watcher to cover both cases. statefulsets := k.client().AppsV1().StatefulSets(k.namespace) sswatcher, err := statefulsets.Watch(v1.ListOptions{ LabelSelector: applicationSelector(appName), Watch: true, }) if err != nil { return nil, errors.Trace(err) } w1, err := k.newWatcher(sswatcher, appName, k.clock) if err != nil { return nil, errors.Trace(err) } deployments := k.client().AppsV1().Deployments(k.namespace) dwatcher, err := deployments.Watch(v1.ListOptions{ LabelSelector: applicationSelector(appName), Watch: true, }) if err != nil { return nil, errors.Trace(err) } w2, err := k.newWatcher(dwatcher, appName, k.clock) if err != nil { return nil, errors.Trace(err) } return watcher.NewMultiNotifyWatcher(w1, w2), nil }
[ "func", "(", "k", "*", "kubernetesClient", ")", "WatchService", "(", "appName", "string", ")", "(", "watcher", ".", "NotifyWatcher", ",", "error", ")", "{", "// Application may be a statefulset or deployment. It may not have", "// been set up when the watcher is started so we don't know which it", "// is ahead of time. So use a multi-watcher to cover both cases.", "statefulsets", ":=", "k", ".", "client", "(", ")", ".", "AppsV1", "(", ")", ".", "StatefulSets", "(", "k", ".", "namespace", ")", "\n", "sswatcher", ",", "err", ":=", "statefulsets", ".", "Watch", "(", "v1", ".", "ListOptions", "{", "LabelSelector", ":", "applicationSelector", "(", "appName", ")", ",", "Watch", ":", "true", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "w1", ",", "err", ":=", "k", ".", "newWatcher", "(", "sswatcher", ",", "appName", ",", "k", ".", "clock", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "deployments", ":=", "k", ".", "client", "(", ")", ".", "AppsV1", "(", ")", ".", "Deployments", "(", "k", ".", "namespace", ")", "\n", "dwatcher", ",", "err", ":=", "deployments", ".", "Watch", "(", "v1", ".", "ListOptions", "{", "LabelSelector", ":", "applicationSelector", "(", "appName", ")", ",", "Watch", ":", "true", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "w2", ",", "err", ":=", "k", ".", "newWatcher", "(", "dwatcher", ",", "appName", ",", "k", ".", "clock", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "watcher", ".", "NewMultiNotifyWatcher", "(", "w1", ",", "w2", ")", ",", "nil", "\n", "}" ]
// WatchService returns a watcher which notifies when there // are changes to the deployment of the specified application.
[ "WatchService", "returns", "a", "watcher", "which", "notifies", "when", "there", "are", "changes", "to", "the", "deployment", "of", "the", "specified", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L1898-L1929
3,925
juju/juju
caas/kubernetes/provider/k8s.go
WatchOperator
func (k *kubernetesClient) WatchOperator(appName string) (watcher.NotifyWatcher, error) { pods := k.client().CoreV1().Pods(k.namespace) w, err := pods.Watch(v1.ListOptions{ LabelSelector: operatorSelector(appName), Watch: true, }) if err != nil { return nil, errors.Trace(err) } return k.newWatcher(w, appName, k.clock) }
go
func (k *kubernetesClient) WatchOperator(appName string) (watcher.NotifyWatcher, error) { pods := k.client().CoreV1().Pods(k.namespace) w, err := pods.Watch(v1.ListOptions{ LabelSelector: operatorSelector(appName), Watch: true, }) if err != nil { return nil, errors.Trace(err) } return k.newWatcher(w, appName, k.clock) }
[ "func", "(", "k", "*", "kubernetesClient", ")", "WatchOperator", "(", "appName", "string", ")", "(", "watcher", ".", "NotifyWatcher", ",", "error", ")", "{", "pods", ":=", "k", ".", "client", "(", ")", ".", "CoreV1", "(", ")", ".", "Pods", "(", "k", ".", "namespace", ")", "\n", "w", ",", "err", ":=", "pods", ".", "Watch", "(", "v1", ".", "ListOptions", "{", "LabelSelector", ":", "operatorSelector", "(", "appName", ")", ",", "Watch", ":", "true", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "k", ".", "newWatcher", "(", "w", ",", "appName", ",", "k", ".", "clock", ")", "\n", "}" ]
// WatchOperator returns a watcher which notifies when there // are changes to the operator of the specified application.
[ "WatchOperator", "returns", "a", "watcher", "which", "notifies", "when", "there", "are", "changes", "to", "the", "operator", "of", "the", "specified", "application", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L1933-L1943
3,926
juju/juju
caas/kubernetes/provider/k8s.go
Operator
func (k *kubernetesClient) Operator(appName string) (*caas.Operator, error) { pods := k.client().CoreV1().Pods(k.namespace) podsList, err := pods.List(v1.ListOptions{ LabelSelector: operatorSelector(appName), }) if err != nil { return nil, errors.Trace(err) } if len(podsList.Items) == 0 { return nil, errors.NotFoundf("operator pod for application %q", appName) } opPod := podsList.Items[0] terminated := opPod.DeletionTimestamp != nil now := time.Now() statusMessage, opStatus, since, err := k.getPODStatus(opPod, now) return &caas.Operator{ Id: string(opPod.UID), Dying: terminated, Status: status.StatusInfo{ Status: opStatus, Message: statusMessage, Since: &since, }, }, nil }
go
func (k *kubernetesClient) Operator(appName string) (*caas.Operator, error) { pods := k.client().CoreV1().Pods(k.namespace) podsList, err := pods.List(v1.ListOptions{ LabelSelector: operatorSelector(appName), }) if err != nil { return nil, errors.Trace(err) } if len(podsList.Items) == 0 { return nil, errors.NotFoundf("operator pod for application %q", appName) } opPod := podsList.Items[0] terminated := opPod.DeletionTimestamp != nil now := time.Now() statusMessage, opStatus, since, err := k.getPODStatus(opPod, now) return &caas.Operator{ Id: string(opPod.UID), Dying: terminated, Status: status.StatusInfo{ Status: opStatus, Message: statusMessage, Since: &since, }, }, nil }
[ "func", "(", "k", "*", "kubernetesClient", ")", "Operator", "(", "appName", "string", ")", "(", "*", "caas", ".", "Operator", ",", "error", ")", "{", "pods", ":=", "k", ".", "client", "(", ")", ".", "CoreV1", "(", ")", ".", "Pods", "(", "k", ".", "namespace", ")", "\n", "podsList", ",", "err", ":=", "pods", ".", "List", "(", "v1", ".", "ListOptions", "{", "LabelSelector", ":", "operatorSelector", "(", "appName", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "podsList", ".", "Items", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "appName", ")", "\n", "}", "\n\n", "opPod", ":=", "podsList", ".", "Items", "[", "0", "]", "\n", "terminated", ":=", "opPod", ".", "DeletionTimestamp", "!=", "nil", "\n", "now", ":=", "time", ".", "Now", "(", ")", "\n", "statusMessage", ",", "opStatus", ",", "since", ",", "err", ":=", "k", ".", "getPODStatus", "(", "opPod", ",", "now", ")", "\n", "return", "&", "caas", ".", "Operator", "{", "Id", ":", "string", "(", "opPod", ".", "UID", ")", ",", "Dying", ":", "terminated", ",", "Status", ":", "status", ".", "StatusInfo", "{", "Status", ":", "opStatus", ",", "Message", ":", "statusMessage", ",", "Since", ":", "&", "since", ",", "}", ",", "}", ",", "nil", "\n", "}" ]
// Operator returns an Operator with current status and life details.
[ "Operator", "returns", "an", "Operator", "with", "current", "status", "and", "life", "details", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L2148-L2173
3,927
juju/juju
caas/kubernetes/provider/k8s.go
ensureConfigMap
func (k *kubernetesClient) ensureConfigMap(configMap *core.ConfigMap) error { configMaps := k.client().CoreV1().ConfigMaps(k.namespace) _, err := configMaps.Update(configMap) if k8serrors.IsNotFound(err) { _, err = configMaps.Create(configMap) } return errors.Trace(err) }
go
func (k *kubernetesClient) ensureConfigMap(configMap *core.ConfigMap) error { configMaps := k.client().CoreV1().ConfigMaps(k.namespace) _, err := configMaps.Update(configMap) if k8serrors.IsNotFound(err) { _, err = configMaps.Create(configMap) } return errors.Trace(err) }
[ "func", "(", "k", "*", "kubernetesClient", ")", "ensureConfigMap", "(", "configMap", "*", "core", ".", "ConfigMap", ")", "error", "{", "configMaps", ":=", "k", ".", "client", "(", ")", ".", "CoreV1", "(", ")", ".", "ConfigMaps", "(", "k", ".", "namespace", ")", "\n", "_", ",", "err", ":=", "configMaps", ".", "Update", "(", "configMap", ")", "\n", "if", "k8serrors", ".", "IsNotFound", "(", "err", ")", "{", "_", ",", "err", "=", "configMaps", ".", "Create", "(", "configMap", ")", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// ensureConfigMap ensures a ConfigMap resource.
[ "ensureConfigMap", "ensures", "a", "ConfigMap", "resource", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L2310-L2317
3,928
juju/juju
caas/kubernetes/provider/k8s.go
deleteConfigMap
func (k *kubernetesClient) deleteConfigMap(configMapName string) error { err := k.client().CoreV1().ConfigMaps(k.namespace).Delete(configMapName, &v1.DeleteOptions{ PropagationPolicy: &defaultPropagationPolicy, }) if k8serrors.IsNotFound(err) { return nil } return errors.Trace(err) }
go
func (k *kubernetesClient) deleteConfigMap(configMapName string) error { err := k.client().CoreV1().ConfigMaps(k.namespace).Delete(configMapName, &v1.DeleteOptions{ PropagationPolicy: &defaultPropagationPolicy, }) if k8serrors.IsNotFound(err) { return nil } return errors.Trace(err) }
[ "func", "(", "k", "*", "kubernetesClient", ")", "deleteConfigMap", "(", "configMapName", "string", ")", "error", "{", "err", ":=", "k", ".", "client", "(", ")", ".", "CoreV1", "(", ")", ".", "ConfigMaps", "(", "k", ".", "namespace", ")", ".", "Delete", "(", "configMapName", ",", "&", "v1", ".", "DeleteOptions", "{", "PropagationPolicy", ":", "&", "defaultPropagationPolicy", ",", "}", ")", "\n", "if", "k8serrors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// deleteConfigMap deletes a ConfigMap resource.
[ "deleteConfigMap", "deletes", "a", "ConfigMap", "resource", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L2320-L2328
3,929
juju/juju
caas/kubernetes/provider/k8s.go
createConfigMap
func (k *kubernetesClient) createConfigMap(configMap *core.ConfigMap) error { _, err := k.client().CoreV1().ConfigMaps(k.namespace).Create(configMap) return errors.Trace(err) }
go
func (k *kubernetesClient) createConfigMap(configMap *core.ConfigMap) error { _, err := k.client().CoreV1().ConfigMaps(k.namespace).Create(configMap) return errors.Trace(err) }
[ "func", "(", "k", "*", "kubernetesClient", ")", "createConfigMap", "(", "configMap", "*", "core", ".", "ConfigMap", ")", "error", "{", "_", ",", "err", ":=", "k", ".", "client", "(", ")", ".", "CoreV1", "(", ")", ".", "ConfigMaps", "(", "k", ".", "namespace", ")", ".", "Create", "(", "configMap", ")", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// createConfigMap creates a ConfigMap resource.
[ "createConfigMap", "creates", "a", "ConfigMap", "resource", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L2331-L2334
3,930
juju/juju
caas/kubernetes/provider/k8s.go
getConfigMap
func (k *kubernetesClient) getConfigMap(cmName string) (*core.ConfigMap, error) { cm, err := k.client().CoreV1().ConfigMaps(k.namespace).Get(cmName, v1.GetOptions{IncludeUninitialized: true}) if err != nil { if k8serrors.IsNotFound(err) { return nil, errors.NotFoundf("configmap %q", cmName) } return nil, errors.Trace(err) } return cm, nil }
go
func (k *kubernetesClient) getConfigMap(cmName string) (*core.ConfigMap, error) { cm, err := k.client().CoreV1().ConfigMaps(k.namespace).Get(cmName, v1.GetOptions{IncludeUninitialized: true}) if err != nil { if k8serrors.IsNotFound(err) { return nil, errors.NotFoundf("configmap %q", cmName) } return nil, errors.Trace(err) } return cm, nil }
[ "func", "(", "k", "*", "kubernetesClient", ")", "getConfigMap", "(", "cmName", "string", ")", "(", "*", "core", ".", "ConfigMap", ",", "error", ")", "{", "cm", ",", "err", ":=", "k", ".", "client", "(", ")", ".", "CoreV1", "(", ")", ".", "ConfigMaps", "(", "k", ".", "namespace", ")", ".", "Get", "(", "cmName", ",", "v1", ".", "GetOptions", "{", "IncludeUninitialized", ":", "true", "}", ")", "\n", "if", "err", "!=", "nil", "{", "if", "k8serrors", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ",", "cmName", ")", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "cm", ",", "nil", "\n", "}" ]
// getConfigMap returns a ConfigMap resource.
[ "getConfigMap", "returns", "a", "ConfigMap", "resource", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L2337-L2346
3,931
juju/juju
caas/kubernetes/provider/k8s.go
legacyAppName
func (k *kubernetesClient) legacyAppName(appName string) bool { statefulsets := k.client().AppsV1().StatefulSets(k.namespace) legacyName := "juju-operator-" + appName _, err := statefulsets.Get(legacyName, v1.GetOptions{IncludeUninitialized: true}) return err == nil }
go
func (k *kubernetesClient) legacyAppName(appName string) bool { statefulsets := k.client().AppsV1().StatefulSets(k.namespace) legacyName := "juju-operator-" + appName _, err := statefulsets.Get(legacyName, v1.GetOptions{IncludeUninitialized: true}) return err == nil }
[ "func", "(", "k", "*", "kubernetesClient", ")", "legacyAppName", "(", "appName", "string", ")", "bool", "{", "statefulsets", ":=", "k", ".", "client", "(", ")", ".", "AppsV1", "(", ")", ".", "StatefulSets", "(", "k", ".", "namespace", ")", "\n", "legacyName", ":=", "\"", "\"", "+", "appName", "\n", "_", ",", "err", ":=", "statefulsets", ".", "Get", "(", "legacyName", ",", "v1", ".", "GetOptions", "{", "IncludeUninitialized", ":", "true", "}", ")", "\n", "return", "err", "==", "nil", "\n", "}" ]
// legacyAppName returns true if there are any artifacts for // appName which indicate that this deployment was for Juju 2.5.0.
[ "legacyAppName", "returns", "true", "if", "there", "are", "any", "artifacts", "for", "appName", "which", "indicate", "that", "this", "deployment", "was", "for", "Juju", "2", ".", "5", ".", "0", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/caas/kubernetes/provider/k8s.go#L2575-L2580
3,932
juju/juju
worker/modelworkermanager/shim.go
Model
func (g StatePoolModelGetter) Model(modelUUID string) (Model, func(), error) { model, ph, err := g.StatePool.GetModel(modelUUID) if err != nil { return nil, nil, errors.Trace(err) } return model, func() { ph.Release() }, nil }
go
func (g StatePoolModelGetter) Model(modelUUID string) (Model, func(), error) { model, ph, err := g.StatePool.GetModel(modelUUID) if err != nil { return nil, nil, errors.Trace(err) } return model, func() { ph.Release() }, nil }
[ "func", "(", "g", "StatePoolModelGetter", ")", "Model", "(", "modelUUID", "string", ")", "(", "Model", ",", "func", "(", ")", ",", "error", ")", "{", "model", ",", "ph", ",", "err", ":=", "g", ".", "StatePool", ".", "GetModel", "(", "modelUUID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "model", ",", "func", "(", ")", "{", "ph", ".", "Release", "(", ")", "}", ",", "nil", "\n", "}" ]
// Model is part of the ModelGetter interface.
[ "Model", "is", "part", "of", "the", "ModelGetter", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/modelworkermanager/shim.go#L16-L22
3,933
juju/juju
cmd/juju/cloud/remove.go
NewRemoveCloudCommand
func NewRemoveCloudCommand() cmd.Command { store := jujuclient.NewFileClientStore() c := &removeCloudCommand{ OptionalControllerCommand: modelcmd.OptionalControllerCommand{Store: store}, store: store, } c.removeCloudAPIFunc = c.cloudAPI return modelcmd.WrapBase(c) }
go
func NewRemoveCloudCommand() cmd.Command { store := jujuclient.NewFileClientStore() c := &removeCloudCommand{ OptionalControllerCommand: modelcmd.OptionalControllerCommand{Store: store}, store: store, } c.removeCloudAPIFunc = c.cloudAPI return modelcmd.WrapBase(c) }
[ "func", "NewRemoveCloudCommand", "(", ")", "cmd", ".", "Command", "{", "store", ":=", "jujuclient", ".", "NewFileClientStore", "(", ")", "\n", "c", ":=", "&", "removeCloudCommand", "{", "OptionalControllerCommand", ":", "modelcmd", ".", "OptionalControllerCommand", "{", "Store", ":", "store", "}", ",", "store", ":", "store", ",", "}", "\n", "c", ".", "removeCloudAPIFunc", "=", "c", ".", "cloudAPI", "\n", "return", "modelcmd", ".", "WrapBase", "(", "c", ")", "\n", "}" ]
// NewRemoveCloudCommand returns a command to remove cloud information.
[ "NewRemoveCloudCommand", "returns", "a", "command", "to", "remove", "cloud", "information", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/juju/cloud/remove.go#L53-L61
3,934
juju/juju
provider/oracle/storage_volumes.go
newOracleVolumeSource
func newOracleVolumeSource(env *OracleEnviron, name, uuid string, api StorageAPI, clock clock.Clock) (*oracleVolumeSource, error) { if env == nil { return nil, errors.NotFoundf("environ") } if api == nil { return nil, errors.NotFoundf("storage client") } return &oracleVolumeSource{ env: env, envName: name, modelUUID: uuid, api: api, clock: clock, }, nil }
go
func newOracleVolumeSource(env *OracleEnviron, name, uuid string, api StorageAPI, clock clock.Clock) (*oracleVolumeSource, error) { if env == nil { return nil, errors.NotFoundf("environ") } if api == nil { return nil, errors.NotFoundf("storage client") } return &oracleVolumeSource{ env: env, envName: name, modelUUID: uuid, api: api, clock: clock, }, nil }
[ "func", "newOracleVolumeSource", "(", "env", "*", "OracleEnviron", ",", "name", ",", "uuid", "string", ",", "api", "StorageAPI", ",", "clock", "clock", ".", "Clock", ")", "(", "*", "oracleVolumeSource", ",", "error", ")", "{", "if", "env", "==", "nil", "{", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "api", "==", "nil", "{", "return", "nil", ",", "errors", ".", "NotFoundf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "oracleVolumeSource", "{", "env", ":", "env", ",", "envName", ":", "name", ",", "modelUUID", ":", "uuid", ",", "api", ":", "api", ",", "clock", ":", "clock", ",", "}", ",", "nil", "\n", "}" ]
// newOracleVolumeSource returns a new volume source to provide an interface // for creating, destroying, describing attaching and detaching volumes in the // oracle cloud environment
[ "newOracleVolumeSource", "returns", "a", "new", "volume", "source", "to", "provide", "an", "interface", "for", "creating", "destroying", "describing", "attaching", "and", "detaching", "volumes", "in", "the", "oracle", "cloud", "environment" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oracle/storage_volumes.go#L37-L53
3,935
juju/juju
provider/oracle/storage_volumes.go
resourceName
func (s *oracleVolumeSource) resourceName(tag string) string { return s.api.ComposeName(s.env.namespace.Value(s.envName + "-" + tag)) }
go
func (s *oracleVolumeSource) resourceName(tag string) string { return s.api.ComposeName(s.env.namespace.Value(s.envName + "-" + tag)) }
[ "func", "(", "s", "*", "oracleVolumeSource", ")", "resourceName", "(", "tag", "string", ")", "string", "{", "return", "s", ".", "api", ".", "ComposeName", "(", "s", ".", "env", ".", "namespace", ".", "Value", "(", "s", ".", "envName", "+", "\"", "\"", "+", "tag", ")", ")", "\n", "}" ]
// resourceName returns an oracle compatible resource name.
[ "resourceName", "returns", "an", "oracle", "compatible", "resource", "name", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oracle/storage_volumes.go#L58-L60
3,936
juju/juju
provider/oracle/storage_volumes.go
CreateVolumes
func (s *oracleVolumeSource) CreateVolumes(ctx context.ProviderCallContext, params []storage.VolumeParams) ([]storage.CreateVolumesResult, error) { if params == nil { return []storage.CreateVolumesResult{}, nil } results := make([]storage.CreateVolumesResult, len(params)) for i, volume := range params { vol, err := s.createVolume(volume) if err != nil { results[i].Error = errors.Trace(err) continue } results[i].Volume = vol } return results, nil }
go
func (s *oracleVolumeSource) CreateVolumes(ctx context.ProviderCallContext, params []storage.VolumeParams) ([]storage.CreateVolumesResult, error) { if params == nil { return []storage.CreateVolumesResult{}, nil } results := make([]storage.CreateVolumesResult, len(params)) for i, volume := range params { vol, err := s.createVolume(volume) if err != nil { results[i].Error = errors.Trace(err) continue } results[i].Volume = vol } return results, nil }
[ "func", "(", "s", "*", "oracleVolumeSource", ")", "CreateVolumes", "(", "ctx", "context", ".", "ProviderCallContext", ",", "params", "[", "]", "storage", ".", "VolumeParams", ")", "(", "[", "]", "storage", ".", "CreateVolumesResult", ",", "error", ")", "{", "if", "params", "==", "nil", "{", "return", "[", "]", "storage", ".", "CreateVolumesResult", "{", "}", ",", "nil", "\n", "}", "\n", "results", ":=", "make", "(", "[", "]", "storage", ".", "CreateVolumesResult", ",", "len", "(", "params", ")", ")", "\n", "for", "i", ",", "volume", ":=", "range", "params", "{", "vol", ",", "err", ":=", "s", ".", "createVolume", "(", "volume", ")", "\n", "if", "err", "!=", "nil", "{", "results", "[", "i", "]", ".", "Error", "=", "errors", ".", "Trace", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "results", "[", "i", "]", ".", "Volume", "=", "vol", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// CreateVolumes is specified on the storage.VolumeSource interface
[ "CreateVolumes", "is", "specified", "on", "the", "storage", ".", "VolumeSource", "interface" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oracle/storage_volumes.go#L160-L174
3,937
juju/juju
provider/oracle/storage_volumes.go
fetchVolumeStatus
func (s *oracleVolumeSource) fetchVolumeStatus(name, desiredStatus string) (complete bool, err error) { details, err := s.api.StorageVolumeDetails(name) if err != nil { return false, errors.Trace(err) } if details.Status == ociCommon.VolumeError { return false, errors.Errorf("volume entered error state: %q", details.Status_detail) } return string(details.Status) == desiredStatus, nil }
go
func (s *oracleVolumeSource) fetchVolumeStatus(name, desiredStatus string) (complete bool, err error) { details, err := s.api.StorageVolumeDetails(name) if err != nil { return false, errors.Trace(err) } if details.Status == ociCommon.VolumeError { return false, errors.Errorf("volume entered error state: %q", details.Status_detail) } return string(details.Status) == desiredStatus, nil }
[ "func", "(", "s", "*", "oracleVolumeSource", ")", "fetchVolumeStatus", "(", "name", ",", "desiredStatus", "string", ")", "(", "complete", "bool", ",", "err", "error", ")", "{", "details", ",", "err", ":=", "s", ".", "api", ".", "StorageVolumeDetails", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "if", "details", ".", "Status", "==", "ociCommon", ".", "VolumeError", "{", "return", "false", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "details", ".", "Status_detail", ")", "\n", "}", "\n", "return", "string", "(", "details", ".", "Status", ")", "==", "desiredStatus", ",", "nil", "\n", "}" ]
// fetchVolumeStatus polls the status of a volume and returns true if the current status // coincides with the desired status
[ "fetchVolumeStatus", "polls", "the", "status", "of", "a", "volume", "and", "returns", "true", "if", "the", "current", "status", "coincides", "with", "the", "desired", "status" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oracle/storage_volumes.go#L178-L188
3,938
juju/juju
provider/oracle/storage_volumes.go
fetchVolumeAttachmentStatus
func (s *oracleVolumeSource) fetchVolumeAttachmentStatus(name, desiredStatus string) (bool, error) { details, err := s.api.StorageAttachmentDetails(name) if err != nil { return false, errors.Trace(err) } return string(details.State) == desiredStatus, nil }
go
func (s *oracleVolumeSource) fetchVolumeAttachmentStatus(name, desiredStatus string) (bool, error) { details, err := s.api.StorageAttachmentDetails(name) if err != nil { return false, errors.Trace(err) } return string(details.State) == desiredStatus, nil }
[ "func", "(", "s", "*", "oracleVolumeSource", ")", "fetchVolumeAttachmentStatus", "(", "name", ",", "desiredStatus", "string", ")", "(", "bool", ",", "error", ")", "{", "details", ",", "err", ":=", "s", ".", "api", ".", "StorageAttachmentDetails", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "string", "(", "details", ".", "State", ")", "==", "desiredStatus", ",", "nil", "\n", "}" ]
// fetchVolumeAttachmentStatus polls the status of a volume attachment and returns true if the current status // coincides with the desired status
[ "fetchVolumeAttachmentStatus", "polls", "the", "status", "of", "a", "volume", "attachment", "and", "returns", "true", "if", "the", "current", "status", "coincides", "with", "the", "desired", "status" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oracle/storage_volumes.go#L192-L198
3,939
juju/juju
provider/oracle/storage_volumes.go
getFreeIndexNumber
func (s *oracleVolumeSource) getFreeIndexNumber(existing []int, max int) (int, error) { if len(existing) == 0 { return 1, nil } sort.Ints(existing) for i := 0; i <= len(existing)-1; i++ { if i+1 >= max { break } if i+1 == len(existing) { return existing[i] + 1, nil } if existing[0] > 1 { return existing[0] - 1, nil } diff := existing[i+1] - existing[i] if diff > 1 { return existing[i] + 1, nil } } return 0, errors.Errorf("no free index") }
go
func (s *oracleVolumeSource) getFreeIndexNumber(existing []int, max int) (int, error) { if len(existing) == 0 { return 1, nil } sort.Ints(existing) for i := 0; i <= len(existing)-1; i++ { if i+1 >= max { break } if i+1 == len(existing) { return existing[i] + 1, nil } if existing[0] > 1 { return existing[0] - 1, nil } diff := existing[i+1] - existing[i] if diff > 1 { return existing[i] + 1, nil } } return 0, errors.Errorf("no free index") }
[ "func", "(", "s", "*", "oracleVolumeSource", ")", "getFreeIndexNumber", "(", "existing", "[", "]", "int", ",", "max", "int", ")", "(", "int", ",", "error", ")", "{", "if", "len", "(", "existing", ")", "==", "0", "{", "return", "1", ",", "nil", "\n", "}", "\n", "sort", ".", "Ints", "(", "existing", ")", "\n", "for", "i", ":=", "0", ";", "i", "<=", "len", "(", "existing", ")", "-", "1", ";", "i", "++", "{", "if", "i", "+", "1", ">=", "max", "{", "break", "\n", "}", "\n", "if", "i", "+", "1", "==", "len", "(", "existing", ")", "{", "return", "existing", "[", "i", "]", "+", "1", ",", "nil", "\n", "}", "\n", "if", "existing", "[", "0", "]", ">", "1", "{", "return", "existing", "[", "0", "]", "-", "1", ",", "nil", "\n", "}", "\n", "diff", ":=", "existing", "[", "i", "+", "1", "]", "-", "existing", "[", "i", "]", "\n", "if", "diff", ">", "1", "{", "return", "existing", "[", "i", "]", "+", "1", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "0", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// getFreeIndexNumber returns the first unused consecutive value in a sorted array of ints // this is used to find an available index number for attaching a volume to an instance
[ "getFreeIndexNumber", "returns", "the", "first", "unused", "consecutive", "value", "in", "a", "sorted", "array", "of", "ints", "this", "is", "used", "to", "find", "an", "available", "index", "number", "for", "attaching", "a", "volume", "to", "an", "instance" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/oracle/storage_volumes.go#L475-L496
3,940
juju/juju
apiserver/common/cloudspec/cloudspec.go
NewCloudSpec
func NewCloudSpec( resources facade.Resources, getCloudSpec func(names.ModelTag) (environs.CloudSpec, error), watchCloudSpec func(tag names.ModelTag) (state.NotifyWatcher, error), getAuthFunc common.GetAuthFunc, ) CloudSpecAPI { return cloudSpecAPI{resources, getCloudSpec, watchCloudSpec, getAuthFunc} }
go
func NewCloudSpec( resources facade.Resources, getCloudSpec func(names.ModelTag) (environs.CloudSpec, error), watchCloudSpec func(tag names.ModelTag) (state.NotifyWatcher, error), getAuthFunc common.GetAuthFunc, ) CloudSpecAPI { return cloudSpecAPI{resources, getCloudSpec, watchCloudSpec, getAuthFunc} }
[ "func", "NewCloudSpec", "(", "resources", "facade", ".", "Resources", ",", "getCloudSpec", "func", "(", "names", ".", "ModelTag", ")", "(", "environs", ".", "CloudSpec", ",", "error", ")", ",", "watchCloudSpec", "func", "(", "tag", "names", ".", "ModelTag", ")", "(", "state", ".", "NotifyWatcher", ",", "error", ")", ",", "getAuthFunc", "common", ".", "GetAuthFunc", ",", ")", "CloudSpecAPI", "{", "return", "cloudSpecAPI", "{", "resources", ",", "getCloudSpec", ",", "watchCloudSpec", ",", "getAuthFunc", "}", "\n", "}" ]
// NewCloudSpec returns a new CloudSpecAPI.
[ "NewCloudSpec", "returns", "a", "new", "CloudSpecAPI", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/cloudspec/cloudspec.go#L40-L47
3,941
juju/juju
apiserver/common/cloudspec/cloudspec.go
CloudSpec
func (s cloudSpecAPI) CloudSpec(args params.Entities) (params.CloudSpecResults, error) { authFunc, err := s.getAuthFunc() if err != nil { return params.CloudSpecResults{}, err } results := params.CloudSpecResults{ Results: make([]params.CloudSpecResult, len(args.Entities)), } for i, arg := range args.Entities { tag, err := names.ParseModelTag(arg.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } if !authFunc(tag) { results.Results[i].Error = common.ServerError(common.ErrPerm) continue } results.Results[i] = s.GetCloudSpec(tag) } return results, nil }
go
func (s cloudSpecAPI) CloudSpec(args params.Entities) (params.CloudSpecResults, error) { authFunc, err := s.getAuthFunc() if err != nil { return params.CloudSpecResults{}, err } results := params.CloudSpecResults{ Results: make([]params.CloudSpecResult, len(args.Entities)), } for i, arg := range args.Entities { tag, err := names.ParseModelTag(arg.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } if !authFunc(tag) { results.Results[i].Error = common.ServerError(common.ErrPerm) continue } results.Results[i] = s.GetCloudSpec(tag) } return results, nil }
[ "func", "(", "s", "cloudSpecAPI", ")", "CloudSpec", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "CloudSpecResults", ",", "error", ")", "{", "authFunc", ",", "err", ":=", "s", ".", "getAuthFunc", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "CloudSpecResults", "{", "}", ",", "err", "\n", "}", "\n", "results", ":=", "params", ".", "CloudSpecResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "CloudSpecResult", ",", "len", "(", "args", ".", "Entities", ")", ")", ",", "}", "\n", "for", "i", ",", "arg", ":=", "range", "args", ".", "Entities", "{", "tag", ",", "err", ":=", "names", ".", "ParseModelTag", "(", "arg", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "!", "authFunc", "(", "tag", ")", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "common", ".", "ErrPerm", ")", "\n", "continue", "\n", "}", "\n", "results", ".", "Results", "[", "i", "]", "=", "s", ".", "GetCloudSpec", "(", "tag", ")", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// CloudSpec returns the model's cloud spec.
[ "CloudSpec", "returns", "the", "model", "s", "cloud", "spec", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/cloudspec/cloudspec.go#L50-L71
3,942
juju/juju
apiserver/common/cloudspec/cloudspec.go
GetCloudSpec
func (s cloudSpecAPI) GetCloudSpec(tag names.ModelTag) params.CloudSpecResult { var result params.CloudSpecResult spec, err := s.getCloudSpec(tag) if err != nil { result.Error = common.ServerError(err) return result } var paramsCloudCredential *params.CloudCredential if spec.Credential != nil && spec.Credential.AuthType() != "" { paramsCloudCredential = &params.CloudCredential{ AuthType: string(spec.Credential.AuthType()), Attributes: spec.Credential.Attributes(), } } result.Result = &params.CloudSpec{ Type: spec.Type, Name: spec.Name, Region: spec.Region, Endpoint: spec.Endpoint, IdentityEndpoint: spec.IdentityEndpoint, StorageEndpoint: spec.StorageEndpoint, Credential: paramsCloudCredential, CACertificates: spec.CACertificates, } return result }
go
func (s cloudSpecAPI) GetCloudSpec(tag names.ModelTag) params.CloudSpecResult { var result params.CloudSpecResult spec, err := s.getCloudSpec(tag) if err != nil { result.Error = common.ServerError(err) return result } var paramsCloudCredential *params.CloudCredential if spec.Credential != nil && spec.Credential.AuthType() != "" { paramsCloudCredential = &params.CloudCredential{ AuthType: string(spec.Credential.AuthType()), Attributes: spec.Credential.Attributes(), } } result.Result = &params.CloudSpec{ Type: spec.Type, Name: spec.Name, Region: spec.Region, Endpoint: spec.Endpoint, IdentityEndpoint: spec.IdentityEndpoint, StorageEndpoint: spec.StorageEndpoint, Credential: paramsCloudCredential, CACertificates: spec.CACertificates, } return result }
[ "func", "(", "s", "cloudSpecAPI", ")", "GetCloudSpec", "(", "tag", "names", ".", "ModelTag", ")", "params", ".", "CloudSpecResult", "{", "var", "result", "params", ".", "CloudSpecResult", "\n", "spec", ",", "err", ":=", "s", ".", "getCloudSpec", "(", "tag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "return", "result", "\n", "}", "\n", "var", "paramsCloudCredential", "*", "params", ".", "CloudCredential", "\n", "if", "spec", ".", "Credential", "!=", "nil", "&&", "spec", ".", "Credential", ".", "AuthType", "(", ")", "!=", "\"", "\"", "{", "paramsCloudCredential", "=", "&", "params", ".", "CloudCredential", "{", "AuthType", ":", "string", "(", "spec", ".", "Credential", ".", "AuthType", "(", ")", ")", ",", "Attributes", ":", "spec", ".", "Credential", ".", "Attributes", "(", ")", ",", "}", "\n", "}", "\n", "result", ".", "Result", "=", "&", "params", ".", "CloudSpec", "{", "Type", ":", "spec", ".", "Type", ",", "Name", ":", "spec", ".", "Name", ",", "Region", ":", "spec", ".", "Region", ",", "Endpoint", ":", "spec", ".", "Endpoint", ",", "IdentityEndpoint", ":", "spec", ".", "IdentityEndpoint", ",", "StorageEndpoint", ":", "spec", ".", "StorageEndpoint", ",", "Credential", ":", "paramsCloudCredential", ",", "CACertificates", ":", "spec", ".", "CACertificates", ",", "}", "\n", "return", "result", "\n", "}" ]
// GetCloudSpec constructs the CloudSpec for a validated and authorized model.
[ "GetCloudSpec", "constructs", "the", "CloudSpec", "for", "a", "validated", "and", "authorized", "model", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/cloudspec/cloudspec.go#L74-L99
3,943
juju/juju
apiserver/common/cloudspec/cloudspec.go
WatchCloudSpecsChanges
func (s cloudSpecAPI) WatchCloudSpecsChanges(args params.Entities) (params.NotifyWatchResults, error) { authFunc, err := s.getAuthFunc() if err != nil { return params.NotifyWatchResults{}, err } results := params.NotifyWatchResults{ Results: make([]params.NotifyWatchResult, len(args.Entities)), } for i, arg := range args.Entities { tag, err := names.ParseModelTag(arg.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } if !authFunc(tag) { results.Results[i].Error = common.ServerError(common.ErrPerm) continue } w, err := s.watchCloudSpecChanges(tag) if err == nil { results.Results[i] = w } else { results.Results[i].Error = common.ServerError(err) } } return results, nil }
go
func (s cloudSpecAPI) WatchCloudSpecsChanges(args params.Entities) (params.NotifyWatchResults, error) { authFunc, err := s.getAuthFunc() if err != nil { return params.NotifyWatchResults{}, err } results := params.NotifyWatchResults{ Results: make([]params.NotifyWatchResult, len(args.Entities)), } for i, arg := range args.Entities { tag, err := names.ParseModelTag(arg.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } if !authFunc(tag) { results.Results[i].Error = common.ServerError(common.ErrPerm) continue } w, err := s.watchCloudSpecChanges(tag) if err == nil { results.Results[i] = w } else { results.Results[i].Error = common.ServerError(err) } } return results, nil }
[ "func", "(", "s", "cloudSpecAPI", ")", "WatchCloudSpecsChanges", "(", "args", "params", ".", "Entities", ")", "(", "params", ".", "NotifyWatchResults", ",", "error", ")", "{", "authFunc", ",", "err", ":=", "s", ".", "getAuthFunc", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "params", ".", "NotifyWatchResults", "{", "}", ",", "err", "\n", "}", "\n", "results", ":=", "params", ".", "NotifyWatchResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "NotifyWatchResult", ",", "len", "(", "args", ".", "Entities", ")", ")", ",", "}", "\n", "for", "i", ",", "arg", ":=", "range", "args", ".", "Entities", "{", "tag", ",", "err", ":=", "names", ".", "ParseModelTag", "(", "arg", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "!", "authFunc", "(", "tag", ")", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "common", ".", "ErrPerm", ")", "\n", "continue", "\n", "}", "\n", "w", ",", "err", ":=", "s", ".", "watchCloudSpecChanges", "(", "tag", ")", "\n", "if", "err", "==", "nil", "{", "results", ".", "Results", "[", "i", "]", "=", "w", "\n", "}", "else", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// WatchCloudSpecsChanges returns a watcher for cloud spec changes.
[ "WatchCloudSpecsChanges", "returns", "a", "watcher", "for", "cloud", "spec", "changes", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/common/cloudspec/cloudspec.go#L102-L128
3,944
juju/juju
service/common/shell.go
IsCmdNotFoundErr
func IsCmdNotFoundErr(err error) bool { err = errors.Cause(err) if os.IsNotExist(err) { // Executable could not be found, go 1.3 and later return true } if err == exec.ErrNotFound { return true } if execErr, ok := err.(*exec.Error); ok { // Executable could not be found, go 1.2 if os.IsNotExist(execErr.Err) || execErr.Err == exec.ErrNotFound { return true } } return false }
go
func IsCmdNotFoundErr(err error) bool { err = errors.Cause(err) if os.IsNotExist(err) { // Executable could not be found, go 1.3 and later return true } if err == exec.ErrNotFound { return true } if execErr, ok := err.(*exec.Error); ok { // Executable could not be found, go 1.2 if os.IsNotExist(execErr.Err) || execErr.Err == exec.ErrNotFound { return true } } return false }
[ "func", "IsCmdNotFoundErr", "(", "err", "error", ")", "bool", "{", "err", "=", "errors", ".", "Cause", "(", "err", ")", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "// Executable could not be found, go 1.3 and later", "return", "true", "\n", "}", "\n", "if", "err", "==", "exec", ".", "ErrNotFound", "{", "return", "true", "\n", "}", "\n", "if", "execErr", ",", "ok", ":=", "err", ".", "(", "*", "exec", ".", "Error", ")", ";", "ok", "{", "// Executable could not be found, go 1.2", "if", "os", ".", "IsNotExist", "(", "execErr", ".", "Err", ")", "||", "execErr", ".", "Err", "==", "exec", ".", "ErrNotFound", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsCmdNotFoundErr returns true if the provided error indicates that the // command passed to exec.LookPath or exec.Command was not found.
[ "IsCmdNotFoundErr", "returns", "true", "if", "the", "provided", "error", "indicates", "that", "the", "command", "passed", "to", "exec", ".", "LookPath", "or", "exec", ".", "Command", "was", "not", "found", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/service/common/shell.go#L15-L31
3,945
juju/juju
environs/config/source.go
AllAttrs
func (c ConfigValues) AllAttrs() map[string]interface{} { result := make(map[string]interface{}) for attr, val := range c { result[attr] = val } return result }
go
func (c ConfigValues) AllAttrs() map[string]interface{} { result := make(map[string]interface{}) for attr, val := range c { result[attr] = val } return result }
[ "func", "(", "c", "ConfigValues", ")", "AllAttrs", "(", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "result", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "for", "attr", ",", "val", ":=", "range", "c", "{", "result", "[", "attr", "]", "=", "val", "\n", "}", "\n", "return", "result", "\n", "}" ]
// AllAttrs returns just the attribute values from the config.
[ "AllAttrs", "returns", "just", "the", "attribute", "values", "from", "the", "config", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/config/source.go#L47-L53
3,946
juju/juju
worker/singular/shim.go
NewFacade
func NewFacade(apiCaller base.APICaller, claimant names.MachineTag, entity names.Tag) (Facade, error) { facade, err := singular.NewAPI(apiCaller, claimant, entity) if err != nil { return nil, errors.Trace(err) } return facade, nil }
go
func NewFacade(apiCaller base.APICaller, claimant names.MachineTag, entity names.Tag) (Facade, error) { facade, err := singular.NewAPI(apiCaller, claimant, entity) if err != nil { return nil, errors.Trace(err) } return facade, nil }
[ "func", "NewFacade", "(", "apiCaller", "base", ".", "APICaller", ",", "claimant", "names", ".", "MachineTag", ",", "entity", "names", ".", "Tag", ")", "(", "Facade", ",", "error", ")", "{", "facade", ",", "err", ":=", "singular", ".", "NewAPI", "(", "apiCaller", ",", "claimant", ",", "entity", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "facade", ",", "nil", "\n", "}" ]
// NewFacade creates a Facade from an APICaller and an entity for which // administrative control will be claimed. It's a suitable default value // for ManifoldConfig.NewFacade.
[ "NewFacade", "creates", "a", "Facade", "from", "an", "APICaller", "and", "an", "entity", "for", "which", "administrative", "control", "will", "be", "claimed", ".", "It", "s", "a", "suitable", "default", "value", "for", "ManifoldConfig", ".", "NewFacade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/singular/shim.go#L18-L24
3,947
juju/juju
worker/singular/shim.go
NewWorker
func NewWorker(config FlagConfig) (worker.Worker, error) { worker, err := NewFlagWorker(config) if err != nil { return nil, errors.Trace(err) } return worker, nil }
go
func NewWorker(config FlagConfig) (worker.Worker, error) { worker, err := NewFlagWorker(config) if err != nil { return nil, errors.Trace(err) } return worker, nil }
[ "func", "NewWorker", "(", "config", "FlagConfig", ")", "(", "worker", ".", "Worker", ",", "error", ")", "{", "worker", ",", "err", ":=", "NewFlagWorker", "(", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "worker", ",", "nil", "\n", "}" ]
// NewWorker calls NewFlagWorker but returns a more convenient type. It's // a suitable default value for ManifoldConfig.NewWorker.
[ "NewWorker", "calls", "NewFlagWorker", "but", "returns", "a", "more", "convenient", "type", ".", "It", "s", "a", "suitable", "default", "value", "for", "ManifoldConfig", ".", "NewWorker", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/singular/shim.go#L28-L34
3,948
juju/juju
worker/simpleworker.go
NewSimpleWorker
func NewSimpleWorker(doWork func(stopCh <-chan struct{}) error) worker.Worker { w := &simpleWorker{} w.tomb.Go(func() error { return doWork(w.tomb.Dying()) }) return w }
go
func NewSimpleWorker(doWork func(stopCh <-chan struct{}) error) worker.Worker { w := &simpleWorker{} w.tomb.Go(func() error { return doWork(w.tomb.Dying()) }) return w }
[ "func", "NewSimpleWorker", "(", "doWork", "func", "(", "stopCh", "<-", "chan", "struct", "{", "}", ")", "error", ")", "worker", ".", "Worker", "{", "w", ":=", "&", "simpleWorker", "{", "}", "\n", "w", ".", "tomb", ".", "Go", "(", "func", "(", ")", "error", "{", "return", "doWork", "(", "w", ".", "tomb", ".", "Dying", "(", ")", ")", "\n", "}", ")", "\n", "return", "w", "\n", "}" ]
// NewSimpleWorker returns a worker that runs the given function. The // stopCh argument will be closed when the worker is killed. The error returned // by the doWork function will be returned by the worker's Wait function.
[ "NewSimpleWorker", "returns", "a", "worker", "that", "runs", "the", "given", "function", ".", "The", "stopCh", "argument", "will", "be", "closed", "when", "the", "worker", "is", "killed", ".", "The", "error", "returned", "by", "the", "doWork", "function", "will", "be", "returned", "by", "the", "worker", "s", "Wait", "function", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/simpleworker.go#L19-L25
3,949
juju/juju
payload/context/unregister.go
NewUnregisterCmd
func NewUnregisterCmd(ctx HookContext) (*UnregisterCmd, error) { return &UnregisterCmd{hookContextFunc: componentHookContext(ctx)}, nil }
go
func NewUnregisterCmd(ctx HookContext) (*UnregisterCmd, error) { return &UnregisterCmd{hookContextFunc: componentHookContext(ctx)}, nil }
[ "func", "NewUnregisterCmd", "(", "ctx", "HookContext", ")", "(", "*", "UnregisterCmd", ",", "error", ")", "{", "return", "&", "UnregisterCmd", "{", "hookContextFunc", ":", "componentHookContext", "(", "ctx", ")", "}", ",", "nil", "\n", "}" ]
// NewUnregisterCmd returns a new UnregisterCmd that wraps the given context.
[ "NewUnregisterCmd", "returns", "a", "new", "UnregisterCmd", "that", "wraps", "the", "given", "context", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/payload/context/unregister.go#L26-L28
3,950
juju/juju
payload/context/unregister.go
Run
func (c *UnregisterCmd) Run(ctx *cmd.Context) error { //TODO(wwitzel3) make Unregister accept class and id and // compose the ID in the API layer using BuildID logger.Tracef(`Running unregister command with id "%s/%s"`, c.class, c.id) hctx, err := c.hookContextFunc() if err != nil { return errors.Trace(err) } // TODO(ericsnow) Verify that Untrack gives a meaningful error when // the ID is not found. if err := hctx.Untrack(c.class, c.id); err != nil { return errors.Trace(err) } // TODO(ericsnow) Is the flush really necessary? // We flush to state immediately so that status reflects the // payload correctly. if err := hctx.Flush(); err != nil { return errors.Trace(err) } return nil }
go
func (c *UnregisterCmd) Run(ctx *cmd.Context) error { //TODO(wwitzel3) make Unregister accept class and id and // compose the ID in the API layer using BuildID logger.Tracef(`Running unregister command with id "%s/%s"`, c.class, c.id) hctx, err := c.hookContextFunc() if err != nil { return errors.Trace(err) } // TODO(ericsnow) Verify that Untrack gives a meaningful error when // the ID is not found. if err := hctx.Untrack(c.class, c.id); err != nil { return errors.Trace(err) } // TODO(ericsnow) Is the flush really necessary? // We flush to state immediately so that status reflects the // payload correctly. if err := hctx.Flush(); err != nil { return errors.Trace(err) } return nil }
[ "func", "(", "c", "*", "UnregisterCmd", ")", "Run", "(", "ctx", "*", "cmd", ".", "Context", ")", "error", "{", "//TODO(wwitzel3) make Unregister accept class and id and", "// compose the ID in the API layer using BuildID", "logger", ".", "Tracef", "(", "`Running unregister command with id \"%s/%s\"`", ",", "c", ".", "class", ",", "c", ".", "id", ")", "\n\n", "hctx", ",", "err", ":=", "c", ".", "hookContextFunc", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "// TODO(ericsnow) Verify that Untrack gives a meaningful error when", "// the ID is not found.", "if", "err", ":=", "hctx", ".", "Untrack", "(", "c", ".", "class", ",", "c", ".", "id", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "// TODO(ericsnow) Is the flush really necessary?", "// We flush to state immediately so that status reflects the", "// payload correctly.", "if", "err", ":=", "hctx", ".", "Flush", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Run runs the unregister command.
[ "Run", "runs", "the", "unregister", "command", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/payload/context/unregister.go#L61-L86
3,951
juju/juju
cmd/jujud/agent/introspection.go
startIntrospection
func startIntrospection(cfg introspectionConfig) error { if runtime.GOOS != "linux" { logger.Debugf("introspection worker not supported on %q", runtime.GOOS) return nil } socketName := cfg.NewSocketName(cfg.Agent.CurrentConfig().Tag()) w, err := cfg.WorkerFunc(introspection.Config{ SocketName: socketName, DepEngine: cfg.Engine, StatePool: cfg.StatePoolReporter, PubSub: cfg.PubSubReporter, MachineLock: cfg.MachineLock, PrometheusGatherer: cfg.PrometheusGatherer, Presence: cfg.PresenceRecorder, }) if err != nil { return errors.Trace(err) } go func() { cfg.Engine.Wait() logger.Debugf("engine stopped, stopping introspection") w.Kill() w.Wait() logger.Debugf("introspection stopped") }() return nil }
go
func startIntrospection(cfg introspectionConfig) error { if runtime.GOOS != "linux" { logger.Debugf("introspection worker not supported on %q", runtime.GOOS) return nil } socketName := cfg.NewSocketName(cfg.Agent.CurrentConfig().Tag()) w, err := cfg.WorkerFunc(introspection.Config{ SocketName: socketName, DepEngine: cfg.Engine, StatePool: cfg.StatePoolReporter, PubSub: cfg.PubSubReporter, MachineLock: cfg.MachineLock, PrometheusGatherer: cfg.PrometheusGatherer, Presence: cfg.PresenceRecorder, }) if err != nil { return errors.Trace(err) } go func() { cfg.Engine.Wait() logger.Debugf("engine stopped, stopping introspection") w.Kill() w.Wait() logger.Debugf("introspection stopped") }() return nil }
[ "func", "startIntrospection", "(", "cfg", "introspectionConfig", ")", "error", "{", "if", "runtime", ".", "GOOS", "!=", "\"", "\"", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "runtime", ".", "GOOS", ")", "\n", "return", "nil", "\n", "}", "\n\n", "socketName", ":=", "cfg", ".", "NewSocketName", "(", "cfg", ".", "Agent", ".", "CurrentConfig", "(", ")", ".", "Tag", "(", ")", ")", "\n", "w", ",", "err", ":=", "cfg", ".", "WorkerFunc", "(", "introspection", ".", "Config", "{", "SocketName", ":", "socketName", ",", "DepEngine", ":", "cfg", ".", "Engine", ",", "StatePool", ":", "cfg", ".", "StatePoolReporter", ",", "PubSub", ":", "cfg", ".", "PubSubReporter", ",", "MachineLock", ":", "cfg", ".", "MachineLock", ",", "PrometheusGatherer", ":", "cfg", ".", "PrometheusGatherer", ",", "Presence", ":", "cfg", ".", "PresenceRecorder", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "go", "func", "(", ")", "{", "cfg", ".", "Engine", ".", "Wait", "(", ")", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ")", "\n", "w", ".", "Kill", "(", ")", "\n", "w", ".", "Wait", "(", ")", "\n", "logger", ".", "Debugf", "(", "\"", "\"", ")", "\n", "}", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// startIntrospection creates the introspection worker. It cannot and should // not be in the engine itself as it reports on the engine, and other aspects // of the runtime. If we put it in the engine, then it is mostly likely shut // down in the times we need it most, which is when the agent is having // problems shutting down. Here we effectively start the worker and tie its // life to that of the engine that is returned.
[ "startIntrospection", "creates", "the", "introspection", "worker", ".", "It", "cannot", "and", "should", "not", "be", "in", "the", "engine", "itself", "as", "it", "reports", "on", "the", "engine", "and", "other", "aspects", "of", "the", "runtime", ".", "If", "we", "put", "it", "in", "the", "engine", "then", "it", "is", "mostly", "likely", "shut", "down", "in", "the", "times", "we", "need", "it", "most", "which", "is", "when", "the", "agent", "is", "having", "problems", "shutting", "down", ".", "Here", "we", "effectively", "start", "the", "worker", "and", "tie", "its", "life", "to", "that", "of", "the", "engine", "that", "is", "returned", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/introspection.go#L50-L78
3,952
juju/juju
cmd/jujud/agent/introspection.go
newPrometheusRegistry
func newPrometheusRegistry() (*prometheus.Registry, error) { r := prometheus.NewRegistry() if err := r.Register(prometheus.NewGoCollector()); err != nil { return nil, errors.Trace(err) } if err := r.Register(prometheus.NewProcessCollector( prometheus.ProcessCollectorOpts{})); err != nil { return nil, errors.Trace(err) } return r, nil }
go
func newPrometheusRegistry() (*prometheus.Registry, error) { r := prometheus.NewRegistry() if err := r.Register(prometheus.NewGoCollector()); err != nil { return nil, errors.Trace(err) } if err := r.Register(prometheus.NewProcessCollector( prometheus.ProcessCollectorOpts{})); err != nil { return nil, errors.Trace(err) } return r, nil }
[ "func", "newPrometheusRegistry", "(", ")", "(", "*", "prometheus", ".", "Registry", ",", "error", ")", "{", "r", ":=", "prometheus", ".", "NewRegistry", "(", ")", "\n", "if", "err", ":=", "r", ".", "Register", "(", "prometheus", ".", "NewGoCollector", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "r", ".", "Register", "(", "prometheus", ".", "NewProcessCollector", "(", "prometheus", ".", "ProcessCollectorOpts", "{", "}", ")", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "r", ",", "nil", "\n", "}" ]
// newPrometheusRegistry returns a new prometheus.Registry with // the Go and process metric collectors registered. This registry // is exposed by the introspection abstract domain socket on all // Linux agents.
[ "newPrometheusRegistry", "returns", "a", "new", "prometheus", ".", "Registry", "with", "the", "Go", "and", "process", "metric", "collectors", "registered", ".", "This", "registry", "is", "exposed", "by", "the", "introspection", "abstract", "domain", "socket", "on", "all", "Linux", "agents", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/cmd/jujud/agent/introspection.go#L84-L94
3,953
juju/juju
provider/azure/internal/iputils/iputils.go
NextSubnetIP
func NextSubnetIP(subnet *net.IPNet, ipsInUse []net.IP) (net.IP, error) { ones, bits := subnet.Mask.Size() subnetMaskUint32 := ipUint32(net.IP(subnet.Mask)) inUse := big.NewInt(0) for _, ip := range ipsInUse { if !subnet.Contains(ip) { continue } index := ipIndex(ip, subnetMaskUint32) inUse = inUse.SetBit(inUse, index, 1) } // Now iterate through all addresses in the subnet and return the // first address that is not in use. We start at the first non- // reserved address, and stop short of the last address in the // subnet (i.e. all non-mask bits set), which is the broadcast // address for the subnet. n := ipUint32(subnet.IP) for i := reservedAddressRangeEnd + 1; i < (1<<uint64(bits-ones) - 1); i++ { ip := uint32IP(n + uint32(i)) if !ip.IsGlobalUnicast() { continue } index := ipIndex(ip, subnetMaskUint32) if inUse.Bit(index) == 0 { return ip, nil } } return nil, errors.Errorf("no addresses available in %s", subnet) }
go
func NextSubnetIP(subnet *net.IPNet, ipsInUse []net.IP) (net.IP, error) { ones, bits := subnet.Mask.Size() subnetMaskUint32 := ipUint32(net.IP(subnet.Mask)) inUse := big.NewInt(0) for _, ip := range ipsInUse { if !subnet.Contains(ip) { continue } index := ipIndex(ip, subnetMaskUint32) inUse = inUse.SetBit(inUse, index, 1) } // Now iterate through all addresses in the subnet and return the // first address that is not in use. We start at the first non- // reserved address, and stop short of the last address in the // subnet (i.e. all non-mask bits set), which is the broadcast // address for the subnet. n := ipUint32(subnet.IP) for i := reservedAddressRangeEnd + 1; i < (1<<uint64(bits-ones) - 1); i++ { ip := uint32IP(n + uint32(i)) if !ip.IsGlobalUnicast() { continue } index := ipIndex(ip, subnetMaskUint32) if inUse.Bit(index) == 0 { return ip, nil } } return nil, errors.Errorf("no addresses available in %s", subnet) }
[ "func", "NextSubnetIP", "(", "subnet", "*", "net", ".", "IPNet", ",", "ipsInUse", "[", "]", "net", ".", "IP", ")", "(", "net", ".", "IP", ",", "error", ")", "{", "ones", ",", "bits", ":=", "subnet", ".", "Mask", ".", "Size", "(", ")", "\n", "subnetMaskUint32", ":=", "ipUint32", "(", "net", ".", "IP", "(", "subnet", ".", "Mask", ")", ")", "\n\n", "inUse", ":=", "big", ".", "NewInt", "(", "0", ")", "\n", "for", "_", ",", "ip", ":=", "range", "ipsInUse", "{", "if", "!", "subnet", ".", "Contains", "(", "ip", ")", "{", "continue", "\n", "}", "\n", "index", ":=", "ipIndex", "(", "ip", ",", "subnetMaskUint32", ")", "\n", "inUse", "=", "inUse", ".", "SetBit", "(", "inUse", ",", "index", ",", "1", ")", "\n", "}", "\n\n", "// Now iterate through all addresses in the subnet and return the", "// first address that is not in use. We start at the first non-", "// reserved address, and stop short of the last address in the", "// subnet (i.e. all non-mask bits set), which is the broadcast", "// address for the subnet.", "n", ":=", "ipUint32", "(", "subnet", ".", "IP", ")", "\n", "for", "i", ":=", "reservedAddressRangeEnd", "+", "1", ";", "i", "<", "(", "1", "<<", "uint64", "(", "bits", "-", "ones", ")", "-", "1", ")", ";", "i", "++", "{", "ip", ":=", "uint32IP", "(", "n", "+", "uint32", "(", "i", ")", ")", "\n", "if", "!", "ip", ".", "IsGlobalUnicast", "(", ")", "{", "continue", "\n", "}", "\n", "index", ":=", "ipIndex", "(", "ip", ",", "subnetMaskUint32", ")", "\n", "if", "inUse", ".", "Bit", "(", "index", ")", "==", "0", "{", "return", "ip", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "subnet", ")", "\n", "}" ]
// NextSubnetIP returns the next available IP address in a given subnet.
[ "NextSubnetIP", "returns", "the", "next", "available", "IP", "address", "in", "a", "given", "subnet", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/azure/internal/iputils/iputils.go#L18-L48
3,954
juju/juju
provider/azure/internal/iputils/iputils.go
NthSubnetIP
func NthSubnetIP(subnet *net.IPNet, n int) net.IP { ones, bits := subnet.Mask.Size() base := ipUint32(subnet.IP) var valid int for i := reservedAddressRangeEnd + 1; i < (1<<uint64(bits-ones) - 1); i++ { ip := uint32IP(base + uint32(i)) if !ip.IsGlobalUnicast() { continue } if n == valid { return ip } valid++ } return nil }
go
func NthSubnetIP(subnet *net.IPNet, n int) net.IP { ones, bits := subnet.Mask.Size() base := ipUint32(subnet.IP) var valid int for i := reservedAddressRangeEnd + 1; i < (1<<uint64(bits-ones) - 1); i++ { ip := uint32IP(base + uint32(i)) if !ip.IsGlobalUnicast() { continue } if n == valid { return ip } valid++ } return nil }
[ "func", "NthSubnetIP", "(", "subnet", "*", "net", ".", "IPNet", ",", "n", "int", ")", "net", ".", "IP", "{", "ones", ",", "bits", ":=", "subnet", ".", "Mask", ".", "Size", "(", ")", "\n", "base", ":=", "ipUint32", "(", "subnet", ".", "IP", ")", "\n", "var", "valid", "int", "\n", "for", "i", ":=", "reservedAddressRangeEnd", "+", "1", ";", "i", "<", "(", "1", "<<", "uint64", "(", "bits", "-", "ones", ")", "-", "1", ")", ";", "i", "++", "{", "ip", ":=", "uint32IP", "(", "base", "+", "uint32", "(", "i", ")", ")", "\n", "if", "!", "ip", ".", "IsGlobalUnicast", "(", ")", "{", "continue", "\n", "}", "\n", "if", "n", "==", "valid", "{", "return", "ip", "\n", "}", "\n", "valid", "++", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// NthSubnetIP returns the n'th IP address in a given subnet, where n is a // zero-based index, zero being the first available IP address in the subnet. // // If n is out of range, NthSubnetIP will return nil.
[ "NthSubnetIP", "returns", "the", "n", "th", "IP", "address", "in", "a", "given", "subnet", "where", "n", "is", "a", "zero", "-", "based", "index", "zero", "being", "the", "first", "available", "IP", "address", "in", "the", "subnet", ".", "If", "n", "is", "out", "of", "range", "NthSubnetIP", "will", "return", "nil", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/provider/azure/internal/iputils/iputils.go#L54-L69
3,955
juju/juju
worker/logforwarder/logforwarder.go
processNewConfig
func (lf *LogForwarder) processNewConfig(currentSender SendCloser) (SendCloser, error) { lf.mu.Lock() defer lf.mu.Unlock() closeExisting := func() error { lf.enabled = false // If we are already sending, close the current sender. if currentSender != nil { return currentSender.Close() } return nil } // Get the new config and set up log forwarding if enabled. cfg, ok, err := lf.args.LogForwardConfig.LogForwardConfig() if err != nil { closeExisting() return nil, errors.Trace(err) } if !ok || !cfg.Enabled { logger.Infof("config change - log forwarding not enabled") return nil, closeExisting() } // If the config is not valid, we don't want to exit with an error // and bounce the worker; we'll just log the issue and wait for another // config change to come through. // We'll continue sending using the current sink. if err := cfg.Validate(); err != nil { logger.Errorf("invalid log forward config change: %v", err) return currentSender, nil } // Shutdown the existing sink since we need to now create a new one. if err := closeExisting(); err != nil { return nil, errors.Trace(err) } sink, err := OpenTrackingSink(TrackingSinkArgs{ Name: lf.args.Name, Config: cfg, Caller: lf.args.Caller, OpenSink: lf.args.OpenSink, }) if err != nil { return nil, errors.Trace(err) } lf.enabledCh <- true return sink, nil }
go
func (lf *LogForwarder) processNewConfig(currentSender SendCloser) (SendCloser, error) { lf.mu.Lock() defer lf.mu.Unlock() closeExisting := func() error { lf.enabled = false // If we are already sending, close the current sender. if currentSender != nil { return currentSender.Close() } return nil } // Get the new config and set up log forwarding if enabled. cfg, ok, err := lf.args.LogForwardConfig.LogForwardConfig() if err != nil { closeExisting() return nil, errors.Trace(err) } if !ok || !cfg.Enabled { logger.Infof("config change - log forwarding not enabled") return nil, closeExisting() } // If the config is not valid, we don't want to exit with an error // and bounce the worker; we'll just log the issue and wait for another // config change to come through. // We'll continue sending using the current sink. if err := cfg.Validate(); err != nil { logger.Errorf("invalid log forward config change: %v", err) return currentSender, nil } // Shutdown the existing sink since we need to now create a new one. if err := closeExisting(); err != nil { return nil, errors.Trace(err) } sink, err := OpenTrackingSink(TrackingSinkArgs{ Name: lf.args.Name, Config: cfg, Caller: lf.args.Caller, OpenSink: lf.args.OpenSink, }) if err != nil { return nil, errors.Trace(err) } lf.enabledCh <- true return sink, nil }
[ "func", "(", "lf", "*", "LogForwarder", ")", "processNewConfig", "(", "currentSender", "SendCloser", ")", "(", "SendCloser", ",", "error", ")", "{", "lf", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "lf", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "closeExisting", ":=", "func", "(", ")", "error", "{", "lf", ".", "enabled", "=", "false", "\n", "// If we are already sending, close the current sender.", "if", "currentSender", "!=", "nil", "{", "return", "currentSender", ".", "Close", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "// Get the new config and set up log forwarding if enabled.", "cfg", ",", "ok", ",", "err", ":=", "lf", ".", "args", ".", "LogForwardConfig", ".", "LogForwardConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "closeExisting", "(", ")", "\n", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "!", "ok", "||", "!", "cfg", ".", "Enabled", "{", "logger", ".", "Infof", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "closeExisting", "(", ")", "\n", "}", "\n", "// If the config is not valid, we don't want to exit with an error", "// and bounce the worker; we'll just log the issue and wait for another", "// config change to come through.", "// We'll continue sending using the current sink.", "if", "err", ":=", "cfg", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "currentSender", ",", "nil", "\n", "}", "\n\n", "// Shutdown the existing sink since we need to now create a new one.", "if", "err", ":=", "closeExisting", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "sink", ",", "err", ":=", "OpenTrackingSink", "(", "TrackingSinkArgs", "{", "Name", ":", "lf", ".", "args", ".", "Name", ",", "Config", ":", "cfg", ",", "Caller", ":", "lf", ".", "args", ".", "Caller", ",", "OpenSink", ":", "lf", ".", "args", ".", "OpenSink", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "lf", ".", "enabledCh", "<-", "true", "\n", "return", "sink", ",", "nil", "\n", "}" ]
// processNewConfig acts on a new syslog forward config change.
[ "processNewConfig", "acts", "on", "a", "new", "syslog", "forward", "config", "change", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/logforwarder/logforwarder.go#L80-L127
3,956
juju/juju
worker/logforwarder/logforwarder.go
waitForEnabled
func (lf *LogForwarder) waitForEnabled() (bool, error) { lf.mu.Lock() enabled := lf.enabled lf.mu.Unlock() if enabled { return true, nil } select { case <-lf.catacomb.Dying(): return false, tomb.ErrDying case enabled = <-lf.enabledCh: } lf.mu.Lock() defer lf.mu.Unlock() if !lf.enabled && enabled { logger.Infof("log forward enabled, starting to stream logs to syslog sink") } lf.enabled = enabled return enabled, nil }
go
func (lf *LogForwarder) waitForEnabled() (bool, error) { lf.mu.Lock() enabled := lf.enabled lf.mu.Unlock() if enabled { return true, nil } select { case <-lf.catacomb.Dying(): return false, tomb.ErrDying case enabled = <-lf.enabledCh: } lf.mu.Lock() defer lf.mu.Unlock() if !lf.enabled && enabled { logger.Infof("log forward enabled, starting to stream logs to syslog sink") } lf.enabled = enabled return enabled, nil }
[ "func", "(", "lf", "*", "LogForwarder", ")", "waitForEnabled", "(", ")", "(", "bool", ",", "error", ")", "{", "lf", ".", "mu", ".", "Lock", "(", ")", "\n", "enabled", ":=", "lf", ".", "enabled", "\n", "lf", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "enabled", "{", "return", "true", ",", "nil", "\n", "}", "\n\n", "select", "{", "case", "<-", "lf", ".", "catacomb", ".", "Dying", "(", ")", ":", "return", "false", ",", "tomb", ".", "ErrDying", "\n", "case", "enabled", "=", "<-", "lf", ".", "enabledCh", ":", "}", "\n", "lf", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "lf", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "!", "lf", ".", "enabled", "&&", "enabled", "{", "logger", ".", "Infof", "(", "\"", "\"", ")", "\n", "}", "\n", "lf", ".", "enabled", "=", "enabled", "\n", "return", "enabled", ",", "nil", "\n", "}" ]
// waitForEnabled returns true if streaming is enabled. // Otherwise if blocks and waits for enabled to be true.
[ "waitForEnabled", "returns", "true", "if", "streaming", "is", "enabled", ".", "Otherwise", "if", "blocks", "and", "waits", "for", "enabled", "to", "be", "true", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/logforwarder/logforwarder.go#L131-L152
3,957
juju/juju
worker/logforwarder/logforwarder.go
NewLogForwarder
func NewLogForwarder(args OpenLogForwarderArgs) (*LogForwarder, error) { lf := &LogForwarder{ args: args, enabledCh: make(chan bool, 1), } err := catacomb.Invoke(catacomb.Plan{ Site: &lf.catacomb, Work: func() error { return errors.Trace(lf.loop()) }, }) if err != nil { return nil, errors.Trace(err) } return lf, nil }
go
func NewLogForwarder(args OpenLogForwarderArgs) (*LogForwarder, error) { lf := &LogForwarder{ args: args, enabledCh: make(chan bool, 1), } err := catacomb.Invoke(catacomb.Plan{ Site: &lf.catacomb, Work: func() error { return errors.Trace(lf.loop()) }, }) if err != nil { return nil, errors.Trace(err) } return lf, nil }
[ "func", "NewLogForwarder", "(", "args", "OpenLogForwarderArgs", ")", "(", "*", "LogForwarder", ",", "error", ")", "{", "lf", ":=", "&", "LogForwarder", "{", "args", ":", "args", ",", "enabledCh", ":", "make", "(", "chan", "bool", ",", "1", ")", ",", "}", "\n", "err", ":=", "catacomb", ".", "Invoke", "(", "catacomb", ".", "Plan", "{", "Site", ":", "&", "lf", ".", "catacomb", ",", "Work", ":", "func", "(", ")", "error", "{", "return", "errors", ".", "Trace", "(", "lf", ".", "loop", "(", ")", ")", "\n", "}", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "lf", ",", "nil", "\n", "}" ]
// NewLogForwarder returns a worker that forwards logs received from // the stream to the sender.
[ "NewLogForwarder", "returns", "a", "worker", "that", "forwards", "logs", "received", "from", "the", "stream", "to", "the", "sender", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/logforwarder/logforwarder.go#L156-L171
3,958
juju/juju
worker/instancemutater/mutater.go
watchProfileChangesLoop
func (m MutaterMachine) watchProfileChangesLoop(removed <-chan struct{}, profileChangeWatcher watcher.NotifyWatcher) error { m.logger.Tracef("watching change on MutaterMachine %s", m.id) for { select { case <-m.context.dying(): return m.context.errDying() case <-profileChangeWatcher.Changes(): info, err := m.machineApi.CharmProfilingInfo() if err != nil { // If the machine is not provisioned then we need to wait for // new changes from the watcher. if params.IsCodeNotProvisioned(errors.Cause(err)) { m.logger.Tracef("got not provisioned machine-%s on charm profiling info, wait for another change", m.id) continue } return errors.Trace(err) } if err = m.processMachineProfileChanges(info); err != nil && errors.IsNotValid(err) { // Return to stop mutating the machine, but no need to restart // the worker. return nil } else if err != nil { return errors.Trace(err) } case <-removed: if err := m.machineApi.Refresh(); err != nil { return errors.Trace(err) } if m.machineApi.Life() == params.Dead { return nil } } } }
go
func (m MutaterMachine) watchProfileChangesLoop(removed <-chan struct{}, profileChangeWatcher watcher.NotifyWatcher) error { m.logger.Tracef("watching change on MutaterMachine %s", m.id) for { select { case <-m.context.dying(): return m.context.errDying() case <-profileChangeWatcher.Changes(): info, err := m.machineApi.CharmProfilingInfo() if err != nil { // If the machine is not provisioned then we need to wait for // new changes from the watcher. if params.IsCodeNotProvisioned(errors.Cause(err)) { m.logger.Tracef("got not provisioned machine-%s on charm profiling info, wait for another change", m.id) continue } return errors.Trace(err) } if err = m.processMachineProfileChanges(info); err != nil && errors.IsNotValid(err) { // Return to stop mutating the machine, but no need to restart // the worker. return nil } else if err != nil { return errors.Trace(err) } case <-removed: if err := m.machineApi.Refresh(); err != nil { return errors.Trace(err) } if m.machineApi.Life() == params.Dead { return nil } } } }
[ "func", "(", "m", "MutaterMachine", ")", "watchProfileChangesLoop", "(", "removed", "<-", "chan", "struct", "{", "}", ",", "profileChangeWatcher", "watcher", ".", "NotifyWatcher", ")", "error", "{", "m", ".", "logger", ".", "Tracef", "(", "\"", "\"", ",", "m", ".", "id", ")", "\n", "for", "{", "select", "{", "case", "<-", "m", ".", "context", ".", "dying", "(", ")", ":", "return", "m", ".", "context", ".", "errDying", "(", ")", "\n", "case", "<-", "profileChangeWatcher", ".", "Changes", "(", ")", ":", "info", ",", "err", ":=", "m", ".", "machineApi", ".", "CharmProfilingInfo", "(", ")", "\n", "if", "err", "!=", "nil", "{", "// If the machine is not provisioned then we need to wait for", "// new changes from the watcher.", "if", "params", ".", "IsCodeNotProvisioned", "(", "errors", ".", "Cause", "(", "err", ")", ")", "{", "m", ".", "logger", ".", "Tracef", "(", "\"", "\"", ",", "m", ".", "id", ")", "\n", "continue", "\n", "}", "\n", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", "=", "m", ".", "processMachineProfileChanges", "(", "info", ")", ";", "err", "!=", "nil", "&&", "errors", ".", "IsNotValid", "(", "err", ")", "{", "// Return to stop mutating the machine, but no need to restart", "// the worker.", "return", "nil", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "case", "<-", "removed", ":", "if", "err", ":=", "m", ".", "machineApi", ".", "Refresh", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "m", ".", "machineApi", ".", "Life", "(", ")", "==", "params", ".", "Dead", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// watchProfileChanges, any error returned will cause the worker to restart.
[ "watchProfileChanges", "any", "error", "returned", "will", "cause", "the", "worker", "to", "restart", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/instancemutater/mutater.go#L125-L158
3,959
juju/juju
apiserver/facades/client/controller/controller.go
NewControllerAPIv7
func NewControllerAPIv7(ctx facade.Context) (*ControllerAPI, error) { st := ctx.State() authorizer := ctx.Auth() pool := ctx.StatePool() resources := ctx.Resources() presence := ctx.Presence() hub := ctx.Hub() return NewControllerAPI( st, pool, authorizer, resources, presence, hub, ) }
go
func NewControllerAPIv7(ctx facade.Context) (*ControllerAPI, error) { st := ctx.State() authorizer := ctx.Auth() pool := ctx.StatePool() resources := ctx.Resources() presence := ctx.Presence() hub := ctx.Hub() return NewControllerAPI( st, pool, authorizer, resources, presence, hub, ) }
[ "func", "NewControllerAPIv7", "(", "ctx", "facade", ".", "Context", ")", "(", "*", "ControllerAPI", ",", "error", ")", "{", "st", ":=", "ctx", ".", "State", "(", ")", "\n", "authorizer", ":=", "ctx", ".", "Auth", "(", ")", "\n", "pool", ":=", "ctx", ".", "StatePool", "(", ")", "\n", "resources", ":=", "ctx", ".", "Resources", "(", ")", "\n", "presence", ":=", "ctx", ".", "Presence", "(", ")", "\n", "hub", ":=", "ctx", ".", "Hub", "(", ")", "\n\n", "return", "NewControllerAPI", "(", "st", ",", "pool", ",", "authorizer", ",", "resources", ",", "presence", ",", "hub", ",", ")", "\n", "}" ]
// NewControllerAPIv7 creates a new ControllerAPIv7.
[ "NewControllerAPIv7", "creates", "a", "new", "ControllerAPIv7", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/controller/controller.go#L78-L94
3,960
juju/juju
apiserver/facades/client/controller/controller.go
NewControllerAPIv6
func NewControllerAPIv6(ctx facade.Context) (*ControllerAPIv6, error) { v7, err := NewControllerAPIv7(ctx) if err != nil { return nil, errors.Trace(err) } return &ControllerAPIv6{v7}, nil }
go
func NewControllerAPIv6(ctx facade.Context) (*ControllerAPIv6, error) { v7, err := NewControllerAPIv7(ctx) if err != nil { return nil, errors.Trace(err) } return &ControllerAPIv6{v7}, nil }
[ "func", "NewControllerAPIv6", "(", "ctx", "facade", ".", "Context", ")", "(", "*", "ControllerAPIv6", ",", "error", ")", "{", "v7", ",", "err", ":=", "NewControllerAPIv7", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "&", "ControllerAPIv6", "{", "v7", "}", ",", "nil", "\n", "}" ]
// NewControllerAPIv6 creates a new ControllerAPIv6.
[ "NewControllerAPIv6", "creates", "a", "new", "ControllerAPIv6", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/controller/controller.go#L97-L103
3,961
juju/juju
apiserver/facades/client/controller/controller.go
NewControllerAPIv5
func NewControllerAPIv5(ctx facade.Context) (*ControllerAPIv5, error) { v6, err := NewControllerAPIv6(ctx) if err != nil { return nil, errors.Trace(err) } return &ControllerAPIv5{v6}, nil }
go
func NewControllerAPIv5(ctx facade.Context) (*ControllerAPIv5, error) { v6, err := NewControllerAPIv6(ctx) if err != nil { return nil, errors.Trace(err) } return &ControllerAPIv5{v6}, nil }
[ "func", "NewControllerAPIv5", "(", "ctx", "facade", ".", "Context", ")", "(", "*", "ControllerAPIv5", ",", "error", ")", "{", "v6", ",", "err", ":=", "NewControllerAPIv6", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "&", "ControllerAPIv5", "{", "v6", "}", ",", "nil", "\n", "}" ]
// NewControllerAPIv5 creates a new ControllerAPIv5.
[ "NewControllerAPIv5", "creates", "a", "new", "ControllerAPIv5", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/controller/controller.go#L106-L112
3,962
juju/juju
apiserver/facades/client/controller/controller.go
NewControllerAPIv4
func NewControllerAPIv4(ctx facade.Context) (*ControllerAPIv4, error) { v5, err := NewControllerAPIv5(ctx) if err != nil { return nil, errors.Trace(err) } return &ControllerAPIv4{v5}, nil }
go
func NewControllerAPIv4(ctx facade.Context) (*ControllerAPIv4, error) { v5, err := NewControllerAPIv5(ctx) if err != nil { return nil, errors.Trace(err) } return &ControllerAPIv4{v5}, nil }
[ "func", "NewControllerAPIv4", "(", "ctx", "facade", ".", "Context", ")", "(", "*", "ControllerAPIv4", ",", "error", ")", "{", "v5", ",", "err", ":=", "NewControllerAPIv5", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "&", "ControllerAPIv4", "{", "v5", "}", ",", "nil", "\n", "}" ]
// NewControllerAPIv4 creates a new ControllerAPIv4.
[ "NewControllerAPIv4", "creates", "a", "new", "ControllerAPIv4", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/controller/controller.go#L115-L121
3,963
juju/juju
apiserver/facades/client/controller/controller.go
NewControllerAPIv3
func NewControllerAPIv3(ctx facade.Context) (*ControllerAPIv3, error) { v4, err := NewControllerAPIv4(ctx) if err != nil { return nil, errors.Trace(err) } return &ControllerAPIv3{v4}, nil }
go
func NewControllerAPIv3(ctx facade.Context) (*ControllerAPIv3, error) { v4, err := NewControllerAPIv4(ctx) if err != nil { return nil, errors.Trace(err) } return &ControllerAPIv3{v4}, nil }
[ "func", "NewControllerAPIv3", "(", "ctx", "facade", ".", "Context", ")", "(", "*", "ControllerAPIv3", ",", "error", ")", "{", "v4", ",", "err", ":=", "NewControllerAPIv4", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "&", "ControllerAPIv3", "{", "v4", "}", ",", "nil", "\n", "}" ]
// NewControllerAPIv3 creates a new ControllerAPIv3.
[ "NewControllerAPIv3", "creates", "a", "new", "ControllerAPIv3", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/controller/controller.go#L124-L130
3,964
juju/juju
apiserver/facades/client/controller/controller.go
NewControllerAPI
func NewControllerAPI( st *state.State, pool *state.StatePool, authorizer facade.Authorizer, resources facade.Resources, presence facade.Presence, hub facade.Hub, ) (*ControllerAPI, error) { if !authorizer.AuthClient() { return nil, errors.Trace(common.ErrPerm) } // Since we know this is a user tag (because AuthClient is true), // we just do the type assertion to the UserTag. apiUser, _ := authorizer.GetAuthTag().(names.UserTag) model, err := st.Model() if err != nil { return nil, errors.Trace(err) } return &ControllerAPI{ ControllerConfigAPI: common.NewStateControllerConfig(st), ModelStatusAPI: common.NewModelStatusAPI( common.NewModelManagerBackend(model, pool), authorizer, apiUser, ), CloudSpecAPI: cloudspec.NewCloudSpec( resources, cloudspec.MakeCloudSpecGetter(pool), cloudspec.MakeCloudSpecWatcherForModel(st), common.AuthFuncForTag(model.ModelTag()), ), state: st, statePool: pool, authorizer: authorizer, apiUser: apiUser, resources: resources, presence: presence, hub: hub, }, nil }
go
func NewControllerAPI( st *state.State, pool *state.StatePool, authorizer facade.Authorizer, resources facade.Resources, presence facade.Presence, hub facade.Hub, ) (*ControllerAPI, error) { if !authorizer.AuthClient() { return nil, errors.Trace(common.ErrPerm) } // Since we know this is a user tag (because AuthClient is true), // we just do the type assertion to the UserTag. apiUser, _ := authorizer.GetAuthTag().(names.UserTag) model, err := st.Model() if err != nil { return nil, errors.Trace(err) } return &ControllerAPI{ ControllerConfigAPI: common.NewStateControllerConfig(st), ModelStatusAPI: common.NewModelStatusAPI( common.NewModelManagerBackend(model, pool), authorizer, apiUser, ), CloudSpecAPI: cloudspec.NewCloudSpec( resources, cloudspec.MakeCloudSpecGetter(pool), cloudspec.MakeCloudSpecWatcherForModel(st), common.AuthFuncForTag(model.ModelTag()), ), state: st, statePool: pool, authorizer: authorizer, apiUser: apiUser, resources: resources, presence: presence, hub: hub, }, nil }
[ "func", "NewControllerAPI", "(", "st", "*", "state", ".", "State", ",", "pool", "*", "state", ".", "StatePool", ",", "authorizer", "facade", ".", "Authorizer", ",", "resources", "facade", ".", "Resources", ",", "presence", "facade", ".", "Presence", ",", "hub", "facade", ".", "Hub", ",", ")", "(", "*", "ControllerAPI", ",", "error", ")", "{", "if", "!", "authorizer", ".", "AuthClient", "(", ")", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "common", ".", "ErrPerm", ")", "\n", "}", "\n\n", "// Since we know this is a user tag (because AuthClient is true),", "// we just do the type assertion to the UserTag.", "apiUser", ",", "_", ":=", "authorizer", ".", "GetAuthTag", "(", ")", ".", "(", "names", ".", "UserTag", ")", "\n\n", "model", ",", "err", ":=", "st", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "&", "ControllerAPI", "{", "ControllerConfigAPI", ":", "common", ".", "NewStateControllerConfig", "(", "st", ")", ",", "ModelStatusAPI", ":", "common", ".", "NewModelStatusAPI", "(", "common", ".", "NewModelManagerBackend", "(", "model", ",", "pool", ")", ",", "authorizer", ",", "apiUser", ",", ")", ",", "CloudSpecAPI", ":", "cloudspec", ".", "NewCloudSpec", "(", "resources", ",", "cloudspec", ".", "MakeCloudSpecGetter", "(", "pool", ")", ",", "cloudspec", ".", "MakeCloudSpecWatcherForModel", "(", "st", ")", ",", "common", ".", "AuthFuncForTag", "(", "model", ".", "ModelTag", "(", ")", ")", ",", ")", ",", "state", ":", "st", ",", "statePool", ":", "pool", ",", "authorizer", ":", "authorizer", ",", "apiUser", ":", "apiUser", ",", "resources", ":", "resources", ",", "presence", ":", "presence", ",", "hub", ":", "hub", ",", "}", ",", "nil", "\n", "}" ]
// NewControllerAPI creates a new api server endpoint for operations // on a controller.
[ "NewControllerAPI", "creates", "a", "new", "api", "server", "endpoint", "for", "operations", "on", "a", "controller", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/controller/controller.go#L134-L175
3,965
juju/juju
apiserver/facades/client/controller/controller.go
MongoVersion
func (c *ControllerAPI) MongoVersion() (params.StringResult, error) { result := params.StringResult{} if err := c.checkHasAdmin(); err != nil { return result, errors.Trace(err) } version, err := c.state.MongoVersion() if err != nil { return result, errors.Trace(err) } result.Result = version return result, nil }
go
func (c *ControllerAPI) MongoVersion() (params.StringResult, error) { result := params.StringResult{} if err := c.checkHasAdmin(); err != nil { return result, errors.Trace(err) } version, err := c.state.MongoVersion() if err != nil { return result, errors.Trace(err) } result.Result = version return result, nil }
[ "func", "(", "c", "*", "ControllerAPI", ")", "MongoVersion", "(", ")", "(", "params", ".", "StringResult", ",", "error", ")", "{", "result", ":=", "params", ".", "StringResult", "{", "}", "\n", "if", "err", ":=", "c", ".", "checkHasAdmin", "(", ")", ";", "err", "!=", "nil", "{", "return", "result", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "version", ",", "err", ":=", "c", ".", "state", ".", "MongoVersion", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "result", ".", "Result", "=", "version", "\n", "return", "result", ",", "nil", "\n", "}" ]
// MongoVersion allows the introspection of the mongo version per controller
[ "MongoVersion", "allows", "the", "introspection", "of", "the", "mongo", "version", "per", "controller" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/controller/controller.go#L232-L243
3,966
juju/juju
apiserver/facades/client/controller/controller.go
ListBlockedModels
func (c *ControllerAPI) ListBlockedModels() (params.ModelBlockInfoList, error) { results := params.ModelBlockInfoList{} if err := c.checkHasAdmin(); err != nil { return results, errors.Trace(err) } blocks, err := c.state.AllBlocksForController() if err != nil { return results, errors.Trace(err) } modelBlocks := make(map[string][]string) for _, block := range blocks { uuid := block.ModelUUID() types, ok := modelBlocks[uuid] if !ok { types = []string{block.Type().String()} } else { types = append(types, block.Type().String()) } modelBlocks[uuid] = types } for uuid, blocks := range modelBlocks { model, ph, err := c.statePool.GetModel(uuid) if err != nil { logger.Debugf("unable to retrieve model %s: %v", uuid, err) continue } results.Models = append(results.Models, params.ModelBlockInfo{ UUID: model.UUID(), Name: model.Name(), OwnerTag: model.Owner().String(), Blocks: blocks, }) ph.Release() } // Sort the resulting sequence by model name, then owner. sort.Sort(orderedBlockInfo(results.Models)) return results, nil }
go
func (c *ControllerAPI) ListBlockedModels() (params.ModelBlockInfoList, error) { results := params.ModelBlockInfoList{} if err := c.checkHasAdmin(); err != nil { return results, errors.Trace(err) } blocks, err := c.state.AllBlocksForController() if err != nil { return results, errors.Trace(err) } modelBlocks := make(map[string][]string) for _, block := range blocks { uuid := block.ModelUUID() types, ok := modelBlocks[uuid] if !ok { types = []string{block.Type().String()} } else { types = append(types, block.Type().String()) } modelBlocks[uuid] = types } for uuid, blocks := range modelBlocks { model, ph, err := c.statePool.GetModel(uuid) if err != nil { logger.Debugf("unable to retrieve model %s: %v", uuid, err) continue } results.Models = append(results.Models, params.ModelBlockInfo{ UUID: model.UUID(), Name: model.Name(), OwnerTag: model.Owner().String(), Blocks: blocks, }) ph.Release() } // Sort the resulting sequence by model name, then owner. sort.Sort(orderedBlockInfo(results.Models)) return results, nil }
[ "func", "(", "c", "*", "ControllerAPI", ")", "ListBlockedModels", "(", ")", "(", "params", ".", "ModelBlockInfoList", ",", "error", ")", "{", "results", ":=", "params", ".", "ModelBlockInfoList", "{", "}", "\n", "if", "err", ":=", "c", ".", "checkHasAdmin", "(", ")", ";", "err", "!=", "nil", "{", "return", "results", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "blocks", ",", "err", ":=", "c", ".", "state", ".", "AllBlocksForController", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "results", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "modelBlocks", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "string", ")", "\n", "for", "_", ",", "block", ":=", "range", "blocks", "{", "uuid", ":=", "block", ".", "ModelUUID", "(", ")", "\n", "types", ",", "ok", ":=", "modelBlocks", "[", "uuid", "]", "\n", "if", "!", "ok", "{", "types", "=", "[", "]", "string", "{", "block", ".", "Type", "(", ")", ".", "String", "(", ")", "}", "\n", "}", "else", "{", "types", "=", "append", "(", "types", ",", "block", ".", "Type", "(", ")", ".", "String", "(", ")", ")", "\n", "}", "\n", "modelBlocks", "[", "uuid", "]", "=", "types", "\n", "}", "\n\n", "for", "uuid", ",", "blocks", ":=", "range", "modelBlocks", "{", "model", ",", "ph", ",", "err", ":=", "c", ".", "statePool", ".", "GetModel", "(", "uuid", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Debugf", "(", "\"", "\"", ",", "uuid", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "results", ".", "Models", "=", "append", "(", "results", ".", "Models", ",", "params", ".", "ModelBlockInfo", "{", "UUID", ":", "model", ".", "UUID", "(", ")", ",", "Name", ":", "model", ".", "Name", "(", ")", ",", "OwnerTag", ":", "model", ".", "Owner", "(", ")", ".", "String", "(", ")", ",", "Blocks", ":", "blocks", ",", "}", ")", "\n", "ph", ".", "Release", "(", ")", "\n", "}", "\n\n", "// Sort the resulting sequence by model name, then owner.", "sort", ".", "Sort", "(", "orderedBlockInfo", "(", "results", ".", "Models", ")", ")", "\n", "return", "results", ",", "nil", "\n", "}" ]
// ListBlockedModels returns a list of all models on the controller // which have a block in place. The resulting slice is sorted by model // name, then owner. Callers must be controller administrators to retrieve the // list.
[ "ListBlockedModels", "returns", "a", "list", "of", "all", "models", "on", "the", "controller", "which", "have", "a", "block", "in", "place", ".", "The", "resulting", "slice", "is", "sorted", "by", "model", "name", "then", "owner", ".", "Callers", "must", "be", "controller", "administrators", "to", "retrieve", "the", "list", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/controller/controller.go#L301-L341
3,967
juju/juju
apiserver/facades/client/controller/controller.go
ModelConfig
func (c *ControllerAPI) ModelConfig() (params.ModelConfigResults, error) { result := params.ModelConfigResults{} if err := c.checkHasAdmin(); err != nil { return result, errors.Trace(err) } controllerState := c.statePool.SystemState() controllerModel, err := controllerState.Model() if err != nil { return result, errors.Trace(err) } cfg, err := controllerModel.Config() if err != nil { return result, errors.Trace(err) } result.Config = make(map[string]params.ConfigValue) for name, val := range cfg.AllAttrs() { result.Config[name] = params.ConfigValue{ Value: val, } } return result, nil }
go
func (c *ControllerAPI) ModelConfig() (params.ModelConfigResults, error) { result := params.ModelConfigResults{} if err := c.checkHasAdmin(); err != nil { return result, errors.Trace(err) } controllerState := c.statePool.SystemState() controllerModel, err := controllerState.Model() if err != nil { return result, errors.Trace(err) } cfg, err := controllerModel.Config() if err != nil { return result, errors.Trace(err) } result.Config = make(map[string]params.ConfigValue) for name, val := range cfg.AllAttrs() { result.Config[name] = params.ConfigValue{ Value: val, } } return result, nil }
[ "func", "(", "c", "*", "ControllerAPI", ")", "ModelConfig", "(", ")", "(", "params", ".", "ModelConfigResults", ",", "error", ")", "{", "result", ":=", "params", ".", "ModelConfigResults", "{", "}", "\n", "if", "err", ":=", "c", ".", "checkHasAdmin", "(", ")", ";", "err", "!=", "nil", "{", "return", "result", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "controllerState", ":=", "c", ".", "statePool", ".", "SystemState", "(", ")", "\n", "controllerModel", ",", "err", ":=", "controllerState", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "cfg", ",", "err", ":=", "controllerModel", ".", "Config", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "result", ".", "Config", "=", "make", "(", "map", "[", "string", "]", "params", ".", "ConfigValue", ")", "\n", "for", "name", ",", "val", ":=", "range", "cfg", ".", "AllAttrs", "(", ")", "{", "result", ".", "Config", "[", "name", "]", "=", "params", ".", "ConfigValue", "{", "Value", ":", "val", ",", "}", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// ModelConfig returns the model config for the controller // model. For information on the current model, use // client.ModelGet
[ "ModelConfig", "returns", "the", "model", "config", "for", "the", "controller", "model", ".", "For", "information", "on", "the", "current", "model", "use", "client", ".", "ModelGet" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/controller/controller.go#L346-L369
3,968
juju/juju
apiserver/facades/client/controller/controller.go
HostedModelConfigs
func (c *ControllerAPI) HostedModelConfigs() (params.HostedModelConfigsResults, error) { result := params.HostedModelConfigsResults{} if err := c.checkHasAdmin(); err != nil { return result, errors.Trace(err) } modelUUIDs, err := c.state.AllModelUUIDs() if err != nil { return result, errors.Trace(err) } for _, modelUUID := range modelUUIDs { if modelUUID == c.state.ControllerModelUUID() { continue } st, err := c.statePool.Get(modelUUID) if err != nil { // This model could have been removed. if errors.IsNotFound(err) { continue } return result, errors.Trace(err) } defer st.Release() model, err := st.Model() if err != nil { return result, errors.Trace(err) } config := params.HostedModelConfig{ Name: model.Name(), OwnerTag: model.Owner().String(), } modelConf, err := model.Config() if err != nil { config.Error = common.ServerError(err) } else { config.Config = modelConf.AllAttrs() } cloudSpec := c.GetCloudSpec(model.ModelTag()) if config.Error == nil { config.CloudSpec = cloudSpec.Result config.Error = cloudSpec.Error } result.Models = append(result.Models, config) } return result, nil }
go
func (c *ControllerAPI) HostedModelConfigs() (params.HostedModelConfigsResults, error) { result := params.HostedModelConfigsResults{} if err := c.checkHasAdmin(); err != nil { return result, errors.Trace(err) } modelUUIDs, err := c.state.AllModelUUIDs() if err != nil { return result, errors.Trace(err) } for _, modelUUID := range modelUUIDs { if modelUUID == c.state.ControllerModelUUID() { continue } st, err := c.statePool.Get(modelUUID) if err != nil { // This model could have been removed. if errors.IsNotFound(err) { continue } return result, errors.Trace(err) } defer st.Release() model, err := st.Model() if err != nil { return result, errors.Trace(err) } config := params.HostedModelConfig{ Name: model.Name(), OwnerTag: model.Owner().String(), } modelConf, err := model.Config() if err != nil { config.Error = common.ServerError(err) } else { config.Config = modelConf.AllAttrs() } cloudSpec := c.GetCloudSpec(model.ModelTag()) if config.Error == nil { config.CloudSpec = cloudSpec.Result config.Error = cloudSpec.Error } result.Models = append(result.Models, config) } return result, nil }
[ "func", "(", "c", "*", "ControllerAPI", ")", "HostedModelConfigs", "(", ")", "(", "params", ".", "HostedModelConfigsResults", ",", "error", ")", "{", "result", ":=", "params", ".", "HostedModelConfigsResults", "{", "}", "\n", "if", "err", ":=", "c", ".", "checkHasAdmin", "(", ")", ";", "err", "!=", "nil", "{", "return", "result", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "modelUUIDs", ",", "err", ":=", "c", ".", "state", ".", "AllModelUUIDs", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "for", "_", ",", "modelUUID", ":=", "range", "modelUUIDs", "{", "if", "modelUUID", "==", "c", ".", "state", ".", "ControllerModelUUID", "(", ")", "{", "continue", "\n", "}", "\n", "st", ",", "err", ":=", "c", ".", "statePool", ".", "Get", "(", "modelUUID", ")", "\n", "if", "err", "!=", "nil", "{", "// This model could have been removed.", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "continue", "\n", "}", "\n", "return", "result", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "defer", "st", ".", "Release", "(", ")", "\n", "model", ",", "err", ":=", "st", ".", "Model", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "config", ":=", "params", ".", "HostedModelConfig", "{", "Name", ":", "model", ".", "Name", "(", ")", ",", "OwnerTag", ":", "model", ".", "Owner", "(", ")", ".", "String", "(", ")", ",", "}", "\n", "modelConf", ",", "err", ":=", "model", ".", "Config", "(", ")", "\n", "if", "err", "!=", "nil", "{", "config", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "else", "{", "config", ".", "Config", "=", "modelConf", ".", "AllAttrs", "(", ")", "\n", "}", "\n", "cloudSpec", ":=", "c", ".", "GetCloudSpec", "(", "model", ".", "ModelTag", "(", ")", ")", "\n", "if", "config", ".", "Error", "==", "nil", "{", "config", ".", "CloudSpec", "=", "cloudSpec", ".", "Result", "\n", "config", ".", "Error", "=", "cloudSpec", ".", "Error", "\n", "}", "\n", "result", ".", "Models", "=", "append", "(", "result", ".", "Models", ",", "config", ")", "\n", "}", "\n\n", "return", "result", ",", "nil", "\n", "}" ]
// HostedModelConfigs returns all the information that the client needs in // order to connect directly with the host model's provider and destroy it // directly.
[ "HostedModelConfigs", "returns", "all", "the", "information", "that", "the", "client", "needs", "in", "order", "to", "connect", "directly", "with", "the", "host", "model", "s", "provider", "and", "destroy", "it", "directly", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/controller/controller.go#L374-L422
3,969
juju/juju
apiserver/facades/client/controller/controller.go
WatchAllModels
func (c *ControllerAPI) WatchAllModels() (params.AllWatcherId, error) { if err := c.checkHasAdmin(); err != nil { return params.AllWatcherId{}, errors.Trace(err) } w := c.state.WatchAllModels(c.statePool) return params.AllWatcherId{ AllWatcherId: c.resources.Register(w), }, nil }
go
func (c *ControllerAPI) WatchAllModels() (params.AllWatcherId, error) { if err := c.checkHasAdmin(); err != nil { return params.AllWatcherId{}, errors.Trace(err) } w := c.state.WatchAllModels(c.statePool) return params.AllWatcherId{ AllWatcherId: c.resources.Register(w), }, nil }
[ "func", "(", "c", "*", "ControllerAPI", ")", "WatchAllModels", "(", ")", "(", "params", ".", "AllWatcherId", ",", "error", ")", "{", "if", "err", ":=", "c", ".", "checkHasAdmin", "(", ")", ";", "err", "!=", "nil", "{", "return", "params", ".", "AllWatcherId", "{", "}", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "w", ":=", "c", ".", "state", ".", "WatchAllModels", "(", "c", ".", "statePool", ")", "\n", "return", "params", ".", "AllWatcherId", "{", "AllWatcherId", ":", "c", ".", "resources", ".", "Register", "(", "w", ")", ",", "}", ",", "nil", "\n", "}" ]
// WatchAllModels starts watching events for all models in the // controller. The returned AllWatcherId should be used with Next on the // AllModelWatcher endpoint to receive deltas.
[ "WatchAllModels", "starts", "watching", "events", "for", "all", "models", "in", "the", "controller", ".", "The", "returned", "AllWatcherId", "should", "be", "used", "with", "Next", "on", "the", "AllModelWatcher", "endpoint", "to", "receive", "deltas", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/controller/controller.go#L439-L447
3,970
juju/juju
apiserver/facades/client/controller/controller.go
GetControllerAccess
func (c *ControllerAPI) GetControllerAccess(req params.Entities) (params.UserAccessResults, error) { results := params.UserAccessResults{} isAdmin, err := c.authorizer.HasPermission(permission.SuperuserAccess, c.state.ControllerTag()) if err != nil { return results, errors.Trace(err) } users := req.Entities results.Results = make([]params.UserAccessResult, len(users)) for i, user := range users { userTag, err := names.ParseUserTag(user.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } if !isAdmin && !c.authorizer.AuthOwner(userTag) { results.Results[i].Error = common.ServerError(common.ErrPerm) continue } access, err := c.state.UserPermission(userTag, c.state.ControllerTag()) if err != nil { results.Results[i].Error = common.ServerError(err) continue } results.Results[i].Result = &params.UserAccess{ Access: string(access), UserTag: userTag.String()} } return results, nil }
go
func (c *ControllerAPI) GetControllerAccess(req params.Entities) (params.UserAccessResults, error) { results := params.UserAccessResults{} isAdmin, err := c.authorizer.HasPermission(permission.SuperuserAccess, c.state.ControllerTag()) if err != nil { return results, errors.Trace(err) } users := req.Entities results.Results = make([]params.UserAccessResult, len(users)) for i, user := range users { userTag, err := names.ParseUserTag(user.Tag) if err != nil { results.Results[i].Error = common.ServerError(err) continue } if !isAdmin && !c.authorizer.AuthOwner(userTag) { results.Results[i].Error = common.ServerError(common.ErrPerm) continue } access, err := c.state.UserPermission(userTag, c.state.ControllerTag()) if err != nil { results.Results[i].Error = common.ServerError(err) continue } results.Results[i].Result = &params.UserAccess{ Access: string(access), UserTag: userTag.String()} } return results, nil }
[ "func", "(", "c", "*", "ControllerAPI", ")", "GetControllerAccess", "(", "req", "params", ".", "Entities", ")", "(", "params", ".", "UserAccessResults", ",", "error", ")", "{", "results", ":=", "params", ".", "UserAccessResults", "{", "}", "\n", "isAdmin", ",", "err", ":=", "c", ".", "authorizer", ".", "HasPermission", "(", "permission", ".", "SuperuserAccess", ",", "c", ".", "state", ".", "ControllerTag", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "results", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "users", ":=", "req", ".", "Entities", "\n", "results", ".", "Results", "=", "make", "(", "[", "]", "params", ".", "UserAccessResult", ",", "len", "(", "users", ")", ")", "\n", "for", "i", ",", "user", ":=", "range", "users", "{", "userTag", ",", "err", ":=", "names", ".", "ParseUserTag", "(", "user", ".", "Tag", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "!", "isAdmin", "&&", "!", "c", ".", "authorizer", ".", "AuthOwner", "(", "userTag", ")", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "common", ".", "ErrPerm", ")", "\n", "continue", "\n", "}", "\n", "access", ",", "err", ":=", "c", ".", "state", ".", "UserPermission", "(", "userTag", ",", "c", ".", "state", ".", "ControllerTag", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "results", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "results", ".", "Results", "[", "i", "]", ".", "Result", "=", "&", "params", ".", "UserAccess", "{", "Access", ":", "string", "(", "access", ")", ",", "UserTag", ":", "userTag", ".", "String", "(", ")", "}", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// GetControllerAccess returns the level of access the specified users // have on the controller.
[ "GetControllerAccess", "returns", "the", "level", "of", "access", "the", "specified", "users", "have", "on", "the", "controller", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/controller/controller.go#L451-L480
3,971
juju/juju
apiserver/facades/client/controller/controller.go
InitiateMigration
func (c *ControllerAPI) InitiateMigration(reqArgs params.InitiateMigrationArgs) ( params.InitiateMigrationResults, error, ) { out := params.InitiateMigrationResults{ Results: make([]params.InitiateMigrationResult, len(reqArgs.Specs)), } if err := c.checkHasAdmin(); err != nil { return out, errors.Trace(err) } for i, spec := range reqArgs.Specs { result := &out.Results[i] result.ModelTag = spec.ModelTag id, err := c.initiateOneMigration(spec) if err != nil { result.Error = common.ServerError(err) } else { result.MigrationId = id } } return out, nil }
go
func (c *ControllerAPI) InitiateMigration(reqArgs params.InitiateMigrationArgs) ( params.InitiateMigrationResults, error, ) { out := params.InitiateMigrationResults{ Results: make([]params.InitiateMigrationResult, len(reqArgs.Specs)), } if err := c.checkHasAdmin(); err != nil { return out, errors.Trace(err) } for i, spec := range reqArgs.Specs { result := &out.Results[i] result.ModelTag = spec.ModelTag id, err := c.initiateOneMigration(spec) if err != nil { result.Error = common.ServerError(err) } else { result.MigrationId = id } } return out, nil }
[ "func", "(", "c", "*", "ControllerAPI", ")", "InitiateMigration", "(", "reqArgs", "params", ".", "InitiateMigrationArgs", ")", "(", "params", ".", "InitiateMigrationResults", ",", "error", ",", ")", "{", "out", ":=", "params", ".", "InitiateMigrationResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "InitiateMigrationResult", ",", "len", "(", "reqArgs", ".", "Specs", ")", ")", ",", "}", "\n", "if", "err", ":=", "c", ".", "checkHasAdmin", "(", ")", ";", "err", "!=", "nil", "{", "return", "out", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "for", "i", ",", "spec", ":=", "range", "reqArgs", ".", "Specs", "{", "result", ":=", "&", "out", ".", "Results", "[", "i", "]", "\n", "result", ".", "ModelTag", "=", "spec", ".", "ModelTag", "\n", "id", ",", "err", ":=", "c", ".", "initiateOneMigration", "(", "spec", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "}", "else", "{", "result", ".", "MigrationId", "=", "id", "\n", "}", "\n", "}", "\n", "return", "out", ",", "nil", "\n", "}" ]
// InitiateMigration attempts to begin the migration of one or // more models to other controllers.
[ "InitiateMigration", "attempts", "to", "begin", "the", "migration", "of", "one", "or", "more", "models", "to", "other", "controllers", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/controller/controller.go#L484-L505
3,972
juju/juju
apiserver/facades/client/controller/controller.go
ModifyControllerAccess
func (c *ControllerAPI) ModifyControllerAccess(args params.ModifyControllerAccessRequest) (params.ErrorResults, error) { result := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Changes)), } if len(args.Changes) == 0 { return result, nil } hasPermission, err := c.authorizer.HasPermission(permission.SuperuserAccess, c.state.ControllerTag()) if err != nil { return result, errors.Trace(err) } for i, arg := range args.Changes { if !hasPermission { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } controllerAccess := permission.Access(arg.Access) if err := permission.ValidateControllerAccess(controllerAccess); err != nil { // TODO(wallyworld) - remove in Juju 3.0 // Backwards compatibility requires us to accept add-model. if controllerAccess != permission.AddModelAccess { result.Results[i].Error = common.ServerError(err) continue } } targetUserTag, err := names.ParseUserTag(arg.UserTag) if err != nil { result.Results[i].Error = common.ServerError(errors.Annotate(err, "could not modify controller access")) continue } result.Results[i].Error = common.ServerError( ChangeControllerAccess(c.state, c.apiUser, targetUserTag, arg.Action, controllerAccess)) } return result, nil }
go
func (c *ControllerAPI) ModifyControllerAccess(args params.ModifyControllerAccessRequest) (params.ErrorResults, error) { result := params.ErrorResults{ Results: make([]params.ErrorResult, len(args.Changes)), } if len(args.Changes) == 0 { return result, nil } hasPermission, err := c.authorizer.HasPermission(permission.SuperuserAccess, c.state.ControllerTag()) if err != nil { return result, errors.Trace(err) } for i, arg := range args.Changes { if !hasPermission { result.Results[i].Error = common.ServerError(common.ErrPerm) continue } controllerAccess := permission.Access(arg.Access) if err := permission.ValidateControllerAccess(controllerAccess); err != nil { // TODO(wallyworld) - remove in Juju 3.0 // Backwards compatibility requires us to accept add-model. if controllerAccess != permission.AddModelAccess { result.Results[i].Error = common.ServerError(err) continue } } targetUserTag, err := names.ParseUserTag(arg.UserTag) if err != nil { result.Results[i].Error = common.ServerError(errors.Annotate(err, "could not modify controller access")) continue } result.Results[i].Error = common.ServerError( ChangeControllerAccess(c.state, c.apiUser, targetUserTag, arg.Action, controllerAccess)) } return result, nil }
[ "func", "(", "c", "*", "ControllerAPI", ")", "ModifyControllerAccess", "(", "args", "params", ".", "ModifyControllerAccessRequest", ")", "(", "params", ".", "ErrorResults", ",", "error", ")", "{", "result", ":=", "params", ".", "ErrorResults", "{", "Results", ":", "make", "(", "[", "]", "params", ".", "ErrorResult", ",", "len", "(", "args", ".", "Changes", ")", ")", ",", "}", "\n", "if", "len", "(", "args", ".", "Changes", ")", "==", "0", "{", "return", "result", ",", "nil", "\n", "}", "\n\n", "hasPermission", ",", "err", ":=", "c", ".", "authorizer", ".", "HasPermission", "(", "permission", ".", "SuperuserAccess", ",", "c", ".", "state", ".", "ControllerTag", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "result", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "for", "i", ",", "arg", ":=", "range", "args", ".", "Changes", "{", "if", "!", "hasPermission", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "common", ".", "ErrPerm", ")", "\n", "continue", "\n", "}", "\n\n", "controllerAccess", ":=", "permission", ".", "Access", "(", "arg", ".", "Access", ")", "\n", "if", "err", ":=", "permission", ".", "ValidateControllerAccess", "(", "controllerAccess", ")", ";", "err", "!=", "nil", "{", "// TODO(wallyworld) - remove in Juju 3.0", "// Backwards compatibility requires us to accept add-model.", "if", "controllerAccess", "!=", "permission", ".", "AddModelAccess", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "}", "\n\n", "targetUserTag", ",", "err", ":=", "names", ".", "ParseUserTag", "(", "arg", ".", "UserTag", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ")", "\n", "continue", "\n", "}", "\n\n", "result", ".", "Results", "[", "i", "]", ".", "Error", "=", "common", ".", "ServerError", "(", "ChangeControllerAccess", "(", "c", ".", "state", ",", "c", ".", "apiUser", ",", "targetUserTag", ",", "arg", ".", "Action", ",", "controllerAccess", ")", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// ModifyControllerAccess changes the model access granted to users.
[ "ModifyControllerAccess", "changes", "the", "model", "access", "granted", "to", "users", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/controller/controller.go#L569-L608
3,973
juju/juju
apiserver/facades/client/controller/controller.go
ConfigSet
func (c *ControllerAPI) ConfigSet(args params.ControllerConfigSet) error { if err := c.checkHasAdmin(); err != nil { return errors.Trace(err) } if err := c.state.UpdateControllerConfig(args.Config, nil); err != nil { return errors.Trace(err) } // TODO(thumper): add a version to controller config to allow for // simultaneous updates and races in publishing, potentially across // HA servers. cfg, err := c.state.ControllerConfig() if err != nil { return errors.Trace(err) } if _, err := c.hub.Publish( controller.ConfigChanged, controller.ConfigChangedMessage{cfg}); err != nil { return errors.Trace(err) } return nil }
go
func (c *ControllerAPI) ConfigSet(args params.ControllerConfigSet) error { if err := c.checkHasAdmin(); err != nil { return errors.Trace(err) } if err := c.state.UpdateControllerConfig(args.Config, nil); err != nil { return errors.Trace(err) } // TODO(thumper): add a version to controller config to allow for // simultaneous updates and races in publishing, potentially across // HA servers. cfg, err := c.state.ControllerConfig() if err != nil { return errors.Trace(err) } if _, err := c.hub.Publish( controller.ConfigChanged, controller.ConfigChangedMessage{cfg}); err != nil { return errors.Trace(err) } return nil }
[ "func", "(", "c", "*", "ControllerAPI", ")", "ConfigSet", "(", "args", "params", ".", "ControllerConfigSet", ")", "error", "{", "if", "err", ":=", "c", ".", "checkHasAdmin", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "c", ".", "state", ".", "UpdateControllerConfig", "(", "args", ".", "Config", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "// TODO(thumper): add a version to controller config to allow for", "// simultaneous updates and races in publishing, potentially across", "// HA servers.", "cfg", ",", "err", ":=", "c", ".", "state", ".", "ControllerConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "c", ".", "hub", ".", "Publish", "(", "controller", ".", "ConfigChanged", ",", "controller", ".", "ConfigChangedMessage", "{", "cfg", "}", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ConfigSet changes the value of specified controller configuration // settings. Only some settings can be changed after bootstrap. // Settings that aren't specified in the params are left unchanged.
[ "ConfigSet", "changes", "the", "value", "of", "specified", "controller", "configuration", "settings", ".", "Only", "some", "settings", "can", "be", "changed", "after", "bootstrap", ".", "Settings", "that", "aren", "t", "specified", "in", "the", "params", "are", "left", "unchanged", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/controller/controller.go#L613-L633
3,974
juju/juju
apiserver/facades/client/controller/controller.go
grantControllerCloudAccess
func grantControllerCloudAccess(accessor *state.State, targetUserTag names.UserTag, access permission.Access) error { controllerInfo, err := accessor.ControllerInfo() if err != nil { return errors.Trace(err) } cloud := controllerInfo.CloudName err = accessor.CreateCloudAccess(cloud, targetUserTag, access) if errors.IsAlreadyExists(err) { cloudAccess, err := accessor.GetCloudAccess(cloud, targetUserTag) if errors.IsNotFound(err) { // Conflicts with prior check, must be inconsistent state. err = txn.ErrExcessiveContention } if err != nil { return errors.Annotate(err, "could not look up cloud access for user") } // Only set access if greater access is being granted. if cloudAccess.EqualOrGreaterCloudAccessThan(access) { return errors.Errorf("user already has %q access or greater", access) } if _, err = accessor.SetUserAccess(targetUserTag, names.NewCloudTag(cloud), access); err != nil { return errors.Annotate(err, "could not set cloud access for user") } return nil } if err != nil { return errors.Trace(err) } return nil }
go
func grantControllerCloudAccess(accessor *state.State, targetUserTag names.UserTag, access permission.Access) error { controllerInfo, err := accessor.ControllerInfo() if err != nil { return errors.Trace(err) } cloud := controllerInfo.CloudName err = accessor.CreateCloudAccess(cloud, targetUserTag, access) if errors.IsAlreadyExists(err) { cloudAccess, err := accessor.GetCloudAccess(cloud, targetUserTag) if errors.IsNotFound(err) { // Conflicts with prior check, must be inconsistent state. err = txn.ErrExcessiveContention } if err != nil { return errors.Annotate(err, "could not look up cloud access for user") } // Only set access if greater access is being granted. if cloudAccess.EqualOrGreaterCloudAccessThan(access) { return errors.Errorf("user already has %q access or greater", access) } if _, err = accessor.SetUserAccess(targetUserTag, names.NewCloudTag(cloud), access); err != nil { return errors.Annotate(err, "could not set cloud access for user") } return nil } if err != nil { return errors.Trace(err) } return nil }
[ "func", "grantControllerCloudAccess", "(", "accessor", "*", "state", ".", "State", ",", "targetUserTag", "names", ".", "UserTag", ",", "access", "permission", ".", "Access", ")", "error", "{", "controllerInfo", ",", "err", ":=", "accessor", ".", "ControllerInfo", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "cloud", ":=", "controllerInfo", ".", "CloudName", "\n", "err", "=", "accessor", ".", "CreateCloudAccess", "(", "cloud", ",", "targetUserTag", ",", "access", ")", "\n", "if", "errors", ".", "IsAlreadyExists", "(", "err", ")", "{", "cloudAccess", ",", "err", ":=", "accessor", ".", "GetCloudAccess", "(", "cloud", ",", "targetUserTag", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "// Conflicts with prior check, must be inconsistent state.", "err", "=", "txn", ".", "ErrExcessiveContention", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Only set access if greater access is being granted.", "if", "cloudAccess", ".", "EqualOrGreaterCloudAccessThan", "(", "access", ")", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "access", ")", "\n", "}", "\n", "if", "_", ",", "err", "=", "accessor", ".", "SetUserAccess", "(", "targetUserTag", ",", "names", ".", "NewCloudTag", "(", "cloud", ")", ",", "access", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// grantControllerCloudAccess exists for backwards compatibility since older clients // still set add-model on the controller rather than the controller cloud.
[ "grantControllerCloudAccess", "exists", "for", "backwards", "compatibility", "since", "older", "clients", "still", "set", "add", "-", "model", "on", "the", "controller", "rather", "than", "the", "controller", "cloud", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/controller/controller.go#L842-L873
3,975
juju/juju
apiserver/facades/client/controller/controller.go
ChangeControllerAccess
func ChangeControllerAccess(accessor *state.State, apiUser, targetUserTag names.UserTag, action params.ControllerAction, access permission.Access) error { switch action { case params.GrantControllerAccess: err := grantControllerAccess(accessor, targetUserTag, apiUser, access) if err != nil { return errors.Annotate(err, "could not grant controller access") } return nil case params.RevokeControllerAccess: return revokeControllerAccess(accessor, targetUserTag, apiUser, access) default: return errors.Errorf("unknown action %q", action) } }
go
func ChangeControllerAccess(accessor *state.State, apiUser, targetUserTag names.UserTag, action params.ControllerAction, access permission.Access) error { switch action { case params.GrantControllerAccess: err := grantControllerAccess(accessor, targetUserTag, apiUser, access) if err != nil { return errors.Annotate(err, "could not grant controller access") } return nil case params.RevokeControllerAccess: return revokeControllerAccess(accessor, targetUserTag, apiUser, access) default: return errors.Errorf("unknown action %q", action) } }
[ "func", "ChangeControllerAccess", "(", "accessor", "*", "state", ".", "State", ",", "apiUser", ",", "targetUserTag", "names", ".", "UserTag", ",", "action", "params", ".", "ControllerAction", ",", "access", "permission", ".", "Access", ")", "error", "{", "switch", "action", "{", "case", "params", ".", "GrantControllerAccess", ":", "err", ":=", "grantControllerAccess", "(", "accessor", ",", "targetUserTag", ",", "apiUser", ",", "access", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "case", "params", ".", "RevokeControllerAccess", ":", "return", "revokeControllerAccess", "(", "accessor", ",", "targetUserTag", ",", "apiUser", ",", "access", ")", "\n", "default", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "action", ")", "\n", "}", "\n", "}" ]
// ChangeControllerAccess performs the requested access grant or revoke action for the // specified user on the controller.
[ "ChangeControllerAccess", "performs", "the", "requested", "access", "grant", "or", "revoke", "action", "for", "the", "specified", "user", "on", "the", "controller", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/client/controller/controller.go#L943-L956
3,976
juju/juju
worker/lease/check.go
Check
func (t token) Check(attempt int, trapdoorKey interface{}) error { // This validation, which could be done at Token creation time, is deferred // until this point for historical reasons. In particular, this code was // extracted from a *leadership* implementation which has a LeadershipCheck // method returning a token; if it returned an error as well it would seem // to imply that the method implemented a check itself, rather than a check // factory. // // Fixing that would be great but seems out of scope. if err := t.secretary.CheckLease(t.leaseKey); err != nil { return errors.Annotatef(err, "cannot check lease %q", t.leaseKey.Lease) } if err := t.secretary.CheckHolder(t.holderName); err != nil { return errors.Annotatef(err, "cannot check holder %q", t.holderName) } return check{ leaseKey: t.leaseKey, holderName: t.holderName, attempt: attempt, trapdoorKey: trapdoorKey, response: make(chan error), stop: t.stop, }.invoke(t.checks) }
go
func (t token) Check(attempt int, trapdoorKey interface{}) error { // This validation, which could be done at Token creation time, is deferred // until this point for historical reasons. In particular, this code was // extracted from a *leadership* implementation which has a LeadershipCheck // method returning a token; if it returned an error as well it would seem // to imply that the method implemented a check itself, rather than a check // factory. // // Fixing that would be great but seems out of scope. if err := t.secretary.CheckLease(t.leaseKey); err != nil { return errors.Annotatef(err, "cannot check lease %q", t.leaseKey.Lease) } if err := t.secretary.CheckHolder(t.holderName); err != nil { return errors.Annotatef(err, "cannot check holder %q", t.holderName) } return check{ leaseKey: t.leaseKey, holderName: t.holderName, attempt: attempt, trapdoorKey: trapdoorKey, response: make(chan error), stop: t.stop, }.invoke(t.checks) }
[ "func", "(", "t", "token", ")", "Check", "(", "attempt", "int", ",", "trapdoorKey", "interface", "{", "}", ")", "error", "{", "// This validation, which could be done at Token creation time, is deferred", "// until this point for historical reasons. In particular, this code was", "// extracted from a *leadership* implementation which has a LeadershipCheck", "// method returning a token; if it returned an error as well it would seem", "// to imply that the method implemented a check itself, rather than a check", "// factory.", "//", "// Fixing that would be great but seems out of scope.", "if", "err", ":=", "t", ".", "secretary", ".", "CheckLease", "(", "t", ".", "leaseKey", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "t", ".", "leaseKey", ".", "Lease", ")", "\n", "}", "\n", "if", "err", ":=", "t", ".", "secretary", ".", "CheckHolder", "(", "t", ".", "holderName", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotatef", "(", "err", ",", "\"", "\"", ",", "t", ".", "holderName", ")", "\n", "}", "\n", "return", "check", "{", "leaseKey", ":", "t", ".", "leaseKey", ",", "holderName", ":", "t", ".", "holderName", ",", "attempt", ":", "attempt", ",", "trapdoorKey", ":", "trapdoorKey", ",", "response", ":", "make", "(", "chan", "error", ")", ",", "stop", ":", "t", ".", "stop", ",", "}", ".", "invoke", "(", "t", ".", "checks", ")", "\n", "}" ]
// Check is part of the lease.Token interface.
[ "Check", "is", "part", "of", "the", "lease", ".", "Token", "interface", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/lease/check.go#L22-L46
3,977
juju/juju
worker/lease/check.go
invoke
func (c check) invoke(ch chan<- check) error { for { select { case <-c.stop: return errStopped case ch <- c: ch = nil case err := <-c.response: return errors.Trace(err) } } }
go
func (c check) invoke(ch chan<- check) error { for { select { case <-c.stop: return errStopped case ch <- c: ch = nil case err := <-c.response: return errors.Trace(err) } } }
[ "func", "(", "c", "check", ")", "invoke", "(", "ch", "chan", "<-", "check", ")", "error", "{", "for", "{", "select", "{", "case", "<-", "c", ".", "stop", ":", "return", "errStopped", "\n", "case", "ch", "<-", "c", ":", "ch", "=", "nil", "\n", "case", "err", ":=", "<-", "c", ".", "response", ":", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "}" ]
// invoke sends the check on the supplied channel and waits for an error // response.
[ "invoke", "sends", "the", "check", "on", "the", "supplied", "channel", "and", "waits", "for", "an", "error", "response", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/lease/check.go#L61-L72
3,978
juju/juju
worker/lease/check.go
respond
func (c check) respond(err error) { select { case <-c.stop: case c.response <- err: } }
go
func (c check) respond(err error) { select { case <-c.stop: case c.response <- err: } }
[ "func", "(", "c", "check", ")", "respond", "(", "err", "error", ")", "{", "select", "{", "case", "<-", "c", ".", "stop", ":", "case", "c", ".", "response", "<-", "err", ":", "}", "\n", "}" ]
// respond notifies the originating invoke of completion status.
[ "respond", "notifies", "the", "originating", "invoke", "of", "completion", "status", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/lease/check.go#L75-L80
3,979
juju/juju
environs/gui/simplestreams.go
NewDataSource
func NewDataSource(baseURL string) simplestreams.DataSource { requireSigned := true return simplestreams.NewURLSignedDataSource( sourceDescription, baseURL, keys.JujuPublicKey, utils.VerifySSLHostnames, simplestreams.DEFAULT_CLOUD_DATA, requireSigned) }
go
func NewDataSource(baseURL string) simplestreams.DataSource { requireSigned := true return simplestreams.NewURLSignedDataSource( sourceDescription, baseURL, keys.JujuPublicKey, utils.VerifySSLHostnames, simplestreams.DEFAULT_CLOUD_DATA, requireSigned) }
[ "func", "NewDataSource", "(", "baseURL", "string", ")", "simplestreams", ".", "DataSource", "{", "requireSigned", ":=", "true", "\n", "return", "simplestreams", ".", "NewURLSignedDataSource", "(", "sourceDescription", ",", "baseURL", ",", "keys", ".", "JujuPublicKey", ",", "utils", ".", "VerifySSLHostnames", ",", "simplestreams", ".", "DEFAULT_CLOUD_DATA", ",", "requireSigned", ")", "\n", "}" ]
// DataSource creates and returns a new simplestreams signed data source for // fetching Juju GUI archives, at the given URL.
[ "DataSource", "creates", "and", "returns", "a", "new", "simplestreams", "signed", "data", "source", "for", "fetching", "Juju", "GUI", "archives", "at", "the", "given", "URL", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/gui/simplestreams.go#L39-L48
3,980
juju/juju
environs/gui/simplestreams.go
FetchMetadata
func FetchMetadata(stream string, sources ...simplestreams.DataSource) ([]*Metadata, error) { params := simplestreams.GetMetadataParams{ StreamsVersion: streamsVersion, LookupConstraint: &constraint{ LookupParams: simplestreams.LookupParams{Stream: stream}, majorVersion: jujuversion.Current.Major, }, ValueParams: simplestreams.ValueParams{ DataType: downloadType, MirrorContentId: contentId(stream), FilterFunc: appendArchives, ValueTemplate: Metadata{}, }, } items, _, err := simplestreams.GetMetadata(sources, params) if err != nil { return nil, errors.Annotate(err, "error fetching simplestreams metadata") } allMeta := make([]*Metadata, len(items)) for i, item := range items { allMeta[i] = item.(*Metadata) } sort.Sort(byVersion(allMeta)) return allMeta, nil }
go
func FetchMetadata(stream string, sources ...simplestreams.DataSource) ([]*Metadata, error) { params := simplestreams.GetMetadataParams{ StreamsVersion: streamsVersion, LookupConstraint: &constraint{ LookupParams: simplestreams.LookupParams{Stream: stream}, majorVersion: jujuversion.Current.Major, }, ValueParams: simplestreams.ValueParams{ DataType: downloadType, MirrorContentId: contentId(stream), FilterFunc: appendArchives, ValueTemplate: Metadata{}, }, } items, _, err := simplestreams.GetMetadata(sources, params) if err != nil { return nil, errors.Annotate(err, "error fetching simplestreams metadata") } allMeta := make([]*Metadata, len(items)) for i, item := range items { allMeta[i] = item.(*Metadata) } sort.Sort(byVersion(allMeta)) return allMeta, nil }
[ "func", "FetchMetadata", "(", "stream", "string", ",", "sources", "...", "simplestreams", ".", "DataSource", ")", "(", "[", "]", "*", "Metadata", ",", "error", ")", "{", "params", ":=", "simplestreams", ".", "GetMetadataParams", "{", "StreamsVersion", ":", "streamsVersion", ",", "LookupConstraint", ":", "&", "constraint", "{", "LookupParams", ":", "simplestreams", ".", "LookupParams", "{", "Stream", ":", "stream", "}", ",", "majorVersion", ":", "jujuversion", ".", "Current", ".", "Major", ",", "}", ",", "ValueParams", ":", "simplestreams", ".", "ValueParams", "{", "DataType", ":", "downloadType", ",", "MirrorContentId", ":", "contentId", "(", "stream", ")", ",", "FilterFunc", ":", "appendArchives", ",", "ValueTemplate", ":", "Metadata", "{", "}", ",", "}", ",", "}", "\n", "items", ",", "_", ",", "err", ":=", "simplestreams", ".", "GetMetadata", "(", "sources", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "allMeta", ":=", "make", "(", "[", "]", "*", "Metadata", ",", "len", "(", "items", ")", ")", "\n", "for", "i", ",", "item", ":=", "range", "items", "{", "allMeta", "[", "i", "]", "=", "item", ".", "(", "*", "Metadata", ")", "\n", "}", "\n", "sort", ".", "Sort", "(", "byVersion", "(", "allMeta", ")", ")", "\n", "return", "allMeta", ",", "nil", "\n", "}" ]
// FetchMetadata fetches and returns Juju GUI metadata from simplestreams, // sorted by version descending.
[ "FetchMetadata", "fetches", "and", "returns", "Juju", "GUI", "metadata", "from", "simplestreams", "sorted", "by", "version", "descending", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/gui/simplestreams.go#L52-L76
3,981
juju/juju
environs/gui/simplestreams.go
appendArchives
func appendArchives( source simplestreams.DataSource, matchingItems []interface{}, items map[string]interface{}, cons simplestreams.LookupConstraint, ) ([]interface{}, error) { var majorVersion int if guiConstraint, ok := cons.(*constraint); ok { majorVersion = guiConstraint.majorVersion } for _, item := range items { meta := item.(*Metadata) if majorVersion != 0 && majorVersion != meta.JujuMajorVersion { continue } fullPath, err := source.URL(meta.Path) if err != nil { return nil, errors.Annotate(err, "cannot retrieve metadata full path") } meta.FullPath = fullPath vers, err := version.Parse(meta.StringVersion) if err != nil { return nil, errors.Annotate(err, "cannot parse metadata version") } meta.Version = vers meta.Source = source matchingItems = append(matchingItems, meta) } return matchingItems, nil }
go
func appendArchives( source simplestreams.DataSource, matchingItems []interface{}, items map[string]interface{}, cons simplestreams.LookupConstraint, ) ([]interface{}, error) { var majorVersion int if guiConstraint, ok := cons.(*constraint); ok { majorVersion = guiConstraint.majorVersion } for _, item := range items { meta := item.(*Metadata) if majorVersion != 0 && majorVersion != meta.JujuMajorVersion { continue } fullPath, err := source.URL(meta.Path) if err != nil { return nil, errors.Annotate(err, "cannot retrieve metadata full path") } meta.FullPath = fullPath vers, err := version.Parse(meta.StringVersion) if err != nil { return nil, errors.Annotate(err, "cannot parse metadata version") } meta.Version = vers meta.Source = source matchingItems = append(matchingItems, meta) } return matchingItems, nil }
[ "func", "appendArchives", "(", "source", "simplestreams", ".", "DataSource", ",", "matchingItems", "[", "]", "interface", "{", "}", ",", "items", "map", "[", "string", "]", "interface", "{", "}", ",", "cons", "simplestreams", ".", "LookupConstraint", ",", ")", "(", "[", "]", "interface", "{", "}", ",", "error", ")", "{", "var", "majorVersion", "int", "\n", "if", "guiConstraint", ",", "ok", ":=", "cons", ".", "(", "*", "constraint", ")", ";", "ok", "{", "majorVersion", "=", "guiConstraint", ".", "majorVersion", "\n", "}", "\n", "for", "_", ",", "item", ":=", "range", "items", "{", "meta", ":=", "item", ".", "(", "*", "Metadata", ")", "\n", "if", "majorVersion", "!=", "0", "&&", "majorVersion", "!=", "meta", ".", "JujuMajorVersion", "{", "continue", "\n", "}", "\n", "fullPath", ",", "err", ":=", "source", ".", "URL", "(", "meta", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "meta", ".", "FullPath", "=", "fullPath", "\n", "vers", ",", "err", ":=", "version", ".", "Parse", "(", "meta", ".", "StringVersion", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "meta", ".", "Version", "=", "vers", "\n", "meta", ".", "Source", "=", "source", "\n", "matchingItems", "=", "append", "(", "matchingItems", ",", "meta", ")", "\n", "}", "\n", "return", "matchingItems", ",", "nil", "\n", "}" ]
// appendArchives collects all matching Juju GUI archive metadata information.
[ "appendArchives", "collects", "all", "matching", "Juju", "GUI", "archive", "metadata", "information", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/environs/gui/simplestreams.go#L130-L159
3,982
juju/juju
api/storageprovisioner/provisioner.go
NewState
func NewState(caller base.APICaller) (*State, error) { facadeCaller := base.NewFacadeCaller(caller, storageProvisionerFacade) return &State{facadeCaller}, nil }
go
func NewState(caller base.APICaller) (*State, error) { facadeCaller := base.NewFacadeCaller(caller, storageProvisionerFacade) return &State{facadeCaller}, nil }
[ "func", "NewState", "(", "caller", "base", ".", "APICaller", ")", "(", "*", "State", ",", "error", ")", "{", "facadeCaller", ":=", "base", ".", "NewFacadeCaller", "(", "caller", ",", "storageProvisionerFacade", ")", "\n", "return", "&", "State", "{", "facadeCaller", "}", ",", "nil", "\n", "}" ]
// NewState creates a new client-side StorageProvisioner facade.
[ "NewState", "creates", "a", "new", "client", "-", "side", "StorageProvisioner", "facade", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/storageprovisioner/provisioner.go#L24-L27
3,983
juju/juju
api/storageprovisioner/provisioner.go
WatchVolumes
func (st *State) WatchVolumes(scope names.Tag) (watcher.StringsWatcher, error) { return st.watchStorageEntities("WatchVolumes", scope) }
go
func (st *State) WatchVolumes(scope names.Tag) (watcher.StringsWatcher, error) { return st.watchStorageEntities("WatchVolumes", scope) }
[ "func", "(", "st", "*", "State", ")", "WatchVolumes", "(", "scope", "names", ".", "Tag", ")", "(", "watcher", ".", "StringsWatcher", ",", "error", ")", "{", "return", "st", ".", "watchStorageEntities", "(", "\"", "\"", ",", "scope", ")", "\n", "}" ]
// WatchVolumes watches for lifecycle changes to volumes scoped to the // entity with the specified tag.
[ "WatchVolumes", "watches", "for", "lifecycle", "changes", "to", "volumes", "scoped", "to", "the", "entity", "with", "the", "specified", "tag", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/storageprovisioner/provisioner.go#L87-L89
3,984
juju/juju
api/storageprovisioner/provisioner.go
WatchVolumeAttachments
func (st *State) WatchVolumeAttachments(scope names.Tag) (watcher.MachineStorageIdsWatcher, error) { return st.watchAttachments("WatchVolumeAttachments", scope, apiwatcher.NewVolumeAttachmentsWatcher) }
go
func (st *State) WatchVolumeAttachments(scope names.Tag) (watcher.MachineStorageIdsWatcher, error) { return st.watchAttachments("WatchVolumeAttachments", scope, apiwatcher.NewVolumeAttachmentsWatcher) }
[ "func", "(", "st", "*", "State", ")", "WatchVolumeAttachments", "(", "scope", "names", ".", "Tag", ")", "(", "watcher", ".", "MachineStorageIdsWatcher", ",", "error", ")", "{", "return", "st", ".", "watchAttachments", "(", "\"", "\"", ",", "scope", ",", "apiwatcher", ".", "NewVolumeAttachmentsWatcher", ")", "\n", "}" ]
// WatchVolumeAttachments watches for changes to volume attachments // scoped to the entity with the specified tag.
[ "WatchVolumeAttachments", "watches", "for", "changes", "to", "volume", "attachments", "scoped", "to", "the", "entity", "with", "the", "specified", "tag", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/storageprovisioner/provisioner.go#L119-L121
3,985
juju/juju
api/storageprovisioner/provisioner.go
WatchVolumeAttachmentPlans
func (st *State) WatchVolumeAttachmentPlans(scope names.Tag) (watcher.MachineStorageIdsWatcher, error) { return st.watchAttachments("WatchVolumeAttachmentPlans", scope, apiwatcher.NewVolumeAttachmentPlansWatcher) }
go
func (st *State) WatchVolumeAttachmentPlans(scope names.Tag) (watcher.MachineStorageIdsWatcher, error) { return st.watchAttachments("WatchVolumeAttachmentPlans", scope, apiwatcher.NewVolumeAttachmentPlansWatcher) }
[ "func", "(", "st", "*", "State", ")", "WatchVolumeAttachmentPlans", "(", "scope", "names", ".", "Tag", ")", "(", "watcher", ".", "MachineStorageIdsWatcher", ",", "error", ")", "{", "return", "st", ".", "watchAttachments", "(", "\"", "\"", ",", "scope", ",", "apiwatcher", ".", "NewVolumeAttachmentPlansWatcher", ")", "\n", "}" ]
// WatchVolumeAttachmentPlans watches for changes to volume attachments // scoped to the entity with the tag passed to NewState.
[ "WatchVolumeAttachmentPlans", "watches", "for", "changes", "to", "volume", "attachments", "scoped", "to", "the", "entity", "with", "the", "tag", "passed", "to", "NewState", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/storageprovisioner/provisioner.go#L125-L127
3,986
juju/juju
api/storageprovisioner/provisioner.go
WatchFilesystemAttachments
func (st *State) WatchFilesystemAttachments(scope names.Tag) (watcher.MachineStorageIdsWatcher, error) { return st.watchAttachments("WatchFilesystemAttachments", scope, apiwatcher.NewFilesystemAttachmentsWatcher) }
go
func (st *State) WatchFilesystemAttachments(scope names.Tag) (watcher.MachineStorageIdsWatcher, error) { return st.watchAttachments("WatchFilesystemAttachments", scope, apiwatcher.NewFilesystemAttachmentsWatcher) }
[ "func", "(", "st", "*", "State", ")", "WatchFilesystemAttachments", "(", "scope", "names", ".", "Tag", ")", "(", "watcher", ".", "MachineStorageIdsWatcher", ",", "error", ")", "{", "return", "st", ".", "watchAttachments", "(", "\"", "\"", ",", "scope", ",", "apiwatcher", ".", "NewFilesystemAttachmentsWatcher", ")", "\n", "}" ]
// WatchFilesystemAttachments watches for changes to filesystem attachments // scoped to the entity with the specified tag.
[ "WatchFilesystemAttachments", "watches", "for", "changes", "to", "filesystem", "attachments", "scoped", "to", "the", "entity", "with", "the", "specified", "tag", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/storageprovisioner/provisioner.go#L131-L133
3,987
juju/juju
api/storageprovisioner/provisioner.go
VolumeBlockDevices
func (st *State) VolumeBlockDevices(ids []params.MachineStorageId) ([]params.BlockDeviceResult, error) { args := params.MachineStorageIds{ids} var results params.BlockDeviceResults err := st.facade.FacadeCall("VolumeBlockDevices", args, &results) if err != nil { return nil, err } if len(results.Results) != len(ids) { return nil, errors.Errorf("expected %d result(s), got %d", len(ids), len(results.Results)) } return results.Results, nil }
go
func (st *State) VolumeBlockDevices(ids []params.MachineStorageId) ([]params.BlockDeviceResult, error) { args := params.MachineStorageIds{ids} var results params.BlockDeviceResults err := st.facade.FacadeCall("VolumeBlockDevices", args, &results) if err != nil { return nil, err } if len(results.Results) != len(ids) { return nil, errors.Errorf("expected %d result(s), got %d", len(ids), len(results.Results)) } return results.Results, nil }
[ "func", "(", "st", "*", "State", ")", "VolumeBlockDevices", "(", "ids", "[", "]", "params", ".", "MachineStorageId", ")", "(", "[", "]", "params", ".", "BlockDeviceResult", ",", "error", ")", "{", "args", ":=", "params", ".", "MachineStorageIds", "{", "ids", "}", "\n", "var", "results", "params", ".", "BlockDeviceResults", "\n", "err", ":=", "st", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "results", ".", "Results", ")", "!=", "len", "(", "ids", ")", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "ids", ")", ",", "len", "(", "results", ".", "Results", ")", ")", "\n", "}", "\n", "return", "results", ".", "Results", ",", "nil", "\n", "}" ]
// VolumeBlockDevices returns details of block devices corresponding to the volume // attachments with the specified IDs.
[ "VolumeBlockDevices", "returns", "details", "of", "block", "devices", "corresponding", "to", "the", "volume", "attachments", "with", "the", "specified", "IDs", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/storageprovisioner/provisioner.go#L237-L248
3,988
juju/juju
api/storageprovisioner/provisioner.go
VolumeParams
func (st *State) VolumeParams(tags []names.VolumeTag) ([]params.VolumeParamsResult, error) { args := params.Entities{ Entities: make([]params.Entity, len(tags)), } for i, tag := range tags { args.Entities[i].Tag = tag.String() } var results params.VolumeParamsResults err := st.facade.FacadeCall("VolumeParams", args, &results) if err != nil { return nil, err } if len(results.Results) != len(tags) { return nil, errors.Errorf("expected %d result(s), got %d", len(tags), len(results.Results)) } return results.Results, nil }
go
func (st *State) VolumeParams(tags []names.VolumeTag) ([]params.VolumeParamsResult, error) { args := params.Entities{ Entities: make([]params.Entity, len(tags)), } for i, tag := range tags { args.Entities[i].Tag = tag.String() } var results params.VolumeParamsResults err := st.facade.FacadeCall("VolumeParams", args, &results) if err != nil { return nil, err } if len(results.Results) != len(tags) { return nil, errors.Errorf("expected %d result(s), got %d", len(tags), len(results.Results)) } return results.Results, nil }
[ "func", "(", "st", "*", "State", ")", "VolumeParams", "(", "tags", "[", "]", "names", ".", "VolumeTag", ")", "(", "[", "]", "params", ".", "VolumeParamsResult", ",", "error", ")", "{", "args", ":=", "params", ".", "Entities", "{", "Entities", ":", "make", "(", "[", "]", "params", ".", "Entity", ",", "len", "(", "tags", ")", ")", ",", "}", "\n", "for", "i", ",", "tag", ":=", "range", "tags", "{", "args", ".", "Entities", "[", "i", "]", ".", "Tag", "=", "tag", ".", "String", "(", ")", "\n", "}", "\n", "var", "results", "params", ".", "VolumeParamsResults", "\n", "err", ":=", "st", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "results", ".", "Results", ")", "!=", "len", "(", "tags", ")", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "tags", ")", ",", "len", "(", "results", ".", "Results", ")", ")", "\n", "}", "\n", "return", "results", ".", "Results", ",", "nil", "\n", "}" ]
// VolumeParams returns the parameters for creating the volumes // with the specified tags.
[ "VolumeParams", "returns", "the", "parameters", "for", "creating", "the", "volumes", "with", "the", "specified", "tags", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/storageprovisioner/provisioner.go#L266-L282
3,989
juju/juju
api/storageprovisioner/provisioner.go
VolumeAttachmentParams
func (st *State) VolumeAttachmentParams(ids []params.MachineStorageId) ([]params.VolumeAttachmentParamsResult, error) { args := params.MachineStorageIds{ids} var results params.VolumeAttachmentParamsResults err := st.facade.FacadeCall("VolumeAttachmentParams", args, &results) if err != nil { return nil, err } if len(results.Results) != len(ids) { return nil, errors.Errorf("expected %d result(s), got %d", len(ids), len(results.Results)) } return results.Results, nil }
go
func (st *State) VolumeAttachmentParams(ids []params.MachineStorageId) ([]params.VolumeAttachmentParamsResult, error) { args := params.MachineStorageIds{ids} var results params.VolumeAttachmentParamsResults err := st.facade.FacadeCall("VolumeAttachmentParams", args, &results) if err != nil { return nil, err } if len(results.Results) != len(ids) { return nil, errors.Errorf("expected %d result(s), got %d", len(ids), len(results.Results)) } return results.Results, nil }
[ "func", "(", "st", "*", "State", ")", "VolumeAttachmentParams", "(", "ids", "[", "]", "params", ".", "MachineStorageId", ")", "(", "[", "]", "params", ".", "VolumeAttachmentParamsResult", ",", "error", ")", "{", "args", ":=", "params", ".", "MachineStorageIds", "{", "ids", "}", "\n", "var", "results", "params", ".", "VolumeAttachmentParamsResults", "\n", "err", ":=", "st", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "results", ".", "Results", ")", "!=", "len", "(", "ids", ")", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "ids", ")", ",", "len", "(", "results", ".", "Results", ")", ")", "\n", "}", "\n", "return", "results", ".", "Results", ",", "nil", "\n", "}" ]
// VolumeAttachmentParams returns the parameters for creating the volume // attachments with the specified tags.
[ "VolumeAttachmentParams", "returns", "the", "parameters", "for", "creating", "the", "volume", "attachments", "with", "the", "specified", "tags", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/storageprovisioner/provisioner.go#L346-L357
3,990
juju/juju
api/storageprovisioner/provisioner.go
FilesystemAttachmentParams
func (st *State) FilesystemAttachmentParams(ids []params.MachineStorageId) ([]params.FilesystemAttachmentParamsResult, error) { args := params.MachineStorageIds{ids} var results params.FilesystemAttachmentParamsResults err := st.facade.FacadeCall("FilesystemAttachmentParams", args, &results) if err != nil { return nil, err } if len(results.Results) != len(ids) { return nil, errors.Errorf("expected %d result(s), got %d", len(ids), len(results.Results)) } return results.Results, nil }
go
func (st *State) FilesystemAttachmentParams(ids []params.MachineStorageId) ([]params.FilesystemAttachmentParamsResult, error) { args := params.MachineStorageIds{ids} var results params.FilesystemAttachmentParamsResults err := st.facade.FacadeCall("FilesystemAttachmentParams", args, &results) if err != nil { return nil, err } if len(results.Results) != len(ids) { return nil, errors.Errorf("expected %d result(s), got %d", len(ids), len(results.Results)) } return results.Results, nil }
[ "func", "(", "st", "*", "State", ")", "FilesystemAttachmentParams", "(", "ids", "[", "]", "params", ".", "MachineStorageId", ")", "(", "[", "]", "params", ".", "FilesystemAttachmentParamsResult", ",", "error", ")", "{", "args", ":=", "params", ".", "MachineStorageIds", "{", "ids", "}", "\n", "var", "results", "params", ".", "FilesystemAttachmentParamsResults", "\n", "err", ":=", "st", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "results", ".", "Results", ")", "!=", "len", "(", "ids", ")", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "ids", ")", ",", "len", "(", "results", ".", "Results", ")", ")", "\n", "}", "\n", "return", "results", ".", "Results", ",", "nil", "\n", "}" ]
// FilesystemAttachmentParams returns the parameters for creating the // filesystem attachments with the specified tags.
[ "FilesystemAttachmentParams", "returns", "the", "parameters", "for", "creating", "the", "filesystem", "attachments", "with", "the", "specified", "tags", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/storageprovisioner/provisioner.go#L361-L372
3,991
juju/juju
api/storageprovisioner/provisioner.go
Life
func (st *State) Life(tags []names.Tag) ([]params.LifeResult, error) { var results params.LifeResults args := params.Entities{ Entities: make([]params.Entity, len(tags)), } for i, tag := range tags { args.Entities[i].Tag = tag.String() } if err := st.facade.FacadeCall("Life", args, &results); err != nil { return nil, err } if len(results.Results) != len(tags) { return nil, errors.Errorf("expected %d result(s), got %d", len(tags), len(results.Results)) } return results.Results, nil }
go
func (st *State) Life(tags []names.Tag) ([]params.LifeResult, error) { var results params.LifeResults args := params.Entities{ Entities: make([]params.Entity, len(tags)), } for i, tag := range tags { args.Entities[i].Tag = tag.String() } if err := st.facade.FacadeCall("Life", args, &results); err != nil { return nil, err } if len(results.Results) != len(tags) { return nil, errors.Errorf("expected %d result(s), got %d", len(tags), len(results.Results)) } return results.Results, nil }
[ "func", "(", "st", "*", "State", ")", "Life", "(", "tags", "[", "]", "names", ".", "Tag", ")", "(", "[", "]", "params", ".", "LifeResult", ",", "error", ")", "{", "var", "results", "params", ".", "LifeResults", "\n", "args", ":=", "params", ".", "Entities", "{", "Entities", ":", "make", "(", "[", "]", "params", ".", "Entity", ",", "len", "(", "tags", ")", ")", ",", "}", "\n", "for", "i", ",", "tag", ":=", "range", "tags", "{", "args", ".", "Entities", "[", "i", "]", ".", "Tag", "=", "tag", ".", "String", "(", ")", "\n", "}", "\n", "if", "err", ":=", "st", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "results", ".", "Results", ")", "!=", "len", "(", "tags", ")", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "tags", ")", ",", "len", "(", "results", ".", "Results", ")", ")", "\n", "}", "\n", "return", "results", ".", "Results", ",", "nil", "\n", "}" ]
// Life requests the life cycle of the entities with the specified tags.
[ "Life", "requests", "the", "life", "cycle", "of", "the", "entities", "with", "the", "specified", "tags", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/storageprovisioner/provisioner.go#L457-L472
3,992
juju/juju
api/storageprovisioner/provisioner.go
AttachmentLife
func (st *State) AttachmentLife(ids []params.MachineStorageId) ([]params.LifeResult, error) { var results params.LifeResults args := params.MachineStorageIds{ids} if err := st.facade.FacadeCall("AttachmentLife", args, &results); err != nil { return nil, err } if len(results.Results) != len(ids) { return nil, errors.Errorf("expected %d result(s), got %d", len(ids), len(results.Results)) } return results.Results, nil }
go
func (st *State) AttachmentLife(ids []params.MachineStorageId) ([]params.LifeResult, error) { var results params.LifeResults args := params.MachineStorageIds{ids} if err := st.facade.FacadeCall("AttachmentLife", args, &results); err != nil { return nil, err } if len(results.Results) != len(ids) { return nil, errors.Errorf("expected %d result(s), got %d", len(ids), len(results.Results)) } return results.Results, nil }
[ "func", "(", "st", "*", "State", ")", "AttachmentLife", "(", "ids", "[", "]", "params", ".", "MachineStorageId", ")", "(", "[", "]", "params", ".", "LifeResult", ",", "error", ")", "{", "var", "results", "params", ".", "LifeResults", "\n", "args", ":=", "params", ".", "MachineStorageIds", "{", "ids", "}", "\n", "if", "err", ":=", "st", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "results", ".", "Results", ")", "!=", "len", "(", "ids", ")", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "ids", ")", ",", "len", "(", "results", ".", "Results", ")", ")", "\n", "}", "\n", "return", "results", ".", "Results", ",", "nil", "\n", "}" ]
// AttachmentLife requests the life cycle of the attachments with the specified IDs.
[ "AttachmentLife", "requests", "the", "life", "cycle", "of", "the", "attachments", "with", "the", "specified", "IDs", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/storageprovisioner/provisioner.go#L475-L485
3,993
juju/juju
api/storageprovisioner/provisioner.go
EnsureDead
func (st *State) EnsureDead(tags []names.Tag) ([]params.ErrorResult, error) { var results params.ErrorResults args := params.Entities{ Entities: make([]params.Entity, len(tags)), } for i, tag := range tags { args.Entities[i].Tag = tag.String() } if err := st.facade.FacadeCall("EnsureDead", args, &results); err != nil { return nil, err } if len(results.Results) != len(tags) { return nil, errors.Errorf("expected %d result(s), got %d", len(tags), len(results.Results)) } return results.Results, nil }
go
func (st *State) EnsureDead(tags []names.Tag) ([]params.ErrorResult, error) { var results params.ErrorResults args := params.Entities{ Entities: make([]params.Entity, len(tags)), } for i, tag := range tags { args.Entities[i].Tag = tag.String() } if err := st.facade.FacadeCall("EnsureDead", args, &results); err != nil { return nil, err } if len(results.Results) != len(tags) { return nil, errors.Errorf("expected %d result(s), got %d", len(tags), len(results.Results)) } return results.Results, nil }
[ "func", "(", "st", "*", "State", ")", "EnsureDead", "(", "tags", "[", "]", "names", ".", "Tag", ")", "(", "[", "]", "params", ".", "ErrorResult", ",", "error", ")", "{", "var", "results", "params", ".", "ErrorResults", "\n", "args", ":=", "params", ".", "Entities", "{", "Entities", ":", "make", "(", "[", "]", "params", ".", "Entity", ",", "len", "(", "tags", ")", ")", ",", "}", "\n", "for", "i", ",", "tag", ":=", "range", "tags", "{", "args", ".", "Entities", "[", "i", "]", ".", "Tag", "=", "tag", ".", "String", "(", ")", "\n", "}", "\n", "if", "err", ":=", "st", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "results", ".", "Results", ")", "!=", "len", "(", "tags", ")", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "tags", ")", ",", "len", "(", "results", ".", "Results", ")", ")", "\n", "}", "\n", "return", "results", ".", "Results", ",", "nil", "\n", "}" ]
// EnsureDead progresses the entities with the specified tags to the Dead // life cycle state, if they are Alive or Dying.
[ "EnsureDead", "progresses", "the", "entities", "with", "the", "specified", "tags", "to", "the", "Dead", "life", "cycle", "state", "if", "they", "are", "Alive", "or", "Dying", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/storageprovisioner/provisioner.go#L489-L504
3,994
juju/juju
api/storageprovisioner/provisioner.go
RemoveAttachments
func (st *State) RemoveAttachments(ids []params.MachineStorageId) ([]params.ErrorResult, error) { var results params.ErrorResults args := params.MachineStorageIds{ids} if err := st.facade.FacadeCall("RemoveAttachment", args, &results); err != nil { return nil, err } if len(results.Results) != len(ids) { return nil, errors.Errorf("expected %d result(s), got %d", len(ids), len(results.Results)) } return results.Results, nil }
go
func (st *State) RemoveAttachments(ids []params.MachineStorageId) ([]params.ErrorResult, error) { var results params.ErrorResults args := params.MachineStorageIds{ids} if err := st.facade.FacadeCall("RemoveAttachment", args, &results); err != nil { return nil, err } if len(results.Results) != len(ids) { return nil, errors.Errorf("expected %d result(s), got %d", len(ids), len(results.Results)) } return results.Results, nil }
[ "func", "(", "st", "*", "State", ")", "RemoveAttachments", "(", "ids", "[", "]", "params", ".", "MachineStorageId", ")", "(", "[", "]", "params", ".", "ErrorResult", ",", "error", ")", "{", "var", "results", "params", ".", "ErrorResults", "\n", "args", ":=", "params", ".", "MachineStorageIds", "{", "ids", "}", "\n", "if", "err", ":=", "st", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "results", ".", "Results", ")", "!=", "len", "(", "ids", ")", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "ids", ")", ",", "len", "(", "results", ".", "Results", ")", ")", "\n", "}", "\n", "return", "results", ".", "Results", ",", "nil", "\n", "}" ]
// RemoveAttachments removes the attachments with the specified IDs from state.
[ "RemoveAttachments", "removes", "the", "attachments", "with", "the", "specified", "IDs", "from", "state", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/storageprovisioner/provisioner.go#L525-L535
3,995
juju/juju
api/storageprovisioner/provisioner.go
InstanceIds
func (st *State) InstanceIds(tags []names.MachineTag) ([]params.StringResult, error) { var results params.StringResults args := params.Entities{ Entities: make([]params.Entity, len(tags)), } for i, tag := range tags { args.Entities[i].Tag = tag.String() } err := st.facade.FacadeCall("InstanceId", args, &results) if err != nil { return nil, errors.Trace(err) } if len(results.Results) != 1 { return nil, errors.Errorf("expected %d result(s), got %d", len(results.Results), len(tags)) } return results.Results, nil }
go
func (st *State) InstanceIds(tags []names.MachineTag) ([]params.StringResult, error) { var results params.StringResults args := params.Entities{ Entities: make([]params.Entity, len(tags)), } for i, tag := range tags { args.Entities[i].Tag = tag.String() } err := st.facade.FacadeCall("InstanceId", args, &results) if err != nil { return nil, errors.Trace(err) } if len(results.Results) != 1 { return nil, errors.Errorf("expected %d result(s), got %d", len(results.Results), len(tags)) } return results.Results, nil }
[ "func", "(", "st", "*", "State", ")", "InstanceIds", "(", "tags", "[", "]", "names", ".", "MachineTag", ")", "(", "[", "]", "params", ".", "StringResult", ",", "error", ")", "{", "var", "results", "params", ".", "StringResults", "\n", "args", ":=", "params", ".", "Entities", "{", "Entities", ":", "make", "(", "[", "]", "params", ".", "Entity", ",", "len", "(", "tags", ")", ")", ",", "}", "\n", "for", "i", ",", "tag", ":=", "range", "tags", "{", "args", ".", "Entities", "[", "i", "]", ".", "Tag", "=", "tag", ".", "String", "(", ")", "\n", "}", "\n", "err", ":=", "st", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "args", ",", "&", "results", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "results", ".", "Results", ")", "!=", "1", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "results", ".", "Results", ")", ",", "len", "(", "tags", ")", ")", "\n", "}", "\n", "return", "results", ".", "Results", ",", "nil", "\n", "}" ]
// InstanceIds returns the provider specific instance ID for each machine, // or an CodeNotProvisioned error if not set.
[ "InstanceIds", "returns", "the", "provider", "specific", "instance", "ID", "for", "each", "machine", "or", "an", "CodeNotProvisioned", "error", "if", "not", "set", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/storageprovisioner/provisioner.go#L539-L555
3,996
juju/juju
api/storageprovisioner/provisioner.go
SetStatus
func (st *State) SetStatus(args []params.EntityStatusArgs) error { var result params.ErrorResults err := st.facade.FacadeCall("SetStatus", params.SetStatus{args}, &result) if err != nil { return err } return result.Combine() }
go
func (st *State) SetStatus(args []params.EntityStatusArgs) error { var result params.ErrorResults err := st.facade.FacadeCall("SetStatus", params.SetStatus{args}, &result) if err != nil { return err } return result.Combine() }
[ "func", "(", "st", "*", "State", ")", "SetStatus", "(", "args", "[", "]", "params", ".", "EntityStatusArgs", ")", "error", "{", "var", "result", "params", ".", "ErrorResults", "\n", "err", ":=", "st", ".", "facade", ".", "FacadeCall", "(", "\"", "\"", ",", "params", ".", "SetStatus", "{", "args", "}", ",", "&", "result", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "result", ".", "Combine", "(", ")", "\n", "}" ]
// SetStatus sets the status of storage entities.
[ "SetStatus", "sets", "the", "status", "of", "storage", "entities", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/api/storageprovisioner/provisioner.go#L558-L565
3,997
juju/juju
apiserver/facades/agent/uniter/subordinaterelationwatcher.go
newSubordinateRelationsWatcher
func newSubordinateRelationsWatcher(backend *state.State, subordinateApp *state.Application, principalName string) ( state.StringsWatcher, error, ) { w := &subRelationsWatcher{ backend: backend, app: subordinateApp, principalName: principalName, relations: make(map[string]bool), out: make(chan []string), } err := catacomb.Invoke(catacomb.Plan{ Site: &w.catacomb, Work: w.loop, }) return w, errors.Trace(err) }
go
func newSubordinateRelationsWatcher(backend *state.State, subordinateApp *state.Application, principalName string) ( state.StringsWatcher, error, ) { w := &subRelationsWatcher{ backend: backend, app: subordinateApp, principalName: principalName, relations: make(map[string]bool), out: make(chan []string), } err := catacomb.Invoke(catacomb.Plan{ Site: &w.catacomb, Work: w.loop, }) return w, errors.Trace(err) }
[ "func", "newSubordinateRelationsWatcher", "(", "backend", "*", "state", ".", "State", ",", "subordinateApp", "*", "state", ".", "Application", ",", "principalName", "string", ")", "(", "state", ".", "StringsWatcher", ",", "error", ",", ")", "{", "w", ":=", "&", "subRelationsWatcher", "{", "backend", ":", "backend", ",", "app", ":", "subordinateApp", ",", "principalName", ":", "principalName", ",", "relations", ":", "make", "(", "map", "[", "string", "]", "bool", ")", ",", "out", ":", "make", "(", "chan", "[", "]", "string", ")", ",", "}", "\n", "err", ":=", "catacomb", ".", "Invoke", "(", "catacomb", ".", "Plan", "{", "Site", ":", "&", "w", ".", "catacomb", ",", "Work", ":", "w", ".", "loop", ",", "}", ")", "\n", "return", "w", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// newSubordinateRelationsWatcher creates a watcher that will notify // about relation lifecycle events for subordinateApp, but filtered to // be relevant to a unit deployed to a container with the // principalName app. Global relations will be included, but only // container-scoped relations for the principal application will be // emitted - other container-scoped relations will be filtered out.
[ "newSubordinateRelationsWatcher", "creates", "a", "watcher", "that", "will", "notify", "about", "relation", "lifecycle", "events", "for", "subordinateApp", "but", "filtered", "to", "be", "relevant", "to", "a", "unit", "deployed", "to", "a", "container", "with", "the", "principalName", "app", ".", "Global", "relations", "will", "be", "included", "but", "only", "container", "-", "scoped", "relations", "for", "the", "principal", "application", "will", "be", "emitted", "-", "other", "container", "-", "scoped", "relations", "will", "be", "filtered", "out", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/facades/agent/uniter/subordinaterelationwatcher.go#L33-L48
3,998
juju/juju
apiserver/params/metrics.go
OneError
func (m *MetricResults) OneError() error { for _, r := range m.Results { if err := r.Error; err != nil { return err } } return nil }
go
func (m *MetricResults) OneError() error { for _, r := range m.Results { if err := r.Error; err != nil { return err } } return nil }
[ "func", "(", "m", "*", "MetricResults", ")", "OneError", "(", ")", "error", "{", "for", "_", ",", "r", ":=", "range", "m", ".", "Results", "{", "if", "err", ":=", "r", ".", "Error", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// OneError returns the first error
[ "OneError", "returns", "the", "first", "error" ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/apiserver/params/metrics.go#L17-L24
3,999
juju/juju
worker/uniter/hook/hook.go
Validate
func (hi Info) Validate() error { switch hi.Kind { case hooks.RelationJoined, hooks.RelationChanged, hooks.RelationDeparted: if hi.RemoteUnit == "" { return fmt.Errorf("%q hook requires a remote unit", hi.Kind) } fallthrough case hooks.Install, hooks.Start, hooks.ConfigChanged, hooks.UpgradeCharm, hooks.Stop, hooks.RelationBroken, hooks.CollectMetrics, hooks.MeterStatusChanged, hooks.UpdateStatus, hooks.PreSeriesUpgrade, hooks.PostSeriesUpgrade: return nil case hooks.Action: return fmt.Errorf("hooks.Kind Action is deprecated") case hooks.StorageAttached, hooks.StorageDetaching: if !names.IsValidStorage(hi.StorageId) { return fmt.Errorf("invalid storage ID %q", hi.StorageId) } return nil // TODO(fwereade): define these in charm/hooks... case LeaderElected, LeaderDeposed, LeaderSettingsChanged: return nil } return fmt.Errorf("unknown hook kind %q", hi.Kind) }
go
func (hi Info) Validate() error { switch hi.Kind { case hooks.RelationJoined, hooks.RelationChanged, hooks.RelationDeparted: if hi.RemoteUnit == "" { return fmt.Errorf("%q hook requires a remote unit", hi.Kind) } fallthrough case hooks.Install, hooks.Start, hooks.ConfigChanged, hooks.UpgradeCharm, hooks.Stop, hooks.RelationBroken, hooks.CollectMetrics, hooks.MeterStatusChanged, hooks.UpdateStatus, hooks.PreSeriesUpgrade, hooks.PostSeriesUpgrade: return nil case hooks.Action: return fmt.Errorf("hooks.Kind Action is deprecated") case hooks.StorageAttached, hooks.StorageDetaching: if !names.IsValidStorage(hi.StorageId) { return fmt.Errorf("invalid storage ID %q", hi.StorageId) } return nil // TODO(fwereade): define these in charm/hooks... case LeaderElected, LeaderDeposed, LeaderSettingsChanged: return nil } return fmt.Errorf("unknown hook kind %q", hi.Kind) }
[ "func", "(", "hi", "Info", ")", "Validate", "(", ")", "error", "{", "switch", "hi", ".", "Kind", "{", "case", "hooks", ".", "RelationJoined", ",", "hooks", ".", "RelationChanged", ",", "hooks", ".", "RelationDeparted", ":", "if", "hi", ".", "RemoteUnit", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hi", ".", "Kind", ")", "\n", "}", "\n", "fallthrough", "\n", "case", "hooks", ".", "Install", ",", "hooks", ".", "Start", ",", "hooks", ".", "ConfigChanged", ",", "hooks", ".", "UpgradeCharm", ",", "hooks", ".", "Stop", ",", "hooks", ".", "RelationBroken", ",", "hooks", ".", "CollectMetrics", ",", "hooks", ".", "MeterStatusChanged", ",", "hooks", ".", "UpdateStatus", ",", "hooks", ".", "PreSeriesUpgrade", ",", "hooks", ".", "PostSeriesUpgrade", ":", "return", "nil", "\n", "case", "hooks", ".", "Action", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "case", "hooks", ".", "StorageAttached", ",", "hooks", ".", "StorageDetaching", ":", "if", "!", "names", ".", "IsValidStorage", "(", "hi", ".", "StorageId", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hi", ".", "StorageId", ")", "\n", "}", "\n", "return", "nil", "\n", "// TODO(fwereade): define these in charm/hooks...", "case", "LeaderElected", ",", "LeaderDeposed", ",", "LeaderSettingsChanged", ":", "return", "nil", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hi", ".", "Kind", ")", "\n", "}" ]
// Validate returns an error if the info is not valid.
[ "Validate", "returns", "an", "error", "if", "the", "info", "is", "not", "valid", "." ]
ba728eedb1e44937c7bdc59f374b06400d0c7133
https://github.com/juju/juju/blob/ba728eedb1e44937c7bdc59f374b06400d0c7133/worker/uniter/hook/hook.go#L43-L65