repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
local-volume/provisioner/pkg/util/volume_util.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/volume_util.go#L210-L215
go
train
// DeleteContents removes all the contents under the given directory
func (u *FakeVolumeUtil) DeleteContents(fullPath string) error
// DeleteContents removes all the contents under the given directory func (u *FakeVolumeUtil) DeleteContents(fullPath string) error
{ if u.deleteShouldFail { return fmt.Errorf("Fake delete contents failed") } return nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
local-volume/provisioner/pkg/util/volume_util.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/volume_util.go#L218-L220
go
train
// GetFsCapacityByte returns capacity in byte about a mounted filesystem.
func (u *FakeVolumeUtil) GetFsCapacityByte(fullPath string) (int64, error)
// GetFsCapacityByte returns capacity in byte about a mounted filesystem. func (u *FakeVolumeUtil) GetFsCapacityByte(fullPath string) (int64, error)
{ return u.getDirEntryCapacity(fullPath, FakeEntryFile) }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
local-volume/provisioner/pkg/util/volume_util.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/volume_util.go#L223-L225
go
train
// GetBlockCapacityByte returns the space in the specified block device.
func (u *FakeVolumeUtil) GetBlockCapacityByte(fullPath string) (int64, error)
// GetBlockCapacityByte returns the space in the specified block device. func (u *FakeVolumeUtil) GetBlockCapacityByte(fullPath string) (int64, error)
{ return u.getDirEntryCapacity(fullPath, FakeEntryBlock) }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
local-volume/provisioner/pkg/util/volume_util.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/volume_util.go#L248-L258
go
train
// AddNewDirEntries adds the given files to the current directory listing // This is only for testing
func (u *FakeVolumeUtil) AddNewDirEntries(mountDir string, dirFiles map[string][]*FakeDirEntry)
// AddNewDirEntries adds the given files to the current directory listing // This is only for testing func (u *FakeVolumeUtil) AddNewDirEntries(mountDir string, dirFiles map[string][]*FakeDirEntry)
{ for dir, files := range dirFiles { mountedPath := filepath.Join(mountDir, dir) curFiles := u.directoryFiles[mountedPath] if curFiles == nil { curFiles = []*FakeDirEntry{} } glog.Infof("Adding to directory %q: files %v\n", dir, files) u.directoryFiles[mountedPath] = append(curFiles, files...) } }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/types.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/types.go#L261-L278
go
train
// GetSupportedVolumeFromPVSpec gets supported volume from PV spec
func GetSupportedVolumeFromPVSpec(spec *core_v1.PersistentVolumeSpec) string
// GetSupportedVolumeFromPVSpec gets supported volume from PV spec func GetSupportedVolumeFromPVSpec(spec *core_v1.PersistentVolumeSpec) string
{ if spec.HostPath != nil { return "hostPath" } if spec.AWSElasticBlockStore != nil { return "aws_ebs" } if spec.GCEPersistentDisk != nil { return "gce-pd" } if spec.Cinder != nil { return "cinder" } if spec.Glusterfs != nil { return "glusterfs" } return "" }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/types.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/types.go#L281-L298
go
train
// GetSupportedVolumeFromSnapshotDataSpec gets supported volume from snapshot data spec
func GetSupportedVolumeFromSnapshotDataSpec(spec *VolumeSnapshotDataSpec) string
// GetSupportedVolumeFromSnapshotDataSpec gets supported volume from snapshot data spec func GetSupportedVolumeFromSnapshotDataSpec(spec *VolumeSnapshotDataSpec) string
{ if spec.HostPath != nil { return "hostPath" } if spec.AWSElasticBlockStore != nil { return "aws_ebs" } if spec.GCEPersistentDiskSnapshot != nil { return "gce-pd" } if spec.CinderSnapshot != nil { return "cinder" } if spec.GlusterSnapshotVolume != nil { return "glusterfs" } return "" }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/types.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/types.go#L353-L362
go
train
// UnmarshalJSON unmarshalls json data
func (v *VolumeSnapshot) UnmarshalJSON(data []byte) error
// UnmarshalJSON unmarshalls json data func (v *VolumeSnapshot) UnmarshalJSON(data []byte) error
{ tmp := VolumeSnapshotCopy{} err := json.Unmarshal(data, &tmp) if err != nil { return err } tmp2 := VolumeSnapshot(tmp) *v = tmp2 return nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/types.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/types.go#L365-L374
go
train
// UnmarshalJSON unmarshals json data
func (vd *VolumeSnapshotList) UnmarshalJSON(data []byte) error
// UnmarshalJSON unmarshals json data func (vd *VolumeSnapshotList) UnmarshalJSON(data []byte) error
{ tmp := VolumeSnapshotListCopy{} err := json.Unmarshal(data, &tmp) if err != nil { return err } tmp2 := VolumeSnapshotList(tmp) *vd = tmp2 return nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/types.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/types.go#L377-L386
go
train
// UnmarshalJSON unmarshals json data
func (v *VolumeSnapshotData) UnmarshalJSON(data []byte) error
// UnmarshalJSON unmarshals json data func (v *VolumeSnapshotData) UnmarshalJSON(data []byte) error
{ tmp := VolumeSnapshotDataCopy{} err := json.Unmarshal(data, &tmp) if err != nil { return err } tmp2 := VolumeSnapshotData(tmp) *v = tmp2 return nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/types.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/types.go#L389-L398
go
train
// UnmarshalJSON unmarshals json data
func (vd *VolumeSnapshotDataList) UnmarshalJSON(data []byte) error
// UnmarshalJSON unmarshals json data func (vd *VolumeSnapshotDataList) UnmarshalJSON(data []byte) error
{ tmp := VolumeSnapshotDataListCopy{} err := json.Unmarshal(data, &tmp) if err != nil { return err } tmp2 := VolumeSnapshotDataList(tmp) *vd = tmp2 return nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/openstack/openstack_snapshots.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_snapshots.go#L144-L169
go
train
// CreateSnapshot from the specified volume
func (os *OpenStack) CreateSnapshot(sourceVolumeID, name, description string, tags map[string]string) (string, string, error)
// CreateSnapshot from the specified volume func (os *OpenStack) CreateSnapshot(sourceVolumeID, name, description string, tags map[string]string) (string, string, error)
{ snapshots, err := os.snapshotService() if err != nil || snapshots == nil { glog.Errorf("Unable to initialize cinder client for region: %s", os.region) return "", "", fmt.Errorf("Failed to create snapshot for volume %s: %v", sourceVolumeID, err) } opts := SnapshotCreateOpts{ VolumeID: sourceVolumeID, Name: name, Description: description, } if tags != nil { opts.Metadata = tags } snapshotID, status, err := snapshots.createSnapshot(opts) if err != nil { glog.Errorf("Failed to snapshot volume %s : %v", sourceVolumeID, err) return "", "", err } glog.Infof("Created snapshot %v from volume: %v", snapshotID, sourceVolumeID) return snapshotID, status, nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/openstack/openstack_snapshots.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_snapshots.go#L172-L184
go
train
// DeleteSnapshot deletes the specified snapshot
func (os *OpenStack) DeleteSnapshot(snapshotID string) error
// DeleteSnapshot deletes the specified snapshot func (os *OpenStack) DeleteSnapshot(snapshotID string) error
{ snapshots, err := os.snapshotService() if err != nil || snapshots == nil { glog.Errorf("Unable to initialize cinder client for region: %s", os.region) return err } err = snapshots.deleteSnapshot(snapshotID) if err != nil { glog.Errorf("Cannot delete snapshot %s: %v", snapshotID, err) } return nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/openstack/openstack_snapshots.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_snapshots.go#L188-L207
go
train
// DescribeSnapshot returns the status of the snapshot // FIXME(j-griffith): Name doesn't fit at all here, this is actually more like is `IsAvailable`
func (os *OpenStack) DescribeSnapshot(snapshotID string) (status string, isCompleted bool, err error)
// DescribeSnapshot returns the status of the snapshot // FIXME(j-griffith): Name doesn't fit at all here, this is actually more like is `IsAvailable` func (os *OpenStack) DescribeSnapshot(snapshotID string) (status string, isCompleted bool, err error)
{ ss, err := os.snapshotService() if err != nil || ss == nil { glog.Errorf("Unable to initialize cinder client for region: %s", os.region) return "", false, fmt.Errorf("Failed to describe snapshot %s: %v", snapshotID, err) } snap, err := ss.getSnapshot(snapshotID) if err != nil { glog.Errorf("error requesting snapshot %s: %v", snapshotID, err) } if err != nil { return "", false, err } if snap.Status != "available" { return snap.Status, false, nil } return snap.Status, true, nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/openstack/openstack_snapshots.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_snapshots.go#L210-L261
go
train
// FindSnapshot finds snapshot by metadata
func (os *OpenStack) FindSnapshot(tags map[string]string) ([]string, []string, error)
// FindSnapshot finds snapshot by metadata func (os *OpenStack) FindSnapshot(tags map[string]string) ([]string, []string, error)
{ var snapshotIDs, statuses []string ss, err := os.snapshotService() if err != nil || ss == nil { glog.Errorf("Unable to initialize cinder client for region: %s", os.region) return snapshotIDs, statuses, fmt.Errorf("Failed to find snapshot by tags %v: %v", tags, err) } opts := SnapshotListOpts{} snapshots, err := ss.listSnapshots(opts) if err != nil { glog.Errorf("Failed to list snapshots. Error: %v", err) return snapshotIDs, statuses, err } glog.Infof("Listed [%v] snapshots.", len(snapshots)) glog.Infof("Looking for matching tags [%#v] in snapshots.", tags) // Loop around to find the snapshot with the matching input metadata // NOTE(xyang): Metadata based filtering for snapshots is supported by Cinder volume API // microversion 3.21 and above. Currently the OpenStack Cloud Provider only supports V2.0. // Revisit this later when V3.0 is supported. for _, snapshot := range snapshots { glog.Infof("Looking for matching tags in snapshot [%#v].", snapshot) namespaceVal, ok := snapshot.Metadata[ctrlsnap.CloudSnapshotCreatedForVolumeSnapshotNamespaceTag] if ok { if tags[ctrlsnap.CloudSnapshotCreatedForVolumeSnapshotNamespaceTag] == namespaceVal { nameVal, ok := snapshot.Metadata[ctrlsnap.CloudSnapshotCreatedForVolumeSnapshotNameTag] if ok { if tags[ctrlsnap.CloudSnapshotCreatedForVolumeSnapshotNameTag] == nameVal { uidVal, ok := snapshot.Metadata[ctrlsnap.CloudSnapshotCreatedForVolumeSnapshotUIDTag] if ok { if tags[ctrlsnap.CloudSnapshotCreatedForVolumeSnapshotUIDTag] == uidVal { timeVal, ok := snapshot.Metadata[ctrlsnap.CloudSnapshotCreatedForVolumeSnapshotTimestampTag] if ok { if tags[ctrlsnap.CloudSnapshotCreatedForVolumeSnapshotTimestampTag] == timeVal { snapshotIDs = append(snapshotIDs, snapshot.ID) statuses = append(statuses, snapshot.Status) glog.Infof("Add snapshot [%#v].", snapshot) } } } } } } } } } return snapshotIDs, statuses, nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
repo-infra/kazel/config.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/repo-infra/kazel/config.go#L41-L52
go
train
// ReadCfg reads and unmarshals the specified json file into a Cfg struct.
func ReadCfg(cfgPath string) (*Cfg, error)
// ReadCfg reads and unmarshals the specified json file into a Cfg struct. func ReadCfg(cfgPath string) (*Cfg, error)
{ b, err := ioutil.ReadFile(cfgPath) if err != nil { return nil, err } var cfg Cfg if err := json.Unmarshal(b, &cfg); err != nil { return nil, err } defaultCfg(&cfg) return &cfg, nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
repo-infra/kazel/generator.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/repo-infra/kazel/generator.go#L40-L50
go
train
// walkGenerated updates the rule for kubernetes' OpenAPI generated file. // This involves reading all go files in the source tree and looking for the // "+k8s:openapi-gen" tag. If present, then that package must be supplied to // the genrule.
func (v *Vendorer) walkGenerated() error
// walkGenerated updates the rule for kubernetes' OpenAPI generated file. // This involves reading all go files in the source tree and looking for the // "+k8s:openapi-gen" tag. If present, then that package must be supplied to // the genrule. func (v *Vendorer) walkGenerated() error
{ if !v.cfg.K8sOpenAPIGen { return nil } v.managedAttrs = append(v.managedAttrs, "openapi_targets", "vendor_targets") paths, err := v.findOpenAPI(v.root) if err != nil { return err } return v.addGeneratedOpenAPIRule(paths) }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
repo-infra/kazel/generator.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/repo-infra/kazel/generator.go#L54-L87
go
train
// findOpenAPI searches for all packages under root that request OpenAPI. It // returns the go import paths. It does not follow symlinks.
func (v *Vendorer) findOpenAPI(root string) ([]string, error)
// findOpenAPI searches for all packages under root that request OpenAPI. It // returns the go import paths. It does not follow symlinks. func (v *Vendorer) findOpenAPI(root string) ([]string, error)
{ finfos, err := ioutil.ReadDir(root) if err != nil { return nil, err } var res []string var includeMe bool for _, finfo := range finfos { path := filepath.Join(root, finfo.Name()) if finfo.IsDir() && (finfo.Mode()&os.ModeSymlink == 0) { children, err := v.findOpenAPI(path) if err != nil { return nil, err } res = append(res, children...) } else if strings.HasSuffix(path, ".go") && !strings.HasSuffix(path, "_test.go") { b, err := ioutil.ReadFile(path) if err != nil { return nil, err } if bytes.Contains(b, []byte(openAPIGenTag)) { includeMe = true } } } if includeMe { pkg, err := v.ctx.ImportDir(root, 0) if err != nil { return nil, err } res = append(res, pkg.ImportPath) } return res, nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
repo-infra/kazel/generator.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/repo-infra/kazel/generator.go#L91-L117
go
train
// addGeneratedOpenAPIRule updates the pkg/generated/openapi go_default_library // rule with the automanaged openapi_targets and vendor_targets.
func (v *Vendorer) addGeneratedOpenAPIRule(paths []string) error
// addGeneratedOpenAPIRule updates the pkg/generated/openapi go_default_library // rule with the automanaged openapi_targets and vendor_targets. func (v *Vendorer) addGeneratedOpenAPIRule(paths []string) error
{ var openAPITargets []string var vendorTargets []string for _, p := range paths { if !strings.HasPrefix(p, baseImport) { return fmt.Errorf("openapi-gen path outside of kubernetes: %s", p) } np := p[len(baseImport):] if strings.HasPrefix(np, staging) { vendorTargets = append(vendorTargets, np[len(staging):]) } else { openAPITargets = append(openAPITargets, np) } } sort.Strings(openAPITargets) sort.Strings(vendorTargets) pkgPath := filepath.Join("pkg", "generated", "openapi") for _, r := range v.newRules[pkgPath] { if r.Name() == "go_default_library" { r.SetAttr("openapi_targets", asExpr(openAPITargets)) r.SetAttr("vendor_targets", asExpr(vendorTargets)) break } } return nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
ceph/rbd/pkg/provision/provision.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/ceph/rbd/pkg/provision/provision.go#L94-L103
go
train
// NewRBDProvisioner creates a Provisioner that provisions Ceph RBD PVs backed by Ceph RBD images.
func NewRBDProvisioner(client kubernetes.Interface, id string, timeout int, usePVName bool) controller.Provisioner
// NewRBDProvisioner creates a Provisioner that provisions Ceph RBD PVs backed by Ceph RBD images. func NewRBDProvisioner(client kubernetes.Interface, id string, timeout int, usePVName bool) controller.Provisioner
{ return &rbdProvisioner{ client: client, identity: id, rbdUtil: &RBDUtil{ timeout: timeout, }, usePVName: usePVName, } }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
ceph/rbd/pkg/provision/provision.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/ceph/rbd/pkg/provision/provision.go#L108-L113
go
train
// getAccessModes returns access modes RBD volume supported.
func (p *rbdProvisioner) getAccessModes() []v1.PersistentVolumeAccessMode
// getAccessModes returns access modes RBD volume supported. func (p *rbdProvisioner) getAccessModes() []v1.PersistentVolumeAccessMode
{ return []v1.PersistentVolumeAccessMode{ v1.ReadWriteOnce, v1.ReadOnlyMany, } }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
ceph/rbd/pkg/provision/provision.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/ceph/rbd/pkg/provision/provision.go#L116-L174
go
train
// Provision creates a storage asset and returns a PV object representing it.
func (p *rbdProvisioner) Provision(options controller.VolumeOptions) (*v1.PersistentVolume, error)
// Provision creates a storage asset and returns a PV object representing it. func (p *rbdProvisioner) Provision(options controller.VolumeOptions) (*v1.PersistentVolume, error)
{ if !util.AccessModesContainedInAll(p.getAccessModes(), options.PVC.Spec.AccessModes) { return nil, fmt.Errorf("invalid AccessModes %v: only AccessModes %v are supported", options.PVC.Spec.AccessModes, p.getAccessModes()) } if options.PVC.Spec.Selector != nil { return nil, fmt.Errorf("claim Selector is not supported") } opts, err := p.parseParameters(options.Parameters) if err != nil { return nil, err } image := options.PVName // If use-pv-name flag not set, generate image name if !p.usePVName { // create random image name image = fmt.Sprintf("kubernetes-dynamic-pvc-%s", uuid.NewUUID()) } rbd, sizeMB, err := p.rbdUtil.CreateImage(image, opts, options) if err != nil { klog.Errorf("rbd: create volume failed, err: %v", err) return nil, err } klog.Infof("successfully created rbd image %q", image) rbd.SecretRef = new(v1.SecretReference) rbd.SecretRef.Name = opts.userSecretName if len(opts.userSecretNamespace) > 0 { rbd.SecretRef.Namespace = opts.userSecretNamespace } rbd.RadosUser = opts.userID pv := &v1.PersistentVolume{ ObjectMeta: metav1.ObjectMeta{ Name: options.PVName, Annotations: map[string]string{ provisionerIDAnn: p.identity, }, }, Spec: v1.PersistentVolumeSpec{ PersistentVolumeReclaimPolicy: options.PersistentVolumeReclaimPolicy, AccessModes: options.PVC.Spec.AccessModes, VolumeMode: options.PVC.Spec.VolumeMode, MountOptions: options.MountOptions, Capacity: v1.ResourceList{ v1.ResourceName(v1.ResourceStorage): resource.MustParse(fmt.Sprintf("%dMi", sizeMB)), }, PersistentVolumeSource: v1.PersistentVolumeSource{ RBD: rbd, }, }, } // use default access modes if missing if len(pv.Spec.AccessModes) == 0 { klog.Warningf("no access modes specified, use default: %v", p.getAccessModes()) pv.Spec.AccessModes = p.getAccessModes() } return pv, nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
ceph/rbd/pkg/provision/provision.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/ceph/rbd/pkg/provision/provision.go#L178-L198
go
train
// Delete removes the storage asset that was created by Provision represented // by the given PV.
func (p *rbdProvisioner) Delete(volume *v1.PersistentVolume) error
// Delete removes the storage asset that was created by Provision represented // by the given PV. func (p *rbdProvisioner) Delete(volume *v1.PersistentVolume) error
{ // TODO: Should we check `pv.kubernetes.io/provisioned-by` key too? ann, ok := volume.Annotations[provisionerIDAnn] if !ok { return errors.New("identity annotation not found on PV") } if ann != p.identity { return &controller.IgnoredError{Reason: "identity annotation on PV does not match ours"} } class, err := p.client.StorageV1beta1().StorageClasses().Get(util.GetPersistentVolumeClass(volume), metav1.GetOptions{}) if err != nil { return err } opts, err := p.parseParameters(class.Parameters) if err != nil { return err } image := volume.Spec.PersistentVolumeSource.RBD.RBDImage return p.rbdUtil.DeleteImage(image, opts) }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
ceph/rbd/pkg/provision/provision.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/ceph/rbd/pkg/provision/provision.go#L310-L329
go
train
// parsePVSecret retrives secret value for a given namespace and name.
func (p *rbdProvisioner) parsePVSecret(namespace, secretName string) (string, error)
// parsePVSecret retrives secret value for a given namespace and name. func (p *rbdProvisioner) parsePVSecret(namespace, secretName string) (string, error)
{ if p.client == nil { return "", fmt.Errorf("Cannot get kube client") } secrets, err := p.client.CoreV1().Secrets(namespace).Get(secretName, metav1.GetOptions{}) if err != nil { return "", err } // TODO: Should we check secret.Type, like `k8s.io/kubernetes/pkg/volume/util.GetSecretForPV` function? secret := "" for k, v := range secrets.Data { if k == secretKeyName { return string(v), nil } secret = string(v) } // If not found, the last secret in the map wins as done before return secret, nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/openstack/openstack_routes.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_routes.go#L148-L213
go
train
// CreateRoute creates a route
func (r *Routes) CreateRoute(clusterName string, nameHint string, route *cloudprovider.Route) error
// CreateRoute creates a route func (r *Routes) CreateRoute(clusterName string, nameHint string, route *cloudprovider.Route) error
{ glog.V(4).Infof("CreateRoute(%v, %v, %v)", clusterName, nameHint, route) onFailure := NewCaller() addr, err := getAddressByName(r.compute, route.TargetNode) if err != nil { return err } glog.V(4).Infof("Using nexthop %v for node %v", addr, route.TargetNode) router, err := routers.Get(r.network, r.opts.RouterID).Extract() if err != nil { return err } routes := router.Routes for _, item := range routes { if item.DestinationCIDR == route.DestinationCIDR && item.NextHop == addr { glog.V(4).Infof("Skipping existing route: %v", route) return nil } } routes = append(routes, routers.Route{ DestinationCIDR: route.DestinationCIDR, NextHop: addr, }) unwind, err := updateRoutes(r.network, router, routes) if err != nil { return err } defer onFailure.Call(unwind) port, err := getPortByIP(r.network, addr) if err != nil { return err } found := false for _, item := range port.AllowedAddressPairs { if item.IPAddress == route.DestinationCIDR { glog.V(4).Info("Found existing allowed-address-pair: ", item) found = true break } } if !found { newPairs := append(port.AllowedAddressPairs, neutronports.AddressPair{ IPAddress: route.DestinationCIDR, }) unwind, err := updateAllowedAddressPairs(r.network, &port, newPairs) if err != nil { return err } defer onFailure.Call(unwind) } glog.V(4).Infof("Route created: %v", route) onFailure.Disarm() return nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/openstack/openstack_routes.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_routes.go#L216-L284
go
train
// DeleteRoute deletes a route
func (r *Routes) DeleteRoute(clusterName string, route *cloudprovider.Route) error
// DeleteRoute deletes a route func (r *Routes) DeleteRoute(clusterName string, route *cloudprovider.Route) error
{ glog.V(4).Infof("DeleteRoute(%v, %v)", clusterName, route) onFailure := NewCaller() addr, err := getAddressByName(r.compute, route.TargetNode) if err != nil { return err } router, err := routers.Get(r.network, r.opts.RouterID).Extract() if err != nil { return err } routes := router.Routes index := -1 for i, item := range routes { if item.DestinationCIDR == route.DestinationCIDR && item.NextHop == addr { index = i break } } if index == -1 { glog.V(4).Infof("Skipping non-existent route: %v", route) return nil } // Delete element `index` routes[index] = routes[len(routes)-1] routes = routes[:len(routes)-1] unwind, err := updateRoutes(r.network, router, routes) if err != nil { return err } defer onFailure.Call(unwind) port, err := getPortByIP(r.network, addr) if err != nil { return err } addrPairs := port.AllowedAddressPairs index = -1 for i, item := range addrPairs { if item.IPAddress == route.DestinationCIDR { index = i break } } if index != -1 { // Delete element `index` addrPairs[index] = addrPairs[len(routes)-1] addrPairs = addrPairs[:len(routes)-1] unwind, err := updateAllowedAddressPairs(r.network, &port, addrPairs) if err != nil { return err } defer onFailure.Call(unwind) } glog.V(4).Infof("Route deleted: %v", route) onFailure.Disarm() return nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L34-L41
go
train
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AWSElasticBlockStoreVolumeSnapshotSource.
func (in *AWSElasticBlockStoreVolumeSnapshotSource) DeepCopy() *AWSElasticBlockStoreVolumeSnapshotSource
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AWSElasticBlockStoreVolumeSnapshotSource. func (in *AWSElasticBlockStoreVolumeSnapshotSource) DeepCopy() *AWSElasticBlockStoreVolumeSnapshotSource
{ if in == nil { return nil } out := new(AWSElasticBlockStoreVolumeSnapshotSource) in.DeepCopyInto(out) return out }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L50-L57
go
train
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CinderVolumeSnapshotSource.
func (in *CinderVolumeSnapshotSource) DeepCopy() *CinderVolumeSnapshotSource
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CinderVolumeSnapshotSource. func (in *CinderVolumeSnapshotSource) DeepCopy() *CinderVolumeSnapshotSource
{ if in == nil { return nil } out := new(CinderVolumeSnapshotSource) in.DeepCopyInto(out) return out }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L66-L73
go
train
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GCEPersistentDiskSnapshotSource.
func (in *GCEPersistentDiskSnapshotSource) DeepCopy() *GCEPersistentDiskSnapshotSource
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GCEPersistentDiskSnapshotSource. func (in *GCEPersistentDiskSnapshotSource) DeepCopy() *GCEPersistentDiskSnapshotSource
{ if in == nil { return nil } out := new(GCEPersistentDiskSnapshotSource) in.DeepCopyInto(out) return out }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L82-L89
go
train
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GlusterVolumeSnapshotSource.
func (in *GlusterVolumeSnapshotSource) DeepCopy() *GlusterVolumeSnapshotSource
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GlusterVolumeSnapshotSource. func (in *GlusterVolumeSnapshotSource) DeepCopy() *GlusterVolumeSnapshotSource
{ if in == nil { return nil } out := new(GlusterVolumeSnapshotSource) in.DeepCopyInto(out) return out }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L98-L105
go
train
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HostPathVolumeSnapshotSource.
func (in *HostPathVolumeSnapshotSource) DeepCopy() *HostPathVolumeSnapshotSource
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HostPathVolumeSnapshotSource. func (in *HostPathVolumeSnapshotSource) DeepCopy() *HostPathVolumeSnapshotSource
{ if in == nil { return nil } out := new(HostPathVolumeSnapshotSource) in.DeepCopyInto(out) return out }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L108-L115
go
train
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *VolumeSnapshot) DeepCopyInto(out *VolumeSnapshot)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VolumeSnapshot) DeepCopyInto(out *VolumeSnapshot)
{ *out = *in out.TypeMeta = in.TypeMeta in.Metadata.DeepCopyInto(&out.Metadata) out.Spec = in.Spec in.Status.DeepCopyInto(&out.Status) return }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L118-L125
go
train
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshot.
func (in *VolumeSnapshot) DeepCopy() *VolumeSnapshot
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshot. func (in *VolumeSnapshot) DeepCopy() *VolumeSnapshot
{ if in == nil { return nil } out := new(VolumeSnapshot) in.DeepCopyInto(out) return out }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L128-L134
go
train
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *VolumeSnapshot) DeepCopyObject() runtime.Object
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *VolumeSnapshot) DeepCopyObject() runtime.Object
{ if c := in.DeepCopy(); c != nil { return c } else { return nil } }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L137-L144
go
train
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotCondition.
func (in *VolumeSnapshotCondition) DeepCopy() *VolumeSnapshotCondition
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotCondition. func (in *VolumeSnapshotCondition) DeepCopy() *VolumeSnapshotCondition
{ if in == nil { return nil } out := new(VolumeSnapshotCondition) in.DeepCopyInto(out) return out }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L147-L154
go
train
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *VolumeSnapshotCopy) DeepCopyInto(out *VolumeSnapshotCopy)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VolumeSnapshotCopy) DeepCopyInto(out *VolumeSnapshotCopy)
{ *out = *in out.TypeMeta = in.TypeMeta in.Metadata.DeepCopyInto(&out.Metadata) out.Spec = in.Spec in.Status.DeepCopyInto(&out.Status) return }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L157-L164
go
train
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotCopy.
func (in *VolumeSnapshotCopy) DeepCopy() *VolumeSnapshotCopy
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotCopy. func (in *VolumeSnapshotCopy) DeepCopy() *VolumeSnapshotCopy
{ if in == nil { return nil } out := new(VolumeSnapshotCopy) in.DeepCopyInto(out) return out }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L167-L174
go
train
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *VolumeSnapshotData) DeepCopyInto(out *VolumeSnapshotData)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VolumeSnapshotData) DeepCopyInto(out *VolumeSnapshotData)
{ *out = *in out.TypeMeta = in.TypeMeta in.Metadata.DeepCopyInto(&out.Metadata) in.Spec.DeepCopyInto(&out.Spec) in.Status.DeepCopyInto(&out.Status) return }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L177-L184
go
train
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotData.
func (in *VolumeSnapshotData) DeepCopy() *VolumeSnapshotData
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotData. func (in *VolumeSnapshotData) DeepCopy() *VolumeSnapshotData
{ if in == nil { return nil } out := new(VolumeSnapshotData) in.DeepCopyInto(out) return out }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L187-L193
go
train
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *VolumeSnapshotData) DeepCopyObject() runtime.Object
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *VolumeSnapshotData) DeepCopyObject() runtime.Object
{ if c := in.DeepCopy(); c != nil { return c } else { return nil } }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L196-L203
go
train
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotDataCondition.
func (in *VolumeSnapshotDataCondition) DeepCopy() *VolumeSnapshotDataCondition
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotDataCondition. func (in *VolumeSnapshotDataCondition) DeepCopy() *VolumeSnapshotDataCondition
{ if in == nil { return nil } out := new(VolumeSnapshotDataCondition) in.DeepCopyInto(out) return out }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L206-L213
go
train
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *VolumeSnapshotDataCopy) DeepCopyInto(out *VolumeSnapshotDataCopy)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VolumeSnapshotDataCopy) DeepCopyInto(out *VolumeSnapshotDataCopy)
{ *out = *in out.TypeMeta = in.TypeMeta in.Metadata.DeepCopyInto(&out.Metadata) in.Spec.DeepCopyInto(&out.Spec) in.Status.DeepCopyInto(&out.Status) return }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L216-L223
go
train
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotDataCopy.
func (in *VolumeSnapshotDataCopy) DeepCopy() *VolumeSnapshotDataCopy
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotDataCopy. func (in *VolumeSnapshotDataCopy) DeepCopy() *VolumeSnapshotDataCopy
{ if in == nil { return nil } out := new(VolumeSnapshotDataCopy) in.DeepCopyInto(out) return out }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L226-L238
go
train
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *VolumeSnapshotDataList) DeepCopyInto(out *VolumeSnapshotDataList)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VolumeSnapshotDataList) DeepCopyInto(out *VolumeSnapshotDataList)
{ *out = *in out.TypeMeta = in.TypeMeta out.Metadata = in.Metadata if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]VolumeSnapshotData, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L241-L248
go
train
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotDataList.
func (in *VolumeSnapshotDataList) DeepCopy() *VolumeSnapshotDataList
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotDataList. func (in *VolumeSnapshotDataList) DeepCopy() *VolumeSnapshotDataList
{ if in == nil { return nil } out := new(VolumeSnapshotDataList) in.DeepCopyInto(out) return out }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L251-L257
go
train
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *VolumeSnapshotDataList) DeepCopyObject() runtime.Object
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *VolumeSnapshotDataList) DeepCopyObject() runtime.Object
{ if c := in.DeepCopy(); c != nil { return c } else { return nil } }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L275-L282
go
train
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotDataListCopy.
func (in *VolumeSnapshotDataListCopy) DeepCopy() *VolumeSnapshotDataListCopy
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotDataListCopy. func (in *VolumeSnapshotDataListCopy) DeepCopy() *VolumeSnapshotDataListCopy
{ if in == nil { return nil } out := new(VolumeSnapshotDataListCopy) in.DeepCopyInto(out) return out }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L285-L333
go
train
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *VolumeSnapshotDataSource) DeepCopyInto(out *VolumeSnapshotDataSource)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VolumeSnapshotDataSource) DeepCopyInto(out *VolumeSnapshotDataSource)
{ *out = *in if in.HostPath != nil { in, out := &in.HostPath, &out.HostPath if *in == nil { *out = nil } else { *out = new(HostPathVolumeSnapshotSource) **out = **in } } if in.GlusterSnapshotVolume != nil { in, out := &in.GlusterSnapshotVolume, &out.GlusterSnapshotVolume if *in == nil { *out = nil } else { *out = new(GlusterVolumeSnapshotSource) **out = **in } } if in.AWSElasticBlockStore != nil { in, out := &in.AWSElasticBlockStore, &out.AWSElasticBlockStore if *in == nil { *out = nil } else { *out = new(AWSElasticBlockStoreVolumeSnapshotSource) **out = **in } } if in.GCEPersistentDiskSnapshot != nil { in, out := &in.GCEPersistentDiskSnapshot, &out.GCEPersistentDiskSnapshot if *in == nil { *out = nil } else { *out = new(GCEPersistentDiskSnapshotSource) **out = **in } } if in.CinderSnapshot != nil { in, out := &in.CinderSnapshot, &out.CinderSnapshot if *in == nil { *out = nil } else { *out = new(CinderVolumeSnapshotSource) **out = **in } } return }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L336-L343
go
train
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotDataSource.
func (in *VolumeSnapshotDataSource) DeepCopy() *VolumeSnapshotDataSource
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotDataSource. func (in *VolumeSnapshotDataSource) DeepCopy() *VolumeSnapshotDataSource
{ if in == nil { return nil } out := new(VolumeSnapshotDataSource) in.DeepCopyInto(out) return out }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L346-L353
go
train
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotDataSpec.
func (in *VolumeSnapshotDataSpec) DeepCopy() *VolumeSnapshotDataSpec
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotDataSpec. func (in *VolumeSnapshotDataSpec) DeepCopy() *VolumeSnapshotDataSpec
{ if in == nil { return nil } out := new(VolumeSnapshotDataSpec) in.DeepCopyInto(out) return out }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L356-L367
go
train
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *VolumeSnapshotDataStatus) DeepCopyInto(out *VolumeSnapshotDataStatus)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VolumeSnapshotDataStatus) DeepCopyInto(out *VolumeSnapshotDataStatus)
{ *out = *in in.CreationTimestamp.DeepCopyInto(&out.CreationTimestamp) if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions *out = make([]VolumeSnapshotDataCondition, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L370-L377
go
train
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotDataStatus.
func (in *VolumeSnapshotDataStatus) DeepCopy() *VolumeSnapshotDataStatus
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotDataStatus. func (in *VolumeSnapshotDataStatus) DeepCopy() *VolumeSnapshotDataStatus
{ if in == nil { return nil } out := new(VolumeSnapshotDataStatus) in.DeepCopyInto(out) return out }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L395-L402
go
train
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotList.
func (in *VolumeSnapshotList) DeepCopy() *VolumeSnapshotList
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotList. func (in *VolumeSnapshotList) DeepCopy() *VolumeSnapshotList
{ if in == nil { return nil } out := new(VolumeSnapshotList) in.DeepCopyInto(out) return out }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L405-L411
go
train
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *VolumeSnapshotList) DeepCopyObject() runtime.Object
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *VolumeSnapshotList) DeepCopyObject() runtime.Object
{ if c := in.DeepCopy(); c != nil { return c } else { return nil } }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L414-L426
go
train
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *VolumeSnapshotListCopy) DeepCopyInto(out *VolumeSnapshotListCopy)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VolumeSnapshotListCopy) DeepCopyInto(out *VolumeSnapshotListCopy)
{ *out = *in out.TypeMeta = in.TypeMeta out.Metadata = in.Metadata if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]VolumeSnapshot, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L429-L436
go
train
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotListCopy.
func (in *VolumeSnapshotListCopy) DeepCopy() *VolumeSnapshotListCopy
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotListCopy. func (in *VolumeSnapshotListCopy) DeepCopy() *VolumeSnapshotListCopy
{ if in == nil { return nil } out := new(VolumeSnapshotListCopy) in.DeepCopyInto(out) return out }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L445-L452
go
train
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotSpec.
func (in *VolumeSnapshotSpec) DeepCopy() *VolumeSnapshotSpec
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotSpec. func (in *VolumeSnapshotSpec) DeepCopy() *VolumeSnapshotSpec
{ if in == nil { return nil } out := new(VolumeSnapshotSpec) in.DeepCopyInto(out) return out }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L455-L466
go
train
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *VolumeSnapshotStatus) DeepCopyInto(out *VolumeSnapshotStatus)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VolumeSnapshotStatus) DeepCopyInto(out *VolumeSnapshotStatus)
{ *out = *in in.CreationTimestamp.DeepCopyInto(&out.CreationTimestamp) if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions *out = make([]VolumeSnapshotCondition, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L469-L476
go
train
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotStatus.
func (in *VolumeSnapshotStatus) DeepCopy() *VolumeSnapshotStatus
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotStatus. func (in *VolumeSnapshotStatus) DeepCopy() *VolumeSnapshotStatus
{ if in == nil { return nil } out := new(VolumeSnapshotStatus) in.DeepCopyInto(out) return out }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go#L548-L562
go
train
// GetLoadBalancer gets the status of the load balancer
func (lbaas *LbaasV2) GetLoadBalancer(clusterName string, service *v1.Service) (*v1.LoadBalancerStatus, bool, error)
// GetLoadBalancer gets the status of the load balancer func (lbaas *LbaasV2) GetLoadBalancer(clusterName string, service *v1.Service) (*v1.LoadBalancerStatus, bool, error)
{ loadBalancerName := cloudprovider.GetLoadBalancerName(service) loadbalancer, err := getLoadbalancerByName(lbaas.network, loadBalancerName) if err == ErrNotFound { return nil, false, nil } if loadbalancer == nil { return nil, false, err } status := &v1.LoadBalancerStatus{} status.Ingress = []v1.LoadBalancerIngress{{IP: loadbalancer.VipAddress}} return status, true, err }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go#L568-L581
go
train
// The LB needs to be configured with instance addresses on the same // subnet as the LB (aka opts.SubnetId). Currently we're just // guessing that the node's InternalIP is the right address - and that // should be sufficient for all "normal" cases.
func nodeAddressForLB(node *v1.Node) (string, error)
// The LB needs to be configured with instance addresses on the same // subnet as the LB (aka opts.SubnetId). Currently we're just // guessing that the node's InternalIP is the right address - and that // should be sufficient for all "normal" cases. func nodeAddressForLB(node *v1.Node) (string, error)
{ addrs := node.Status.Addresses if len(addrs) == 0 { return "", ErrNoAddressFound } for _, addr := range addrs { if addr.Type == v1.NodeInternalIP { return addr.Address, nil } } return addrs[0].Address, nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go#L589-L944
go
train
// TODO: This code currently ignores 'region' and always creates a // loadbalancer in only the current OpenStack region. We should take // a list of regions (from config) and query/create loadbalancers in // each region. // EnsureLoadBalancer ensures the load balancer works properly
func (lbaas *LbaasV2) EnsureLoadBalancer(clusterName string, apiService *v1.Service, nodes []*v1.Node) (*v1.LoadBalancerStatus, error)
// TODO: This code currently ignores 'region' and always creates a // loadbalancer in only the current OpenStack region. We should take // a list of regions (from config) and query/create loadbalancers in // each region. // EnsureLoadBalancer ensures the load balancer works properly func (lbaas *LbaasV2) EnsureLoadBalancer(clusterName string, apiService *v1.Service, nodes []*v1.Node) (*v1.LoadBalancerStatus, error)
{ glog.V(4).Infof("EnsureLoadBalancer(%v, %v, %v, %v, %v, %v, %v)", clusterName, apiService.Namespace, apiService.Name, apiService.Spec.LoadBalancerIP, apiService.Spec.Ports, nodes, apiService.Annotations) ports := apiService.Spec.Ports if len(ports) == 0 { return nil, fmt.Errorf("no ports provided to openstack load balancer") } // Check for TCP protocol on each port // TODO: Convert all error messages to use an event recorder for _, port := range ports { if port.Protocol != v1.ProtocolTCP { return nil, fmt.Errorf("Only TCP LoadBalancer is supported for openstack load balancers") } } sourceRanges, err := service.GetLoadBalancerSourceRanges(apiService) if err != nil { return nil, err } if !service.IsAllowAll(sourceRanges) && !lbaas.opts.ManageSecurityGroups { return nil, fmt.Errorf("Source range restrictions are not supported for openstack load balancers without managing security groups") } affinity := apiService.Spec.SessionAffinity var persistence *v2pools.SessionPersistence switch affinity { case v1.ServiceAffinityNone: persistence = nil case v1.ServiceAffinityClientIP: persistence = &v2pools.SessionPersistence{Type: "SOURCE_IP"} default: return nil, fmt.Errorf("unsupported load balancer affinity: %v", affinity) } name := cloudprovider.GetLoadBalancerName(apiService) loadbalancer, err := getLoadbalancerByName(lbaas.network, name) if err != nil { if err != ErrNotFound { return nil, fmt.Errorf("Error getting loadbalancer %s: %v", name, err) } glog.V(2).Infof("Creating loadbalancer %s", name) loadbalancer, err = lbaas.createLoadBalancer(apiService, name) if err != nil { // Unknown error, retry later return nil, fmt.Errorf("Error creating loadbalancer %s: %v", name, err) } } else { glog.V(2).Infof("LoadBalancer %s already exists", name) } waitLoadbalancerActiveProvisioningStatus(lbaas.network, loadbalancer.ID) lbmethod := v2pools.LBMethod(lbaas.opts.LBMethod) if lbmethod == "" { lbmethod = v2pools.LBMethodRoundRobin } oldListeners, err := getListenersByLoadBalancerID(lbaas.network, loadbalancer.ID) if err != nil { return nil, fmt.Errorf("Error getting LB %s listeners: %v", name, err) } for portIndex, port := range ports { listener := getListenerForPort(oldListeners, port) if listener == nil { glog.V(4).Infof("Creating listener for port %d", int(port.Port)) listener, err = listeners.Create(lbaas.network, listeners.CreateOpts{ Name: fmt.Sprintf("listener_%s_%d", name, portIndex), Protocol: listeners.Protocol(port.Protocol), ProtocolPort: int(port.Port), LoadbalancerID: loadbalancer.ID, }).Extract() if err != nil { // Unknown error, retry later return nil, fmt.Errorf("Error creating LB listener: %v", err) } waitLoadbalancerActiveProvisioningStatus(lbaas.network, loadbalancer.ID) } glog.V(4).Infof("Listener for %s port %d: %s", string(port.Protocol), int(port.Port), listener.ID) // After all ports have been processed, remaining listeners are removed as obsolete. // Pop valid listeners. oldListeners = popListener(oldListeners, listener.ID) pool, err := getPoolByListenerID(lbaas.network, loadbalancer.ID, listener.ID) if err != nil && err != ErrNotFound { // Unknown error, retry later return nil, fmt.Errorf("Error getting pool for listener %s: %v", listener.ID, err) } if pool == nil { glog.V(4).Infof("Creating pool for listener %s", listener.ID) pool, err = v2pools.Create(lbaas.network, v2pools.CreateOpts{ Name: fmt.Sprintf("pool_%s_%d", name, portIndex), Protocol: v2pools.Protocol(port.Protocol), LBMethod: lbmethod, ListenerID: listener.ID, Persistence: persistence, }).Extract() if err != nil { // Unknown error, retry later return nil, fmt.Errorf("Error creating pool for listener %s: %v", listener.ID, err) } waitLoadbalancerActiveProvisioningStatus(lbaas.network, loadbalancer.ID) } glog.V(4).Infof("Pool for listener %s: %s", listener.ID, pool.ID) members, err := getMembersByPoolID(lbaas.network, pool.ID) if err != nil && !isNotFound(err) { return nil, fmt.Errorf("Error getting pool members %s: %v", pool.ID, err) } for _, node := range nodes { addr, err := nodeAddressForLB(node) if err != nil { if err == ErrNotFound { // Node failure, do not create member glog.Warningf("Failed to create LB pool member for node %s: %v", node.Name, err) continue } else { return nil, fmt.Errorf("Error getting address for node %s: %v", node.Name, err) } } if !memberExists(members, addr, int(port.NodePort)) { glog.V(4).Infof("Creating member for pool %s", pool.ID) _, err := v2pools.CreateMember(lbaas.network, pool.ID, v2pools.CreateMemberOpts{ ProtocolPort: int(port.NodePort), Address: addr, SubnetID: lbaas.opts.SubnetID, }).Extract() if err != nil { return nil, fmt.Errorf("Error creating LB pool member for node: %s, %v", node.Name, err) } waitLoadbalancerActiveProvisioningStatus(lbaas.network, loadbalancer.ID) } else { // After all members have been processed, remaining members are deleted as obsolete. members = popMember(members, addr, int(port.NodePort)) } glog.V(4).Infof("Ensured pool %s has member for %s at %s", pool.ID, node.Name, addr) } // Delete obsolete members for this pool for _, member := range members { glog.V(4).Infof("Deleting obsolete member %s for pool %s address %s", member.ID, pool.ID, member.Address) err := v2pools.DeleteMember(lbaas.network, pool.ID, member.ID).ExtractErr() if err != nil && !isNotFound(err) { return nil, fmt.Errorf("Error deleting obsolete member %s for pool %s address %s: %v", member.ID, pool.ID, member.Address, err) } waitLoadbalancerActiveProvisioningStatus(lbaas.network, loadbalancer.ID) } monitorID := pool.MonitorID if monitorID == "" && lbaas.opts.CreateMonitor { glog.V(4).Infof("Creating monitor for pool %s", pool.ID) monitor, err := v2monitors.Create(lbaas.network, v2monitors.CreateOpts{ PoolID: pool.ID, Type: string(port.Protocol), Delay: int(lbaas.opts.MonitorDelay.Duration.Seconds()), Timeout: int(lbaas.opts.MonitorTimeout.Duration.Seconds()), MaxRetries: int(lbaas.opts.MonitorMaxRetries), }).Extract() if err != nil { return nil, fmt.Errorf("Error creating LB pool healthmonitor: %v", err) } waitLoadbalancerActiveProvisioningStatus(lbaas.network, loadbalancer.ID) monitorID = monitor.ID } glog.V(4).Infof("Monitor for pool %s: %s", pool.ID, monitorID) } // All remaining listeners are obsolete, delete for _, listener := range oldListeners { glog.V(4).Infof("Deleting obsolete listener %s:", listener.ID) // get pool for listener pool, err := getPoolByListenerID(lbaas.network, loadbalancer.ID, listener.ID) if err != nil && err != ErrNotFound { return nil, fmt.Errorf("Error getting pool for obsolete listener %s: %v", listener.ID, err) } if pool != nil { // get and delete monitor monitorID := pool.MonitorID if monitorID != "" { glog.V(4).Infof("Deleting obsolete monitor %s for pool %s", monitorID, pool.ID) err = v2monitors.Delete(lbaas.network, monitorID).ExtractErr() if err != nil && !isNotFound(err) { return nil, fmt.Errorf("Error deleting obsolete monitor %s for pool %s: %v", monitorID, pool.ID, err) } waitLoadbalancerActiveProvisioningStatus(lbaas.network, loadbalancer.ID) } // get and delete pool members members, poolErr := getMembersByPoolID(lbaas.network, pool.ID) if poolErr != nil && !isNotFound(poolErr) { return nil, fmt.Errorf("Error getting members for pool %s: %v", pool.ID, poolErr) } if members != nil { for _, member := range members { glog.V(4).Infof("Deleting obsolete member %s for pool %s address %s", member.ID, pool.ID, member.Address) err := v2pools.DeleteMember(lbaas.network, pool.ID, member.ID).ExtractErr() if err != nil && !isNotFound(err) { return nil, fmt.Errorf("Error deleting obsolete member %s for pool %s address %s: %v", member.ID, pool.ID, member.Address, err) } waitLoadbalancerActiveProvisioningStatus(lbaas.network, loadbalancer.ID) } } glog.V(4).Infof("Deleting obsolete pool %s for listener %s", pool.ID, listener.ID) // delete pool err = v2pools.Delete(lbaas.network, pool.ID).ExtractErr() if err != nil && !isNotFound(err) { return nil, fmt.Errorf("Error deleting obsolete pool %s for listener %s: %v", pool.ID, listener.ID, err) } waitLoadbalancerActiveProvisioningStatus(lbaas.network, loadbalancer.ID) } // delete listener err = listeners.Delete(lbaas.network, listener.ID).ExtractErr() if err != nil && !isNotFound(err) { return nil, fmt.Errorf("Error deleteting obsolete listener: %v", err) } waitLoadbalancerActiveProvisioningStatus(lbaas.network, loadbalancer.ID) glog.V(2).Infof("Deleted obsolete listener: %s", listener.ID) } status := &v1.LoadBalancerStatus{} status.Ingress = []v1.LoadBalancerIngress{{IP: loadbalancer.VipAddress}} portID := loadbalancer.VipPortID floatIP, err := getFloatingIPByPortID(lbaas.network, portID) if err != nil && err != ErrNotFound { return nil, fmt.Errorf("Error getting floating ip for port %s: %v", portID, err) } if floatIP == nil && lbaas.opts.FloatingNetworkID != "" { glog.V(4).Infof("Creating floating ip for loadbalancer %s port %s", loadbalancer.ID, portID) floatIPOpts := floatingips.CreateOpts{ FloatingNetworkID: lbaas.opts.FloatingNetworkID, PortID: portID, } floatIP, err = floatingips.Create(lbaas.network, floatIPOpts).Extract() if err != nil { return nil, fmt.Errorf("Error creating LB floatingip %+v: %v", floatIPOpts, err) } } if floatIP != nil { status.Ingress = append(status.Ingress, v1.LoadBalancerIngress{IP: floatIP.FloatingIP}) } if lbaas.opts.ManageSecurityGroups { lbSecGroupCreateOpts := groups.CreateOpts{ Name: getSecurityGroupName(clusterName, apiService), Description: fmt.Sprintf("Securty Group for %v Service LoadBalancer", apiService.Name), } lbSecGroup, err := groups.Create(lbaas.network, lbSecGroupCreateOpts).Extract() if err != nil { // cleanup what was created so far _ = lbaas.EnsureLoadBalancerDeleted(clusterName, apiService) return nil, err } for _, port := range ports { for _, sourceRange := range sourceRanges.StringSlice() { ethertype := rules.EtherType4 network, _, err := net.ParseCIDR(sourceRange) if err != nil { // cleanup what was created so far glog.Errorf("Error parsing source range %s as a CIDR", sourceRange) _ = lbaas.EnsureLoadBalancerDeleted(clusterName, apiService) return nil, err } if network.To4() == nil { ethertype = rules.EtherType6 } lbSecGroupRuleCreateOpts := rules.CreateOpts{ Direction: rules.DirIngress, PortRangeMax: int(port.Port), PortRangeMin: int(port.Port), Protocol: toRuleProtocol(port.Protocol), RemoteIPPrefix: sourceRange, SecGroupID: lbSecGroup.ID, EtherType: ethertype, } _, err = rules.Create(lbaas.network, lbSecGroupRuleCreateOpts).Extract() if err != nil { // cleanup what was created so far _ = lbaas.EnsureLoadBalancerDeleted(clusterName, apiService) return nil, err } } err := createNodeSecurityGroup(lbaas.network, lbaas.opts.NodeSecurityGroupID, int(port.NodePort), port.Protocol, lbSecGroup.ID) if err != nil { glog.Errorf("Error occurred creating security group for loadbalancer %s:", loadbalancer.ID) _ = lbaas.EnsureLoadBalancerDeleted(clusterName, apiService) return nil, err } } lbSecGroupRuleCreateOpts := rules.CreateOpts{ Direction: rules.DirIngress, PortRangeMax: 4, // ICMP: Code - Values for ICMP "Destination Unreachable: Fragmentation Needed and Don't Fragment was Set" PortRangeMin: 3, // ICMP: Type Protocol: rules.ProtocolICMP, RemoteIPPrefix: "0.0.0.0/0", // The Fragmentation packet can come from anywhere along the path back to the sourceRange - we need to all this from all SecGroupID: lbSecGroup.ID, EtherType: rules.EtherType4, } _, err = rules.Create(lbaas.network, lbSecGroupRuleCreateOpts).Extract() if err != nil { // cleanup what was created so far _ = lbaas.EnsureLoadBalancerDeleted(clusterName, apiService) return nil, err } lbSecGroupRuleCreateOpts = rules.CreateOpts{ Direction: rules.DirIngress, PortRangeMax: 0, // ICMP: Code - Values for ICMP "Packet Too Big" PortRangeMin: 2, // ICMP: Type Protocol: rules.ProtocolICMP, RemoteIPPrefix: "::/0", // The Fragmentation packet can come from anywhere along the path back to the sourceRange - we need to all this from all SecGroupID: lbSecGroup.ID, EtherType: rules.EtherType6, } _, err = rules.Create(lbaas.network, lbSecGroupRuleCreateOpts).Extract() if err != nil { // cleanup what was created so far _ = lbaas.EnsureLoadBalancerDeleted(clusterName, apiService) return nil, err } portID := loadbalancer.VipPortID newOpts := []string{lbSecGroup.ID} updateOpts := neutronports.UpdateOpts{SecurityGroups: &newOpts} res := neutronports.Update(lbaas.network, portID, updateOpts) if res.Err != nil { glog.Errorf("Error occurred updating port: %s", portID) // cleanup what was created so far _ = lbaas.EnsureLoadBalancerDeleted(clusterName, apiService) return nil, res.Err } } return status, nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go#L947-L1059
go
train
// UpdateLoadBalancer updates the load balancer
func (lbaas *LbaasV2) UpdateLoadBalancer(clusterName string, service *v1.Service, nodes []*v1.Node) error
// UpdateLoadBalancer updates the load balancer func (lbaas *LbaasV2) UpdateLoadBalancer(clusterName string, service *v1.Service, nodes []*v1.Node) error
{ loadBalancerName := cloudprovider.GetLoadBalancerName(service) glog.V(4).Infof("UpdateLoadBalancer(%v, %v, %v)", clusterName, loadBalancerName, nodes) ports := service.Spec.Ports if len(ports) == 0 { return fmt.Errorf("no ports provided to openstack load balancer") } loadbalancer, err := getLoadbalancerByName(lbaas.network, loadBalancerName) if err != nil { return err } if loadbalancer == nil { return fmt.Errorf("Loadbalancer %s does not exist", loadBalancerName) } // Get all listeners for this loadbalancer, by "port key". type portKey struct { Protocol listeners.Protocol Port int } var listenerIDs []string lbListeners := make(map[portKey]listeners.Listener) allListeners, err := getListenersByLoadBalancerID(lbaas.network, loadbalancer.ID) if err != nil { return fmt.Errorf("Error getting listeners for LB %s: %v", loadBalancerName, err) } for _, l := range allListeners { key := portKey{Protocol: listeners.Protocol(l.Protocol), Port: l.ProtocolPort} lbListeners[key] = l listenerIDs = append(listenerIDs, l.ID) } // Get all pools for this loadbalancer, by listener ID. lbPools := make(map[string]v2pools.Pool) for _, listenerID := range listenerIDs { pool, err := getPoolByListenerID(lbaas.network, loadbalancer.ID, listenerID) if err != nil { return fmt.Errorf("Error getting pool for listener %s: %v", listenerID, err) } lbPools[listenerID] = *pool } // Compose Set of member (addresses) that _should_ exist addrs := map[string]empty{} for _, node := range nodes { addr, err := nodeAddressForLB(node) if err != nil { return err } addrs[addr] = empty{} } // Check for adding/removing members associated with each port for _, port := range ports { // Get listener associated with this port listener, ok := lbListeners[portKey{ Protocol: toListenersProtocol(port.Protocol), Port: int(port.Port), }] if !ok { return fmt.Errorf("Loadbalancer %s does not contain required listener for port %d and protocol %s", loadBalancerName, port.Port, port.Protocol) } // Get pool associated with this listener pool, ok := lbPools[listener.ID] if !ok { return fmt.Errorf("Loadbalancer %s does not contain required pool for listener %s", loadBalancerName, listener.ID) } // Find existing pool members (by address) for this port getMembers, err := getMembersByPoolID(lbaas.network, pool.ID) if err != nil { return fmt.Errorf("Error getting pool members %s: %v", pool.ID, err) } members := make(map[string]v2pools.Member) for _, member := range getMembers { members[member.Address] = member } // Add any new members for this port for addr := range addrs { if _, ok := members[addr]; ok && members[addr].ProtocolPort == int(port.NodePort) { // Already exists, do not create member continue } _, err := v2pools.CreateMember(lbaas.network, pool.ID, v2pools.CreateMemberOpts{ Address: addr, ProtocolPort: int(port.NodePort), SubnetID: lbaas.opts.SubnetID, }).Extract() if err != nil { return err } waitLoadbalancerActiveProvisioningStatus(lbaas.network, loadbalancer.ID) } // Remove any old members for this port for _, member := range members { if _, ok := addrs[member.Address]; ok && member.ProtocolPort == int(port.NodePort) { // Still present, do not delete member continue } err = v2pools.DeleteMember(lbaas.network, pool.ID, member.ID).ExtractErr() if err != nil && !isNotFound(err) { return err } waitLoadbalancerActiveProvisioningStatus(lbaas.network, loadbalancer.ID) } } return nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go#L1062-L1198
go
train
// EnsureLoadBalancerDeleted ensures the load balancer is deleted
func (lbaas *LbaasV2) EnsureLoadBalancerDeleted(clusterName string, service *v1.Service) error
// EnsureLoadBalancerDeleted ensures the load balancer is deleted func (lbaas *LbaasV2) EnsureLoadBalancerDeleted(clusterName string, service *v1.Service) error
{ loadBalancerName := cloudprovider.GetLoadBalancerName(service) glog.V(4).Infof("EnsureLoadBalancerDeleted(%v, %v)", clusterName, loadBalancerName) loadbalancer, err := getLoadbalancerByName(lbaas.network, loadBalancerName) if err != nil && err != ErrNotFound { return err } if loadbalancer == nil { return nil } if lbaas.opts.FloatingNetworkID != "" && loadbalancer != nil { portID := loadbalancer.VipPortID floatingIP, addrErr := getFloatingIPByPortID(lbaas.network, portID) if addrErr != nil && addrErr != ErrNotFound { return addrErr } if floatingIP != nil { err = floatingips.Delete(lbaas.network, floatingIP.ID).ExtractErr() if err != nil && !isNotFound(err) { return err } } } // get all listeners associated with this loadbalancer listenerList, err := getListenersByLoadBalancerID(lbaas.network, loadbalancer.ID) if err != nil { return fmt.Errorf("Error getting LB %s listeners: %v", loadbalancer.ID, err) } // get all pools (and health monitors) associated with this loadbalancer var poolIDs []string var monitorIDs []string for _, listener := range listenerList { pool, poolErr := getPoolByListenerID(lbaas.network, loadbalancer.ID, listener.ID) if poolErr != nil && poolErr != ErrNotFound { return fmt.Errorf("Error getting pool for listener %s: %v", listener.ID, poolErr) } poolIDs = append(poolIDs, pool.ID) monitorIDs = append(monitorIDs, pool.MonitorID) } // get all members associated with each poolIDs var memberIDs []string for _, pool := range poolIDs { membersList, poolErr := getMembersByPoolID(lbaas.network, pool) if poolErr != nil && !isNotFound(poolErr) { return fmt.Errorf("Error getting pool members %s: %v", pool, poolErr) } for _, member := range membersList { memberIDs = append(memberIDs, member.ID) } } // delete all monitors for _, monitorID := range monitorIDs { err := v2monitors.Delete(lbaas.network, monitorID).ExtractErr() if err != nil && !isNotFound(err) { return err } waitLoadbalancerActiveProvisioningStatus(lbaas.network, loadbalancer.ID) } // delete all members and pools for _, poolID := range poolIDs { // delete all members for this pool for _, memberID := range memberIDs { err := v2pools.DeleteMember(lbaas.network, poolID, memberID).ExtractErr() if err != nil && !isNotFound(err) { return err } waitLoadbalancerActiveProvisioningStatus(lbaas.network, loadbalancer.ID) } // delete pool err := v2pools.Delete(lbaas.network, poolID).ExtractErr() if err != nil && !isNotFound(err) { return err } waitLoadbalancerActiveProvisioningStatus(lbaas.network, loadbalancer.ID) } // delete all listeners for _, listener := range listenerList { err := listeners.Delete(lbaas.network, listener.ID).ExtractErr() if err != nil && !isNotFound(err) { return err } waitLoadbalancerActiveProvisioningStatus(lbaas.network, loadbalancer.ID) } // delete loadbalancer err = loadbalancers.Delete(lbaas.network, loadbalancer.ID).ExtractErr() if err != nil && !isNotFound(err) { return err } waitLoadbalancerDeleted(lbaas.network, loadbalancer.ID) // Delete the Security Group if lbaas.opts.ManageSecurityGroups { // Generate Name lbSecGroupName := getSecurityGroupName(clusterName, service) lbSecGroupID, err := groups.IDFromName(lbaas.network, lbSecGroupName) if err != nil { glog.V(1).Infof("Error occurred finding security group: %s: %v", lbSecGroupName, err) return nil } lbSecGroup := groups.Delete(lbaas.network, lbSecGroupID) if lbSecGroup.Err != nil && !isNotFound(lbSecGroup.Err) { return lbSecGroup.Err } // Delete the rules in the Node Security Group opts := rules.ListOpts{ SecGroupID: lbaas.opts.NodeSecurityGroupID, RemoteGroupID: lbSecGroupID, } secGroupRules, err := getSecurityGroupRules(lbaas.network, opts) if err != nil && !isNotFound(err) { glog.Errorf("Error finding rules for remote group id %s in security group id %s", lbSecGroupID, lbaas.opts.NodeSecurityGroupID) return err } for _, rule := range secGroupRules { res := rules.Delete(lbaas.network, rule.ID) if res.Err != nil && !isNotFound(res.Err) { glog.V(1).Infof("Error occurred deleting security group rule: %s: %v", rule.ID, res.Err) } } } return nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go#L1201-L1215
go
train
// GetLoadBalancer gets a load balancer
func (lb *LbaasV1) GetLoadBalancer(clusterName string, service *v1.Service) (*v1.LoadBalancerStatus, bool, error)
// GetLoadBalancer gets a load balancer func (lb *LbaasV1) GetLoadBalancer(clusterName string, service *v1.Service) (*v1.LoadBalancerStatus, bool, error)
{ loadBalancerName := cloudprovider.GetLoadBalancerName(service) vip, err := getVipByName(lb.network, loadBalancerName) if err == ErrNotFound { return nil, false, nil } if vip == nil { return nil, false, err } status := &v1.LoadBalancerStatus{} status.Ingress = []v1.LoadBalancerIngress{{IP: vip.Address}} return status, true, err }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go#L1223-L1370
go
train
// TODO: This code currently ignores 'region' and always creates a // loadbalancer in only the current OpenStack region. We should take // a list of regions (from config) and query/create loadbalancers in // each region. // EnsureLoadBalancer ensures the load balancer works well
func (lb *LbaasV1) EnsureLoadBalancer(clusterName string, apiService *v1.Service, nodes []*v1.Node) (*v1.LoadBalancerStatus, error)
// TODO: This code currently ignores 'region' and always creates a // loadbalancer in only the current OpenStack region. We should take // a list of regions (from config) and query/create loadbalancers in // each region. // EnsureLoadBalancer ensures the load balancer works well func (lb *LbaasV1) EnsureLoadBalancer(clusterName string, apiService *v1.Service, nodes []*v1.Node) (*v1.LoadBalancerStatus, error)
{ glog.V(4).Infof("EnsureLoadBalancer(%v, %v, %v, %v, %v, %v, %v)", clusterName, apiService.Namespace, apiService.Name, apiService.Spec.LoadBalancerIP, apiService.Spec.Ports, nodes, apiService.Annotations) ports := apiService.Spec.Ports if len(ports) > 1 { return nil, fmt.Errorf("multiple ports are not supported in openstack v1 load balancers") } else if len(ports) == 0 { return nil, fmt.Errorf("no ports provided to openstack load balancer") } // The service controller verified all the protocols match on the ports, just check and use the first one // TODO: Convert all error messages to use an event recorder if ports[0].Protocol != v1.ProtocolTCP { return nil, fmt.Errorf("Only TCP LoadBalancer is supported for openstack load balancers") } affinity := apiService.Spec.SessionAffinity var persistence *vips.SessionPersistence switch affinity { case v1.ServiceAffinityNone: persistence = nil case v1.ServiceAffinityClientIP: persistence = &vips.SessionPersistence{Type: "SOURCE_IP"} default: return nil, fmt.Errorf("unsupported load balancer affinity: %v", affinity) } sourceRanges, err := service.GetLoadBalancerSourceRanges(apiService) if err != nil { return nil, err } if !service.IsAllowAll(sourceRanges) { return nil, fmt.Errorf("Source range restrictions are not supported for openstack load balancers") } glog.V(2).Infof("Checking if openstack load balancer already exists: %s", cloudprovider.GetLoadBalancerName(apiService)) _, exists, err := lb.GetLoadBalancer(clusterName, apiService) if err != nil { return nil, fmt.Errorf("error checking if openstack load balancer already exists: %v", err) } // TODO: Implement a more efficient update strategy for common changes than delete & create // In particular, if we implement hosts update, we can get rid of UpdateHosts if exists { err := lb.EnsureLoadBalancerDeleted(clusterName, apiService) if err != nil { return nil, fmt.Errorf("error deleting existing openstack load balancer: %v", err) } } lbmethod := pools.LBMethod(lb.opts.LBMethod) if lbmethod == "" { lbmethod = pools.LBMethodRoundRobin } name := cloudprovider.GetLoadBalancerName(apiService) pool, err := pools.Create(lb.network, pools.CreateOpts{ Name: name, Protocol: pools.ProtocolTCP, SubnetID: lb.opts.SubnetID, LBMethod: lbmethod, }).Extract() if err != nil { return nil, err } for _, node := range nodes { addr, err := nodeAddressForLB(node) if err != nil { return nil, err } _, err = members.Create(lb.network, members.CreateOpts{ PoolID: pool.ID, ProtocolPort: int(ports[0].NodePort), //Note: only handles single port Address: addr, }).Extract() if err != nil { pools.Delete(lb.network, pool.ID) return nil, err } } var mon *monitors.Monitor if lb.opts.CreateMonitor { mon, err = monitors.Create(lb.network, monitors.CreateOpts{ Type: monitors.TypeTCP, Delay: int(lb.opts.MonitorDelay.Duration.Seconds()), Timeout: int(lb.opts.MonitorTimeout.Duration.Seconds()), MaxRetries: int(lb.opts.MonitorMaxRetries), }).Extract() if err != nil { pools.Delete(lb.network, pool.ID) return nil, err } _, err = pools.AssociateMonitor(lb.network, pool.ID, mon.ID).Extract() if err != nil { monitors.Delete(lb.network, mon.ID) pools.Delete(lb.network, pool.ID) return nil, err } } createOpts := vips.CreateOpts{ Name: name, Description: fmt.Sprintf("Kubernetes external service %s", name), Protocol: "TCP", ProtocolPort: int(ports[0].Port), //TODO: need to handle multi-port PoolID: pool.ID, SubnetID: lb.opts.SubnetID, Persistence: persistence, } loadBalancerIP := apiService.Spec.LoadBalancerIP if loadBalancerIP != "" { createOpts.Address = loadBalancerIP } vip, err := vips.Create(lb.network, createOpts).Extract() if err != nil { if mon != nil { monitors.Delete(lb.network, mon.ID) } pools.Delete(lb.network, pool.ID) return nil, err } status := &v1.LoadBalancerStatus{} status.Ingress = []v1.LoadBalancerIngress{{IP: vip.Address}} if lb.opts.FloatingNetworkID != "" { floatIPOpts := floatingips.CreateOpts{ FloatingNetworkID: lb.opts.FloatingNetworkID, PortID: vip.PortID, } floatIP, err := floatingips.Create(lb.network, floatIPOpts).Extract() if err != nil { return nil, err } status.Ingress = append(status.Ingress, v1.LoadBalancerIngress{IP: floatIP.FloatingIP}) } return status, nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go#L1373-L1433
go
train
// UpdateLoadBalancer updates the load balancer
func (lb *LbaasV1) UpdateLoadBalancer(clusterName string, service *v1.Service, nodes []*v1.Node) error
// UpdateLoadBalancer updates the load balancer func (lb *LbaasV1) UpdateLoadBalancer(clusterName string, service *v1.Service, nodes []*v1.Node) error
{ loadBalancerName := cloudprovider.GetLoadBalancerName(service) glog.V(4).Infof("UpdateLoadBalancer(%v, %v, %v)", clusterName, loadBalancerName, nodes) vip, err := getVipByName(lb.network, loadBalancerName) if err != nil { return err } // Set of member (addresses) that _should_ exist addrs := map[string]bool{} for _, node := range nodes { addr, addrErr := nodeAddressForLB(node) if addrErr != nil { return addrErr } addrs[addr] = true } // Iterate over members that _do_ exist pager := members.List(lb.network, members.ListOpts{PoolID: vip.PoolID}) err = pager.EachPage(func(page pagination.Page) (bool, error) { memList, err := members.ExtractMembers(page) if err != nil { return false, err } for _, member := range memList { if _, found := addrs[member.Address]; found { // Member already exists delete(addrs, member.Address) } else { // Member needs to be deleted err = members.Delete(lb.network, member.ID).ExtractErr() if err != nil { return false, err } } } return true, nil }) if err != nil { return err } // Anything left in addrs is a new member that needs to be added for addr := range addrs { _, err := members.Create(lb.network, members.CreateOpts{ PoolID: vip.PoolID, Address: addr, ProtocolPort: vip.ProtocolPort, }).Extract() if err != nil { return err } } return nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go#L1436-L1509
go
train
// EnsureLoadBalancerDeleted ensures the load balancer is deleted
func (lb *LbaasV1) EnsureLoadBalancerDeleted(clusterName string, service *v1.Service) error
// EnsureLoadBalancerDeleted ensures the load balancer is deleted func (lb *LbaasV1) EnsureLoadBalancerDeleted(clusterName string, service *v1.Service) error
{ loadBalancerName := cloudprovider.GetLoadBalancerName(service) glog.V(4).Infof("EnsureLoadBalancerDeleted(%v, %v)", clusterName, loadBalancerName) vip, err := getVipByName(lb.network, loadBalancerName) if err != nil && err != ErrNotFound { return err } if lb.opts.FloatingNetworkID != "" && vip != nil { floatingIP, addrErr := getFloatingIPByPortID(lb.network, vip.PortID) if addrErr != nil && !isNotFound(addrErr) { return addrErr } if floatingIP != nil { err = floatingips.Delete(lb.network, floatingIP.ID).ExtractErr() if err != nil && !isNotFound(err) { return err } } } // We have to delete the VIP before the pool can be deleted, // so no point continuing if this fails. if vip != nil { err := vips.Delete(lb.network, vip.ID).ExtractErr() if err != nil && !isNotFound(err) { return err } } var pool *pools.Pool if vip != nil { pool, err = pools.Get(lb.network, vip.PoolID).Extract() if err != nil && !isNotFound(err) { return err } } else { // The VIP is gone, but it is conceivable that a Pool // still exists that we failed to delete on some // previous occasion. Make a best effort attempt to // cleanup any pools with the same name as the VIP. pool, err = getPoolByName(lb.network, service.Name) if err != nil && err != ErrNotFound { return err } } if pool != nil { for _, monID := range pool.MonitorIDs { _, err = pools.DisassociateMonitor(lb.network, pool.ID, monID).Extract() if err != nil { return err } err = monitors.Delete(lb.network, monID).ExtractErr() if err != nil && !isNotFound(err) { return err } } for _, memberID := range pool.MemberIDs { err = members.Delete(lb.network, memberID).ExtractErr() if err != nil && !isNotFound(err) { return err } } err = pools.Delete(lb.network, pool.ID).ExtractErr() if err != nil && !isNotFound(err) { return err } } return nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
openebs/pkg/v1/maya_api.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/openebs/pkg/v1/maya_api.go#L55-L74
go
train
//GetMayaClusterIP returns maya-apiserver IP address
func (v OpenEBSVolume) GetMayaClusterIP(client kubernetes.Interface) (string, error)
//GetMayaClusterIP returns maya-apiserver IP address func (v OpenEBSVolume) GetMayaClusterIP(client kubernetes.Interface) (string, error)
{ clusterIP := "127.0.0.1" namespace := os.Getenv("OPENEBS_NAMESPACE") if namespace == "" { namespace = "default" } glog.Info("OpenEBS volume provisioner namespace ", namespace) //Fetch the Maya ClusterIP using the Maya API Server Service sc, err := client.CoreV1().Services(namespace).Get("maya-apiserver-service", metav1.GetOptions{}) if err != nil { glog.Errorf("Error getting maya-apiserver IP Address: %v", err) } clusterIP = sc.Spec.ClusterIP glog.V(2).Infof("Maya Cluster IP: %v", clusterIP) return clusterIP, err }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
openebs/pkg/v1/maya_api.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/openebs/pkg/v1/maya_api.go#L77-L123
go
train
// CreateVolume to create the Vsm through a API call to m-apiserver
func (v OpenEBSVolume) CreateVolume(vs mayav1.VolumeSpec) (string, error)
// CreateVolume to create the Vsm through a API call to m-apiserver func (v OpenEBSVolume) CreateVolume(vs mayav1.VolumeSpec) (string, error)
{ addr := os.Getenv("MAPI_ADDR") if addr == "" { err := errors.New("MAPI_ADDR environment variable not set") glog.Errorf("Error getting maya-apiserver IP Address: %v", err) return "Error getting maya-apiserver IP Address", err } url := addr + "/latest/volumes/" vs.Kind = "PersistentVolumeClaim" vs.APIVersion = "v1" //Marshal serializes the value provided into a YAML document yamlValue, _ := yaml.Marshal(vs) glog.V(2).Infof("[DEBUG] volume Spec Created:\n%v\n", string(yamlValue)) req, err := http.NewRequest("POST", url, bytes.NewBuffer(yamlValue)) req.Header.Add("Content-Type", "application/yaml") c := &http.Client{ Timeout: timeout, } resp, err := c.Do(req) if err != nil { glog.Errorf("Error when connecting maya-apiserver %v", err) return "Could not connect to maya-apiserver", err } defer resp.Body.Close() data, err := ioutil.ReadAll(resp.Body) if err != nil { glog.Errorf("Unable to read response from maya-apiserver %v", err) return "Unable to read response from maya-apiserver", err } code := resp.StatusCode if code != http.StatusOK { glog.Errorf("Status error: %v\n", http.StatusText(code)) return "HTTP Status error from maya-apiserver", err } glog.Infof("volume Successfully Created:\n%v\n", string(data)) return "volume Successfully Created", nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
openebs/pkg/v1/maya_api.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/openebs/pkg/v1/maya_api.go#L126-L156
go
train
// ListVolume to get the info of Vsm through a API call to m-apiserver
func (v OpenEBSVolume) ListVolume(vname string, obj interface{}) error
// ListVolume to get the info of Vsm through a API call to m-apiserver func (v OpenEBSVolume) ListVolume(vname string, obj interface{}) error
{ addr := os.Getenv("MAPI_ADDR") if addr == "" { err := errors.New("MAPI_ADDR environment variable not set") glog.Errorf("Error getting mayaapi-server IP Address: %v", err) return err } url := addr + "/latest/volumes/info/" + vname glog.V(2).Infof("[DEBUG] Get details for Volume :%v", string(vname)) req, err := http.NewRequest("GET", url, nil) c := &http.Client{ Timeout: timeout, } resp, err := c.Do(req) if err != nil { glog.Errorf("Error when connecting to maya-apiserver %v", err) return err } defer resp.Body.Close() code := resp.StatusCode if code != http.StatusOK { glog.Errorf("HTTP Status error from maya-apiserver: %v\n", http.StatusText(code)) return err } glog.V(2).Info("volume Details Successfully Retrieved") return json.NewDecoder(resp.Body).Decode(obj) }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
ceph/cephfs/cephfs-provisioner.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/ceph/cephfs/cephfs-provisioner.go#L96-L115
go
train
// getSecretFromCephFSPersistentVolume gets secret reference from CephFS PersistentVolume. // It fallbacks to use ClaimRef.Namespace if SecretRef.Namespace is // empty. See https://github.com/kubernetes/kubernetes/pull/49502.
func getSecretFromCephFSPersistentVolume(pv *v1.PersistentVolume) (*v1.SecretReference, error)
// getSecretFromCephFSPersistentVolume gets secret reference from CephFS PersistentVolume. // It fallbacks to use ClaimRef.Namespace if SecretRef.Namespace is // empty. See https://github.com/kubernetes/kubernetes/pull/49502. func getSecretFromCephFSPersistentVolume(pv *v1.PersistentVolume) (*v1.SecretReference, error)
{ source := &pv.Spec.PersistentVolumeSource if source.CephFS == nil { return nil, errors.New("pv.Spec.PersistentVolumeSource.CephFS is nil") } if source.CephFS.SecretRef == nil { return nil, errors.New("pv.Spec.PersistentVolumeSource.CephFS.SecretRef is nil") } if len(source.CephFS.SecretRef.Namespace) > 0 { return source.CephFS.SecretRef, nil } ns := getClaimRefNamespace(pv) if len(ns) <= 0 { return nil, errors.New("both pv.Spec.SecretRef.Namespace and pv.Spec.ClaimRef.Namespace are empty") } return &v1.SecretReference{ Name: source.CephFS.SecretRef.Name, Namespace: ns, }, nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
ceph/cephfs/cephfs-provisioner.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/ceph/cephfs/cephfs-provisioner.go#L118-L228
go
train
// Provision creates a storage asset and returns a PV object representing it.
func (p *cephFSProvisioner) Provision(options controller.VolumeOptions) (*v1.PersistentVolume, error)
// Provision creates a storage asset and returns a PV object representing it. func (p *cephFSProvisioner) Provision(options controller.VolumeOptions) (*v1.PersistentVolume, error)
{ if options.PVC.Spec.Selector != nil { return nil, fmt.Errorf("claim Selector is not supported") } cluster, adminID, adminSecret, pvcRoot, mon, deterministicNames, err := p.parseParameters(options.Parameters) if err != nil { return nil, err } var share, user string if deterministicNames { share = options.PVC.Name user = fmt.Sprintf("k8s.%s.%s", options.PVC.Namespace, options.PVC.Name) } else { // create random share name share = fmt.Sprintf("kubernetes-dynamic-pvc-%s", uuid.NewUUID()) // create random user id user = fmt.Sprintf("kubernetes-dynamic-user-%s", uuid.NewUUID()) } // provision share // create cmd args := []string{"-n", share, "-u", user} if p.enableQuota { capacity := options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)] requestBytes := strconv.FormatInt(capacity.Value(), 10) args = append(args, "-s", requestBytes) } cmd := exec.Command(provisionCmd, args...) // set env cmd.Env = []string{ "CEPH_CLUSTER_NAME=" + cluster, "CEPH_MON=" + strings.Join(mon[:], ","), "CEPH_AUTH_ID=" + adminID, "CEPH_AUTH_KEY=" + adminSecret, "CEPH_VOLUME_ROOT=" + pvcRoot} if deterministicNames { cmd.Env = append(cmd.Env, "CEPH_VOLUME_GROUP="+options.PVC.Namespace) } if *disableCephNamespaceIsolation { cmd.Env = append(cmd.Env, "CEPH_NAMESPACE_ISOLATION_DISABLED=true") } output, cmdErr := cmd.CombinedOutput() if cmdErr != nil { klog.Errorf("failed to provision share %q for %q, err: %v, output: %v", share, user, cmdErr, string(output)) return nil, cmdErr } // validate output res := &provisionOutput{} json.Unmarshal([]byte(output), &res) if res.User == "" || res.Secret == "" || res.Path == "" { return nil, fmt.Errorf("invalid provisioner output") } nameSpace := p.secretNamespace if nameSpace == "" { // if empty, create secret in PVC's namespace nameSpace = options.PVC.Namespace } secretName := generateSecretName(user) secret := &v1.Secret{ ObjectMeta: metav1.ObjectMeta{ Namespace: nameSpace, Name: secretName, }, Data: map[string][]byte{ "key": []byte(res.Secret), }, Type: "Opaque", } _, err = p.client.CoreV1().Secrets(nameSpace).Create(secret) if err != nil { klog.Errorf("Cephfs Provisioner: create volume failed, err: %v", err) return nil, fmt.Errorf("failed to create secret") } pv := &v1.PersistentVolume{ ObjectMeta: metav1.ObjectMeta{ Name: options.PVName, Annotations: map[string]string{ provisionerIDAnn: p.identity, cephShareAnn: share, }, }, Spec: v1.PersistentVolumeSpec{ PersistentVolumeReclaimPolicy: options.PersistentVolumeReclaimPolicy, AccessModes: options.PVC.Spec.AccessModes, MountOptions: options.MountOptions, Capacity: v1.ResourceList{ // Quotas are supported by the userspace client(ceph-fuse, libcephfs), or kernel client >= 4.17 but only on mimic clusters. // In other cases capacity is meaningless here. // If quota is enabled, provisioner will set ceph.quota.max_bytes on volume path. v1.ResourceName(v1.ResourceStorage): options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)], }, PersistentVolumeSource: v1.PersistentVolumeSource{ CephFS: &v1.CephFSPersistentVolumeSource{ Monitors: mon, Path: res.Path[strings.Index(res.Path, "/"):], SecretRef: &v1.SecretReference{ Name: secretName, Namespace: nameSpace, }, User: user, }, }, }, } klog.Infof("successfully created CephFS share %+v", pv.Spec.PersistentVolumeSource.CephFS) return pv, nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
ceph/cephfs/cephfs-provisioner.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/ceph/cephfs/cephfs-provisioner.go#L232-L288
go
train
// Delete removes the storage asset that was created by Provision represented // by the given PV.
func (p *cephFSProvisioner) Delete(volume *v1.PersistentVolume) error
// Delete removes the storage asset that was created by Provision represented // by the given PV. func (p *cephFSProvisioner) Delete(volume *v1.PersistentVolume) error
{ ann, ok := volume.Annotations[provisionerIDAnn] if !ok { return errors.New("identity annotation not found on PV") } if ann != p.identity { return &controller.IgnoredError{Reason: "identity annotation on PV does not match ours"} } share, ok := volume.Annotations[cephShareAnn] if !ok { return errors.New("ceph share annotation not found on PV") } // delete CephFS // TODO when beta is removed, have to check kube version and pick v1/beta // accordingly: maybe the controller lib should offer a function for that class, err := p.client.StorageV1beta1().StorageClasses().Get(util.GetPersistentVolumeClass(volume), metav1.GetOptions{}) if err != nil { return err } cluster, adminID, adminSecret, pvcRoot, mon, _, err := p.parseParameters(class.Parameters) if err != nil { return err } user := volume.Spec.PersistentVolumeSource.CephFS.User // create cmd cmd := exec.Command(provisionCmd, "-r", "-n", share, "-u", user) // set env cmd.Env = []string{ "CEPH_CLUSTER_NAME=" + cluster, "CEPH_MON=" + strings.Join(mon[:], ","), "CEPH_AUTH_ID=" + adminID, "CEPH_AUTH_KEY=" + adminSecret, "CEPH_VOLUME_ROOT=" + pvcRoot} if *disableCephNamespaceIsolation { cmd.Env = append(cmd.Env, "CEPH_NAMESPACE_ISOLATION_DISABLED=true") } output, cmdErr := cmd.CombinedOutput() if cmdErr != nil { klog.Errorf("failed to delete share %q for %q, err: %v, output: %v", share, user, cmdErr, string(output)) return cmdErr } // Remove dynamic user secret secretRef, err := getSecretFromCephFSPersistentVolume(volume) if err != nil { klog.Errorf("failed to get secret references, err: %v", err) return err } err = p.client.CoreV1().Secrets(secretRef.Namespace).Delete(secretRef.Name, &metav1.DeleteOptions{}) if err != nil { klog.Errorf("Cephfs Provisioner: delete secret failed, err: %v", err) return fmt.Errorf("failed to delete secret") } return nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
aws/efs/cmd/efs-provisioner/efs-provisioner.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/aws/efs/cmd/efs-provisioner/efs-provisioner.go#L57-L100
go
train
// NewEFSProvisioner creates an AWS EFS volume provisioner
func NewEFSProvisioner(client kubernetes.Interface) controller.Provisioner
// NewEFSProvisioner creates an AWS EFS volume provisioner func NewEFSProvisioner(client kubernetes.Interface) controller.Provisioner
{ fileSystemID := os.Getenv(fileSystemIDKey) if fileSystemID == "" { klog.Fatalf("environment variable %s is not set! Please set it.", fileSystemIDKey) } awsRegion := os.Getenv(awsRegionKey) if awsRegion == "" { klog.Fatalf("environment variable %s is not set! Please set it.", awsRegionKey) } dnsName := os.Getenv(dnsNameKey) klog.Errorf("%v", dnsName) if dnsName == "" { dnsName = getDNSName(fileSystemID, awsRegion) } mountpoint, source, err := getMount(dnsName) if err != nil { klog.Fatal(err) } sess, err := session.NewSession() if err != nil { klog.Warningf("couldn't create an AWS session: %v", err) } svc := efs.New(sess, &aws.Config{Region: aws.String(awsRegion)}) params := &efs.DescribeFileSystemsInput{ FileSystemId: aws.String(fileSystemID), } _, err = svc.DescribeFileSystems(params) if err != nil { klog.Warningf("couldn't confirm that the EFS file system exists: %v", err) } return &efsProvisioner{ dnsName: dnsName, mountpoint: mountpoint, source: source, allocator: gidallocator.New(client), } }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
aws/efs/cmd/efs-provisioner/efs-provisioner.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/aws/efs/cmd/efs-provisioner/efs-provisioner.go#L127-L195
go
train
// Provision creates a storage asset and returns a PV object representing it.
func (p *efsProvisioner) Provision(options controller.VolumeOptions) (*v1.PersistentVolume, error)
// Provision creates a storage asset and returns a PV object representing it. func (p *efsProvisioner) Provision(options controller.VolumeOptions) (*v1.PersistentVolume, error)
{ if options.PVC.Spec.Selector != nil { return nil, fmt.Errorf("claim.Spec.Selector is not supported") } gidAllocate := true for k, v := range options.Parameters { switch strings.ToLower(k) { case "gidmin": // Let allocator handle case "gidmax": // Let allocator handle case "gidallocate": b, err := strconv.ParseBool(v) if err != nil { return nil, fmt.Errorf("invalid value %s for parameter %s: %v", v, k, err) } gidAllocate = b } } var gid *int if gidAllocate { allocate, err := p.allocator.AllocateNext(options) if err != nil { return nil, err } gid = &allocate } err := p.createVolume(p.getLocalPath(options), gid) if err != nil { return nil, err } mountOptions := []string{"vers=4.1"} if options.MountOptions != nil { mountOptions = options.MountOptions } pv := &v1.PersistentVolume{ ObjectMeta: metav1.ObjectMeta{ Name: options.PVName, }, Spec: v1.PersistentVolumeSpec{ PersistentVolumeReclaimPolicy: options.PersistentVolumeReclaimPolicy, AccessModes: options.PVC.Spec.AccessModes, Capacity: v1.ResourceList{ v1.ResourceName(v1.ResourceStorage): options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)], }, PersistentVolumeSource: v1.PersistentVolumeSource{ NFS: &v1.NFSVolumeSource{ Server: p.dnsName, Path: p.getRemotePath(options), ReadOnly: false, }, }, MountOptions: mountOptions, }, } if gidAllocate { pv.ObjectMeta.Annotations = map[string]string{ gidallocator.VolumeGidAnnotationKey: strconv.FormatInt(int64(*gid), 10), } } return pv, nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
aws/efs/cmd/efs-provisioner/efs-provisioner.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/aws/efs/cmd/efs-provisioner/efs-provisioner.go#L240-L257
go
train
// Delete removes the storage asset that was created by Provision represented // by the given PV.
func (p *efsProvisioner) Delete(volume *v1.PersistentVolume) error
// Delete removes the storage asset that was created by Provision represented // by the given PV. func (p *efsProvisioner) Delete(volume *v1.PersistentVolume) error
{ //TODO ignorederror err := p.allocator.Release(volume) if err != nil { return err } path, err := p.getLocalPathToDelete(volume.Spec.NFS) if err != nil { return err } if err := os.RemoveAll(path); err != nil { return err } return nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
local-volume/provisioner/pkg/util/api_util.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/api_util.go#L60-L69
go
train
// CreatePV will create a PersistentVolume
func (u *apiUtil) CreatePV(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)
// CreatePV will create a PersistentVolume func (u *apiUtil) CreatePV(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)
{ startTime := time.Now() metrics.APIServerRequestsTotal.WithLabelValues(metrics.APIServerRequestCreate).Inc() pv, err := u.client.CoreV1().PersistentVolumes().Create(pv) metrics.APIServerRequestsDurationSeconds.WithLabelValues(metrics.APIServerRequestCreate).Observe(time.Since(startTime).Seconds()) if err != nil { metrics.APIServerRequestsFailedTotal.WithLabelValues(metrics.APIServerRequestCreate).Inc() } return pv, err }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
local-volume/provisioner/pkg/util/api_util.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/api_util.go#L72-L81
go
train
// DeletePV will delete a PersistentVolume
func (u *apiUtil) DeletePV(pvName string) error
// DeletePV will delete a PersistentVolume func (u *apiUtil) DeletePV(pvName string) error
{ startTime := time.Now() metrics.APIServerRequestsTotal.WithLabelValues(metrics.APIServerRequestDelete).Inc() err := u.client.CoreV1().PersistentVolumes().Delete(pvName, &metav1.DeleteOptions{}) metrics.APIServerRequestsDurationSeconds.WithLabelValues(metrics.APIServerRequestDelete).Observe(time.Since(startTime).Seconds()) if err != nil { metrics.APIServerRequestsFailedTotal.WithLabelValues(metrics.APIServerRequestDelete).Inc() } return err }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
local-volume/provisioner/pkg/util/api_util.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/api_util.go#L113-L122
go
train
// NewFakeAPIUtil returns an APIUtil object that can be used for unit testing
func NewFakeAPIUtil(shouldFail bool, cache *cache.VolumeCache) *FakeAPIUtil
// NewFakeAPIUtil returns an APIUtil object that can be used for unit testing func NewFakeAPIUtil(shouldFail bool, cache *cache.VolumeCache) *FakeAPIUtil
{ return &FakeAPIUtil{ createdPVs: map[string]*v1.PersistentVolume{}, deletedPVs: map[string]*v1.PersistentVolume{}, CreatedJobs: map[string]*batch_v1.Job{}, DeletedJobs: map[string]string{}, shouldFail: shouldFail, cache: cache, } }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
local-volume/provisioner/pkg/util/api_util.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/api_util.go#L125-L133
go
train
// CreatePV will add the PV to the created list and cache
func (u *FakeAPIUtil) CreatePV(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)
// CreatePV will add the PV to the created list and cache func (u *FakeAPIUtil) CreatePV(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)
{ if u.shouldFail { return nil, fmt.Errorf("API failed") } u.createdPVs[pv.Name] = pv u.cache.AddPV(pv) return pv, nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
local-volume/provisioner/pkg/util/api_util.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/api_util.go#L136-L149
go
train
// DeletePV will delete the PV from the created list and cache, and also add it to the deleted list
func (u *FakeAPIUtil) DeletePV(pvName string) error
// DeletePV will delete the PV from the created list and cache, and also add it to the deleted list func (u *FakeAPIUtil) DeletePV(pvName string) error
{ if u.shouldFail { return fmt.Errorf("API failed") } pv, exists := u.cache.GetPV(pvName) if exists { u.deletedPVs[pvName] = pv delete(u.createdPVs, pvName) u.cache.DeletePV(pvName) return nil } return errors.NewNotFound(v1.Resource("persistentvolumes"), pvName) }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
local-volume/provisioner/pkg/util/api_util.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/api_util.go#L153-L157
go
train
// GetAndResetCreatedPVs returns createdPVs and resets the map // This is only for testing
func (u *FakeAPIUtil) GetAndResetCreatedPVs() map[string]*v1.PersistentVolume
// GetAndResetCreatedPVs returns createdPVs and resets the map // This is only for testing func (u *FakeAPIUtil) GetAndResetCreatedPVs() map[string]*v1.PersistentVolume
{ createdPVs := u.createdPVs u.createdPVs = map[string]*v1.PersistentVolume{} return createdPVs }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
local-volume/provisioner/pkg/util/api_util.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/api_util.go#L161-L165
go
train
// GetAndResetDeletedPVs returns createdPVs and resets the map // This is only for testing
func (u *FakeAPIUtil) GetAndResetDeletedPVs() map[string]*v1.PersistentVolume
// GetAndResetDeletedPVs returns createdPVs and resets the map // This is only for testing func (u *FakeAPIUtil) GetAndResetDeletedPVs() map[string]*v1.PersistentVolume
{ deletedPVs := u.deletedPVs u.deletedPVs = map[string]*v1.PersistentVolume{} return deletedPVs }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
local-volume/provisioner/pkg/util/api_util.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/api_util.go#L168-L171
go
train
// CreateJob mocks job create method.
func (u *FakeAPIUtil) CreateJob(job *batch_v1.Job) error
// CreateJob mocks job create method. func (u *FakeAPIUtil) CreateJob(job *batch_v1.Job) error
{ u.CreatedJobs[job.Namespace+"/"+job.Name] = job return nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
local-volume/provisioner/pkg/util/api_util.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/api_util.go#L174-L177
go
train
// DeleteJob mocks delete jon method.
func (u *FakeAPIUtil) DeleteJob(jobName string, namespace string) error
// DeleteJob mocks delete jon method. func (u *FakeAPIUtil) DeleteJob(jobName string, namespace string) error
{ u.DeletedJobs[namespace+"/"+jobName] = jobName return nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/aws/aws.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L559-L564
go
train
// stringPointerArray creates a slice of string pointers from a slice of strings // Deprecated: consider using aws.StringSlice - but note the slightly different behaviour with a nil input
func stringPointerArray(orig []string) []*string
// stringPointerArray creates a slice of string pointers from a slice of strings // Deprecated: consider using aws.StringSlice - but note the slightly different behaviour with a nil input func stringPointerArray(orig []string) []*string
{ if orig == nil { return nil } return aws.StringSlice(orig) }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/aws/aws.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L589-L591
go
train
// AddSSHKeyToAllInstances is currently not implemented.
func (c *Cloud) AddSSHKeyToAllInstances(user string, keyData []byte) error
// AddSSHKeyToAllInstances is currently not implemented. func (c *Cloud) AddSSHKeyToAllInstances(user string, keyData []byte) error
{ return errors.New("unimplemented") }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/aws/aws.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L594-L596
go
train
// CurrentNodeName returns the name of the current node
func (c *Cloud) CurrentNodeName(hostname string) (types.NodeName, error)
// CurrentNodeName returns the name of the current node func (c *Cloud) CurrentNodeName(hostname string) (types.NodeName, error)
{ return c.selfAWSInstance.nodeName, nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/aws/aws.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L599-L622
go
train
// Implementation of EC2.Instances
func (s *awsSdkEC2) DescribeInstances(request *ec2.DescribeInstancesInput) ([]*ec2.Instance, error)
// Implementation of EC2.Instances func (s *awsSdkEC2) DescribeInstances(request *ec2.DescribeInstancesInput) ([]*ec2.Instance, error)
{ // Instances are paged results := []*ec2.Instance{} var nextToken *string for { response, err := s.ec2.DescribeInstances(request) if err != nil { return nil, fmt.Errorf("error listing AWS instances: %v", err) } for _, reservation := range response.Reservations { results = append(results, reservation.Instances...) } nextToken = response.NextToken if isNilOrEmpty(nextToken) { break } request.NextToken = nextToken } return results, nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/aws/aws.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L773-L798
go
train
// readAWSCloudConfig reads an instance of AWSCloudConfig from config reader.
func readAWSCloudConfig(config io.Reader, metadata EC2Metadata) (*CloudConfig, error)
// readAWSCloudConfig reads an instance of AWSCloudConfig from config reader. func readAWSCloudConfig(config io.Reader, metadata EC2Metadata) (*CloudConfig, error)
{ var cfg CloudConfig var err error if config != nil { err = gcfg.ReadInto(&cfg, config) if err != nil { return nil, err } } if cfg.Global.Zone == "" { if metadata != nil { glog.Info("Zone not specified in configuration file; querying AWS metadata service") cfg.Global.Zone, err = getAvailabilityZone(metadata) if err != nil { return nil, err } } if cfg.Global.Zone == "" { return nil, fmt.Errorf("no zone specified in configuration file") } } return &cfg, nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/aws/aws.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L820-L926
go
train
// newAWSCloud creates a new instance of AWSCloud. // AWSProvider and instanceId are primarily for tests
func newAWSCloud(config io.Reader, awsServices Services) (*Cloud, error)
// newAWSCloud creates a new instance of AWSCloud. // AWSProvider and instanceId are primarily for tests func newAWSCloud(config io.Reader, awsServices Services) (*Cloud, error)
{ // We have some state in the Cloud object - in particular the attaching map // Log so that if we are building multiple Cloud objects, it is obvious! glog.Infof("Building AWS cloudprovider") metadata, err := awsServices.Metadata() if err != nil { return nil, fmt.Errorf("error creating AWS metadata client: %v", err) } cfg, err := readAWSCloudConfig(config, metadata) if err != nil { return nil, fmt.Errorf("unable to read AWS cloud provider config file: %v", err) } zone := cfg.Global.Zone if len(zone) <= 1 { return nil, fmt.Errorf("invalid AWS zone in config file: %s", zone) } regionName, err := azToRegion(zone) if err != nil { return nil, err } // Trust that if we get a region from configuration or AWS metadata that it is valid, // and register ECR providers RecognizeRegion(regionName) if !cfg.Global.DisableStrictZoneCheck { valid := isRegionValid(regionName) if !valid { // This _should_ now be unreachable, given we call RecognizeRegion return nil, fmt.Errorf("not a valid AWS zone (unknown region): %s", zone) } } else { glog.Warningf("Strict AWS zone checking is disabled. Proceeding with zone: %s", zone) } ec2, err := awsServices.Compute(regionName) if err != nil { return nil, fmt.Errorf("error creating AWS EC2 client: %v", err) } elb, err := awsServices.LoadBalancing(regionName) if err != nil { return nil, fmt.Errorf("error creating AWS ELB client: %v", err) } asg, err := awsServices.Autoscaling(regionName) if err != nil { return nil, fmt.Errorf("error creating AWS autoscaling client: %v", err) } awsCloud := &Cloud{ ec2: ec2, elb: elb, asg: asg, metadata: metadata, cfg: cfg, region: regionName, attaching: make(map[types.NodeName]map[mountDevice]awsVolumeID), deviceAllocators: make(map[types.NodeName]DeviceAllocator), } if cfg.Global.VPC != "" && cfg.Global.SubnetID != "" && (cfg.Global.KubernetesClusterTag != "" || cfg.Global.KubernetesClusterID != "") { // When the master is running on a different AWS account, cloud provider or on-premise // build up a dummy instance and use the VPC from the nodes account glog.Info("Master is configured to run on a different AWS account, different cloud provider or on-premise") awsCloud.selfAWSInstance = &awsInstance{ nodeName: "master-dummy", vpcID: cfg.Global.VPC, subnetID: cfg.Global.SubnetID, } awsCloud.vpcID = cfg.Global.VPC } else { selfAWSInstance, err := awsCloud.buildSelfAWSInstance() if err != nil { return nil, err } awsCloud.selfAWSInstance = selfAWSInstance awsCloud.vpcID = selfAWSInstance.vpcID } if cfg.Global.KubernetesClusterTag != "" || cfg.Global.KubernetesClusterID != "" { if err := awsCloud.tagging.init(cfg.Global.KubernetesClusterTag, cfg.Global.KubernetesClusterID); err != nil { return nil, err } } else { // TODO: Clean up double-API query info, err := awsCloud.selfAWSInstance.describeInstance() if err != nil { return nil, err } if err := awsCloud.tagging.initFromTags(info.Tags); err != nil { return nil, err } } // Register regions, in particular for ECR credentials once.Do(func() { RecognizeWellKnownRegions() }) return awsCloud, nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/aws/aws.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L939-L941
go
train
// ScrubDNS filters DNS settings for pods.
func (c *Cloud) ScrubDNS(nameservers, searches []string) (nsOut, srchOut []string)
// ScrubDNS filters DNS settings for pods. func (c *Cloud) ScrubDNS(nameservers, searches []string) (nsOut, srchOut []string)
{ return nameservers, searches }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/aws/aws.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L964-L1038
go
train
// NodeAddresses is an implementation of Instances.NodeAddresses.
func (c *Cloud) NodeAddresses(name types.NodeName) ([]v1.NodeAddress, error)
// NodeAddresses is an implementation of Instances.NodeAddresses. func (c *Cloud) NodeAddresses(name types.NodeName) ([]v1.NodeAddress, error)
{ if c.selfAWSInstance.nodeName == name || len(name) == 0 { addresses := []v1.NodeAddress{} internalIP, err := c.metadata.GetMetadata("local-ipv4") if err != nil { return nil, err } addresses = append(addresses, v1.NodeAddress{Type: v1.NodeInternalIP, Address: internalIP}) externalIP, err := c.metadata.GetMetadata("public-ipv4") if err != nil { //TODO: It would be nice to be able to determine the reason for the failure, // but the AWS client masks all failures with the same error description. glog.V(4).Info("Could not determine public IP from AWS metadata.") } else { addresses = append(addresses, v1.NodeAddress{Type: v1.NodeExternalIP, Address: externalIP}) } internalDNS, err := c.metadata.GetMetadata("local-hostname") if err != nil || len(internalDNS) == 0 { //TODO: It would be nice to be able to determine the reason for the failure, // but the AWS client masks all failures with the same error description. glog.V(2).Info("Could not determine private DNS from AWS metadata.") } else { addresses = append(addresses, v1.NodeAddress{Type: v1.NodeInternalDNS, Address: internalDNS}) } externalDNS, err := c.metadata.GetMetadata("public-hostname") if err != nil || len(externalDNS) == 0 { //TODO: It would be nice to be able to determine the reason for the failure, // but the AWS client masks all failures with the same error description. glog.V(2).Info("Could not determine public DNS from AWS metadata.") } else { addresses = append(addresses, v1.NodeAddress{Type: v1.NodeExternalDNS, Address: externalDNS}) } return addresses, nil } instance, err := c.getInstanceByNodeName(name) if err != nil { return nil, fmt.Errorf("getInstanceByNodeName failed for %q with %v", name, err) } addresses := []v1.NodeAddress{} if !isNilOrEmpty(instance.PrivateIpAddress) { ipAddress := *instance.PrivateIpAddress ip := net.ParseIP(ipAddress) if ip == nil { return nil, fmt.Errorf("EC2 instance had invalid private address: %s (%s)", orEmpty(instance.InstanceId), ipAddress) } addresses = append(addresses, v1.NodeAddress{Type: v1.NodeInternalIP, Address: ip.String()}) } // TODO: Other IP addresses (multiple ips)? if !isNilOrEmpty(instance.PublicIpAddress) { ipAddress := *instance.PublicIpAddress ip := net.ParseIP(ipAddress) if ip == nil { return nil, fmt.Errorf("EC2 instance had invalid public address: %s (%s)", orEmpty(instance.InstanceId), ipAddress) } addresses = append(addresses, v1.NodeAddress{Type: v1.NodeExternalIP, Address: ip.String()}) } if !isNilOrEmpty(instance.PrivateDnsName) { addresses = append(addresses, v1.NodeAddress{Type: v1.NodeInternalDNS, Address: *instance.PrivateDnsName}) } if !isNilOrEmpty(instance.PublicDnsName) { addresses = append(addresses, v1.NodeAddress{Type: v1.NodeExternalDNS, Address: *instance.PublicDnsName}) } return addresses, nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/aws/aws.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L1041-L1056
go
train
// ExternalID returns the cloud provider ID of the node with the specified nodeName (deprecated).
func (c *Cloud) ExternalID(nodeName types.NodeName) (string, error)
// ExternalID returns the cloud provider ID of the node with the specified nodeName (deprecated). func (c *Cloud) ExternalID(nodeName types.NodeName) (string, error)
{ if c.selfAWSInstance.nodeName == nodeName { // We assume that if this is run on the instance itself, the instance exists and is alive return c.selfAWSInstance.awsID, nil } // We must verify that the instance still exists // Note that if the instance does not exist or is no longer running, we must return ("", cloudprovider.InstanceNotFound) instance, err := c.findInstanceByNodeName(nodeName) if err != nil { return "", err } if instance == nil { return "", cloudprovider.ErrInstanceNotFound } return orEmpty(instance.InstanceId), nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/aws/aws.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L1059-L1070
go
train
// InstanceID returns the cloud provider ID of the node with the specified nodeName.
func (c *Cloud) InstanceID(nodeName types.NodeName) (string, error)
// InstanceID returns the cloud provider ID of the node with the specified nodeName. func (c *Cloud) InstanceID(nodeName types.NodeName) (string, error)
{ // In the future it is possible to also return an endpoint as: // <endpoint>/<zone>/<instanceid> if c.selfAWSInstance.nodeName == nodeName { return "/" + c.selfAWSInstance.availabilityZone + "/" + c.selfAWSInstance.awsID, nil } inst, err := c.getInstanceByNodeName(nodeName) if err != nil { return "", fmt.Errorf("getInstanceByNodeName failed for %q with %v", nodeName, err) } return "/" + orEmpty(inst.Placement.AvailabilityZone) + "/" + orEmpty(inst.InstanceId), nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/aws/aws.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L1073-L1082
go
train
// InstanceType returns the type of the node with the specified nodeName.
func (c *Cloud) InstanceType(nodeName types.NodeName) (string, error)
// InstanceType returns the type of the node with the specified nodeName. func (c *Cloud) InstanceType(nodeName types.NodeName) (string, error)
{ if c.selfAWSInstance.nodeName == nodeName { return c.selfAWSInstance.instanceType, nil } inst, err := c.getInstanceByNodeName(nodeName) if err != nil { return "", fmt.Errorf("getInstanceByNodeName failed for %q with %v", nodeName, err) } return orEmpty(inst.InstanceType), nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/aws/aws.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L1085-L1132
go
train
// Return a list of instances matching regex string.
func (c *Cloud) getInstancesByRegex(regex string) ([]types.NodeName, error)
// Return a list of instances matching regex string. func (c *Cloud) getInstancesByRegex(regex string) ([]types.NodeName, error)
{ filters := []*ec2.Filter{newEc2Filter("instance-state-name", "running")} instances, err := c.describeInstances(filters) if err != nil { return []types.NodeName{}, err } if len(instances) == 0 { return []types.NodeName{}, fmt.Errorf("no instances returned") } if strings.HasPrefix(regex, "'") && strings.HasSuffix(regex, "'") { glog.Infof("Stripping quotes around regex (%s)", regex) regex = regex[1 : len(regex)-1] } re, err := regexp.Compile(regex) if err != nil { return []types.NodeName{}, err } matchingInstances := []types.NodeName{} for _, instance := range instances { // Only return fully-ready instances when listing instances // (vs a query by name, where we will return it if we find it) if orEmpty(instance.State.Name) == "pending" { glog.V(2).Infof("Skipping EC2 instance (pending): %s", *instance.InstanceId) continue } nodeName := mapInstanceToNodeName(instance) if nodeName == "" { glog.V(2).Infof("Skipping EC2 instance (no PrivateDNSName): %s", aws.StringValue(instance.InstanceId)) continue } for _, tag := range instance.Tags { if orEmpty(tag.Key) == "Name" && re.MatchString(orEmpty(tag.Value)) { matchingInstances = append(matchingInstances, nodeName) break } } } glog.V(2).Infof("Matched EC2 instances: %s", matchingInstances) return matchingInstances, nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/aws/aws.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L1249-L1266
go
train
// Gets the full information about this instance from the EC2 API
func (i *awsInstance) describeInstance() (*ec2.Instance, error)
// Gets the full information about this instance from the EC2 API func (i *awsInstance) describeInstance() (*ec2.Instance, error)
{ instanceID := i.awsID request := &ec2.DescribeInstancesInput{ InstanceIds: []*string{&instanceID}, } instances, err := i.ec2.DescribeInstances(request) if err != nil { return nil, err } if len(instances) == 0 { return nil, fmt.Errorf("no instances found for instance: %s", i.awsID) } if len(instances) > 1 { return nil, fmt.Errorf("multiple instances found for instance: %s", i.awsID) } return instances[0], nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/aws/aws.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L1271-L1344
go
train
// Gets the mountDevice already assigned to the volume, or assigns an unused mountDevice. // If the volume is already assigned, this will return the existing mountDevice with alreadyAttached=true. // Otherwise the mountDevice is assigned by finding the first available mountDevice, and it is returned with alreadyAttached=false.
func (c *Cloud) getMountDevice( i *awsInstance, info *ec2.Instance, volumeID awsVolumeID, assign bool) (assigned mountDevice, alreadyAttached bool, err error)
// Gets the mountDevice already assigned to the volume, or assigns an unused mountDevice. // If the volume is already assigned, this will return the existing mountDevice with alreadyAttached=true. // Otherwise the mountDevice is assigned by finding the first available mountDevice, and it is returned with alreadyAttached=false. func (c *Cloud) getMountDevice( i *awsInstance, info *ec2.Instance, volumeID awsVolumeID, assign bool) (assigned mountDevice, alreadyAttached bool, err error)
{ instanceType := i.getInstanceType() if instanceType == nil { return "", false, fmt.Errorf("could not get instance type for instance: %s", i.awsID) } deviceMappings := map[mountDevice]awsVolumeID{} for _, blockDevice := range info.BlockDeviceMappings { name := aws.StringValue(blockDevice.DeviceName) if strings.HasPrefix(name, "/dev/sd") { name = name[7:] } if strings.HasPrefix(name, "/dev/xvd") { name = name[8:] } if len(name) < 1 || len(name) > 2 { glog.Warningf("Unexpected EBS DeviceName: %q", aws.StringValue(blockDevice.DeviceName)) } deviceMappings[mountDevice(name)] = awsVolumeID(aws.StringValue(blockDevice.Ebs.VolumeId)) } // We lock to prevent concurrent mounts from conflicting // We may still conflict if someone calls the API concurrently, // but the AWS API will then fail one of the two attach operations c.attachingMutex.Lock() defer c.attachingMutex.Unlock() for mountDevice, volume := range c.attaching[i.nodeName] { deviceMappings[mountDevice] = volume } // Check to see if this volume is already assigned a device on this machine for mountDevice, mappingVolumeID := range deviceMappings { if volumeID == mappingVolumeID { if assign { glog.Warningf("Got assignment call for already-assigned volume: %s@%s", mountDevice, mappingVolumeID) } return mountDevice, true, nil } } if !assign { return mountDevice(""), false, nil } // Find the next unused device name deviceAllocator := c.deviceAllocators[i.nodeName] if deviceAllocator == nil { // we want device names with two significant characters, starting with /dev/xvdbb // the allowed range is /dev/xvd[b-c][a-z] // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/device_naming.html deviceAllocator = NewDeviceAllocator(0) c.deviceAllocators[i.nodeName] = deviceAllocator } chosen, err := deviceAllocator.GetNext(deviceMappings) if err != nil { glog.Warningf("Could not assign a mount device. mappings=%v, error: %v", deviceMappings, err) return "", false, fmt.Errorf("Too many EBS volumes attached to node %s", i.nodeName) } attaching := c.attaching[i.nodeName] if attaching == nil { attaching = make(map[mountDevice]awsVolumeID) c.attaching[i.nodeName] = attaching } attaching[chosen] = volumeID glog.V(2).Infof("Assigned mount device %s -> volume %s", chosen, volumeID) return chosen, false, nil }
kubernetes-incubator/external-storage
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
snapshot/pkg/cloudprovider/providers/aws/aws.go
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L1348-L1367
go
train
// endAttaching removes the entry from the "attachments in progress" map // It returns true if it was found (and removed), false otherwise
func (c *Cloud) endAttaching(i *awsInstance, volumeID awsVolumeID, mountDevice mountDevice) bool
// endAttaching removes the entry from the "attachments in progress" map // It returns true if it was found (and removed), false otherwise func (c *Cloud) endAttaching(i *awsInstance, volumeID awsVolumeID, mountDevice mountDevice) bool
{ c.attachingMutex.Lock() defer c.attachingMutex.Unlock() existingVolumeID, found := c.attaching[i.nodeName][mountDevice] if !found { return false } if volumeID != existingVolumeID { // This actually can happen, because getMountDevice combines the attaching map with the volumes // attached to the instance (as reported by the EC2 API). So if endAttaching comes after // a 10 second poll delay, we might well have had a concurrent request to allocate a mountpoint, // which because we allocate sequentially is _very_ likely to get the immediately freed volume glog.Infof("endAttaching on device %q assigned to different volume: %q vs %q", mountDevice, volumeID, existingVolumeID) return false } glog.V(2).Infof("Releasing in-process attachment entry: %s -> volume %s", mountDevice, volumeID) delete(c.attaching[i.nodeName], mountDevice) return true }