repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
kubernetes-incubator/external-storage
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
DeepCopy
func (in *VolumeSnapshotCopy) DeepCopy() *VolumeSnapshotCopy { if in == nil { return nil } out := new(VolumeSnapshotCopy) in.DeepCopyInto(out) return out }
go
func (in *VolumeSnapshotCopy) DeepCopy() *VolumeSnapshotCopy { if in == nil { return nil } out := new(VolumeSnapshotCopy) in.DeepCopyInto(out) return out }
[ "func", "(", "in", "*", "VolumeSnapshotCopy", ")", "DeepCopy", "(", ")", "*", "VolumeSnapshotCopy", "{", "if", "in", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "out", ":=", "new", "(", "VolumeSnapshotCopy", ")", "\n", "in", ".", "DeepCopyInto", "(", "out", ")", "\n", "return", "out", "\n", "}" ]
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotCopy.
[ "DeepCopy", "is", "an", "autogenerated", "deepcopy", "function", "copying", "the", "receiver", "creating", "a", "new", "VolumeSnapshotCopy", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L157-L164
train
kubernetes-incubator/external-storage
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
DeepCopy
func (in *VolumeSnapshotData) DeepCopy() *VolumeSnapshotData { if in == nil { return nil } out := new(VolumeSnapshotData) in.DeepCopyInto(out) return out }
go
func (in *VolumeSnapshotData) DeepCopy() *VolumeSnapshotData { if in == nil { return nil } out := new(VolumeSnapshotData) in.DeepCopyInto(out) return out }
[ "func", "(", "in", "*", "VolumeSnapshotData", ")", "DeepCopy", "(", ")", "*", "VolumeSnapshotData", "{", "if", "in", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "out", ":=", "new", "(", "VolumeSnapshotData", ")", "\n", "in", ".", "DeepCopyInto", "(", "out", ")", "\n", "return", "out", "\n", "}" ]
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotData.
[ "DeepCopy", "is", "an", "autogenerated", "deepcopy", "function", "copying", "the", "receiver", "creating", "a", "new", "VolumeSnapshotData", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L177-L184
train
kubernetes-incubator/external-storage
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
DeepCopy
func (in *VolumeSnapshotDataCondition) DeepCopy() *VolumeSnapshotDataCondition { if in == nil { return nil } out := new(VolumeSnapshotDataCondition) in.DeepCopyInto(out) return out }
go
func (in *VolumeSnapshotDataCondition) DeepCopy() *VolumeSnapshotDataCondition { if in == nil { return nil } out := new(VolumeSnapshotDataCondition) in.DeepCopyInto(out) return out }
[ "func", "(", "in", "*", "VolumeSnapshotDataCondition", ")", "DeepCopy", "(", ")", "*", "VolumeSnapshotDataCondition", "{", "if", "in", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "out", ":=", "new", "(", "VolumeSnapshotDataCondition", ")", "\n", "in", ".", "DeepCopyInto", "(", "out", ")", "\n", "return", "out", "\n", "}" ]
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotDataCondition.
[ "DeepCopy", "is", "an", "autogenerated", "deepcopy", "function", "copying", "the", "receiver", "creating", "a", "new", "VolumeSnapshotDataCondition", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L196-L203
train
kubernetes-incubator/external-storage
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
DeepCopy
func (in *VolumeSnapshotDataCopy) DeepCopy() *VolumeSnapshotDataCopy { if in == nil { return nil } out := new(VolumeSnapshotDataCopy) in.DeepCopyInto(out) return out }
go
func (in *VolumeSnapshotDataCopy) DeepCopy() *VolumeSnapshotDataCopy { if in == nil { return nil } out := new(VolumeSnapshotDataCopy) in.DeepCopyInto(out) return out }
[ "func", "(", "in", "*", "VolumeSnapshotDataCopy", ")", "DeepCopy", "(", ")", "*", "VolumeSnapshotDataCopy", "{", "if", "in", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "out", ":=", "new", "(", "VolumeSnapshotDataCopy", ")", "\n", "in", ".", "DeepCopyInto", "(", "out", ")", "\n", "return", "out", "\n", "}" ]
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotDataCopy.
[ "DeepCopy", "is", "an", "autogenerated", "deepcopy", "function", "copying", "the", "receiver", "creating", "a", "new", "VolumeSnapshotDataCopy", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L216-L223
train
kubernetes-incubator/external-storage
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
DeepCopy
func (in *VolumeSnapshotDataList) DeepCopy() *VolumeSnapshotDataList { if in == nil { return nil } out := new(VolumeSnapshotDataList) in.DeepCopyInto(out) return out }
go
func (in *VolumeSnapshotDataList) DeepCopy() *VolumeSnapshotDataList { if in == nil { return nil } out := new(VolumeSnapshotDataList) in.DeepCopyInto(out) return out }
[ "func", "(", "in", "*", "VolumeSnapshotDataList", ")", "DeepCopy", "(", ")", "*", "VolumeSnapshotDataList", "{", "if", "in", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "out", ":=", "new", "(", "VolumeSnapshotDataList", ")", "\n", "in", ".", "DeepCopyInto", "(", "out", ")", "\n", "return", "out", "\n", "}" ]
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotDataList.
[ "DeepCopy", "is", "an", "autogenerated", "deepcopy", "function", "copying", "the", "receiver", "creating", "a", "new", "VolumeSnapshotDataList", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L241-L248
train
kubernetes-incubator/external-storage
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
DeepCopy
func (in *VolumeSnapshotDataListCopy) DeepCopy() *VolumeSnapshotDataListCopy { if in == nil { return nil } out := new(VolumeSnapshotDataListCopy) in.DeepCopyInto(out) return out }
go
func (in *VolumeSnapshotDataListCopy) DeepCopy() *VolumeSnapshotDataListCopy { if in == nil { return nil } out := new(VolumeSnapshotDataListCopy) in.DeepCopyInto(out) return out }
[ "func", "(", "in", "*", "VolumeSnapshotDataListCopy", ")", "DeepCopy", "(", ")", "*", "VolumeSnapshotDataListCopy", "{", "if", "in", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "out", ":=", "new", "(", "VolumeSnapshotDataListCopy", ")", "\n", "in", ".", "DeepCopyInto", "(", "out", ")", "\n", "return", "out", "\n", "}" ]
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotDataListCopy.
[ "DeepCopy", "is", "an", "autogenerated", "deepcopy", "function", "copying", "the", "receiver", "creating", "a", "new", "VolumeSnapshotDataListCopy", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L275-L282
train
kubernetes-incubator/external-storage
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
DeepCopy
func (in *VolumeSnapshotDataSource) DeepCopy() *VolumeSnapshotDataSource { if in == nil { return nil } out := new(VolumeSnapshotDataSource) in.DeepCopyInto(out) return out }
go
func (in *VolumeSnapshotDataSource) DeepCopy() *VolumeSnapshotDataSource { if in == nil { return nil } out := new(VolumeSnapshotDataSource) in.DeepCopyInto(out) return out }
[ "func", "(", "in", "*", "VolumeSnapshotDataSource", ")", "DeepCopy", "(", ")", "*", "VolumeSnapshotDataSource", "{", "if", "in", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "out", ":=", "new", "(", "VolumeSnapshotDataSource", ")", "\n", "in", ".", "DeepCopyInto", "(", "out", ")", "\n", "return", "out", "\n", "}" ]
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotDataSource.
[ "DeepCopy", "is", "an", "autogenerated", "deepcopy", "function", "copying", "the", "receiver", "creating", "a", "new", "VolumeSnapshotDataSource", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L336-L343
train
kubernetes-incubator/external-storage
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
DeepCopy
func (in *VolumeSnapshotDataSpec) DeepCopy() *VolumeSnapshotDataSpec { if in == nil { return nil } out := new(VolumeSnapshotDataSpec) in.DeepCopyInto(out) return out }
go
func (in *VolumeSnapshotDataSpec) DeepCopy() *VolumeSnapshotDataSpec { if in == nil { return nil } out := new(VolumeSnapshotDataSpec) in.DeepCopyInto(out) return out }
[ "func", "(", "in", "*", "VolumeSnapshotDataSpec", ")", "DeepCopy", "(", ")", "*", "VolumeSnapshotDataSpec", "{", "if", "in", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "out", ":=", "new", "(", "VolumeSnapshotDataSpec", ")", "\n", "in", ".", "DeepCopyInto", "(", "out", ")", "\n", "return", "out", "\n", "}" ]
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotDataSpec.
[ "DeepCopy", "is", "an", "autogenerated", "deepcopy", "function", "copying", "the", "receiver", "creating", "a", "new", "VolumeSnapshotDataSpec", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L346-L353
train
kubernetes-incubator/external-storage
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
DeepCopy
func (in *VolumeSnapshotDataStatus) DeepCopy() *VolumeSnapshotDataStatus { if in == nil { return nil } out := new(VolumeSnapshotDataStatus) in.DeepCopyInto(out) return out }
go
func (in *VolumeSnapshotDataStatus) DeepCopy() *VolumeSnapshotDataStatus { if in == nil { return nil } out := new(VolumeSnapshotDataStatus) in.DeepCopyInto(out) return out }
[ "func", "(", "in", "*", "VolumeSnapshotDataStatus", ")", "DeepCopy", "(", ")", "*", "VolumeSnapshotDataStatus", "{", "if", "in", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "out", ":=", "new", "(", "VolumeSnapshotDataStatus", ")", "\n", "in", ".", "DeepCopyInto", "(", "out", ")", "\n", "return", "out", "\n", "}" ]
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotDataStatus.
[ "DeepCopy", "is", "an", "autogenerated", "deepcopy", "function", "copying", "the", "receiver", "creating", "a", "new", "VolumeSnapshotDataStatus", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L370-L377
train
kubernetes-incubator/external-storage
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
DeepCopy
func (in *VolumeSnapshotList) DeepCopy() *VolumeSnapshotList { if in == nil { return nil } out := new(VolumeSnapshotList) in.DeepCopyInto(out) return out }
go
func (in *VolumeSnapshotList) DeepCopy() *VolumeSnapshotList { if in == nil { return nil } out := new(VolumeSnapshotList) in.DeepCopyInto(out) return out }
[ "func", "(", "in", "*", "VolumeSnapshotList", ")", "DeepCopy", "(", ")", "*", "VolumeSnapshotList", "{", "if", "in", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "out", ":=", "new", "(", "VolumeSnapshotList", ")", "\n", "in", ".", "DeepCopyInto", "(", "out", ")", "\n", "return", "out", "\n", "}" ]
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotList.
[ "DeepCopy", "is", "an", "autogenerated", "deepcopy", "function", "copying", "the", "receiver", "creating", "a", "new", "VolumeSnapshotList", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L395-L402
train
kubernetes-incubator/external-storage
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
DeepCopy
func (in *VolumeSnapshotListCopy) DeepCopy() *VolumeSnapshotListCopy { if in == nil { return nil } out := new(VolumeSnapshotListCopy) in.DeepCopyInto(out) return out }
go
func (in *VolumeSnapshotListCopy) DeepCopy() *VolumeSnapshotListCopy { if in == nil { return nil } out := new(VolumeSnapshotListCopy) in.DeepCopyInto(out) return out }
[ "func", "(", "in", "*", "VolumeSnapshotListCopy", ")", "DeepCopy", "(", ")", "*", "VolumeSnapshotListCopy", "{", "if", "in", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "out", ":=", "new", "(", "VolumeSnapshotListCopy", ")", "\n", "in", ".", "DeepCopyInto", "(", "out", ")", "\n", "return", "out", "\n", "}" ]
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotListCopy.
[ "DeepCopy", "is", "an", "autogenerated", "deepcopy", "function", "copying", "the", "receiver", "creating", "a", "new", "VolumeSnapshotListCopy", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L429-L436
train
kubernetes-incubator/external-storage
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
DeepCopy
func (in *VolumeSnapshotSpec) DeepCopy() *VolumeSnapshotSpec { if in == nil { return nil } out := new(VolumeSnapshotSpec) in.DeepCopyInto(out) return out }
go
func (in *VolumeSnapshotSpec) DeepCopy() *VolumeSnapshotSpec { if in == nil { return nil } out := new(VolumeSnapshotSpec) in.DeepCopyInto(out) return out }
[ "func", "(", "in", "*", "VolumeSnapshotSpec", ")", "DeepCopy", "(", ")", "*", "VolumeSnapshotSpec", "{", "if", "in", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "out", ":=", "new", "(", "VolumeSnapshotSpec", ")", "\n", "in", ".", "DeepCopyInto", "(", "out", ")", "\n", "return", "out", "\n", "}" ]
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotSpec.
[ "DeepCopy", "is", "an", "autogenerated", "deepcopy", "function", "copying", "the", "receiver", "creating", "a", "new", "VolumeSnapshotSpec", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L445-L452
train
kubernetes-incubator/external-storage
snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go
DeepCopy
func (in *VolumeSnapshotStatus) DeepCopy() *VolumeSnapshotStatus { if in == nil { return nil } out := new(VolumeSnapshotStatus) in.DeepCopyInto(out) return out }
go
func (in *VolumeSnapshotStatus) DeepCopy() *VolumeSnapshotStatus { if in == nil { return nil } out := new(VolumeSnapshotStatus) in.DeepCopyInto(out) return out }
[ "func", "(", "in", "*", "VolumeSnapshotStatus", ")", "DeepCopy", "(", ")", "*", "VolumeSnapshotStatus", "{", "if", "in", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "out", ":=", "new", "(", "VolumeSnapshotStatus", ")", "\n", "in", ".", "DeepCopyInto", "(", "out", ")", "\n", "return", "out", "\n", "}" ]
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VolumeSnapshotStatus.
[ "DeepCopy", "is", "an", "autogenerated", "deepcopy", "function", "copying", "the", "receiver", "creating", "a", "new", "VolumeSnapshotStatus", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/apis/crd/v1/zz_generated.deepcopy.go#L469-L476
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go
GetLoadBalancer
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 }
go
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 }
[ "func", "(", "lbaas", "*", "LbaasV2", ")", "GetLoadBalancer", "(", "clusterName", "string", ",", "service", "*", "v1", ".", "Service", ")", "(", "*", "v1", ".", "LoadBalancerStatus", ",", "bool", ",", "error", ")", "{", "loadBalancerName", ":=", "cloudprovider", ".", "GetLoadBalancerName", "(", "service", ")", "\n", "loadbalancer", ",", "err", ":=", "getLoadbalancerByName", "(", "lbaas", ".", "network", ",", "loadBalancerName", ")", "\n", "if", "err", "==", "ErrNotFound", "{", "return", "nil", ",", "false", ",", "nil", "\n", "}", "\n", "if", "loadbalancer", "==", "nil", "{", "return", "nil", ",", "false", ",", "err", "\n", "}", "\n", "status", ":=", "&", "v1", ".", "LoadBalancerStatus", "{", "}", "\n", "status", ".", "Ingress", "=", "[", "]", "v1", ".", "LoadBalancerIngress", "{", "{", "IP", ":", "loadbalancer", ".", "VipAddress", "}", "}", "\n", "return", "status", ",", "true", ",", "err", "\n", "}" ]
// GetLoadBalancer gets the status of the load balancer
[ "GetLoadBalancer", "gets", "the", "status", "of", "the", "load", "balancer" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go#L548-L562
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go
GetLoadBalancer
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 }
go
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 }
[ "func", "(", "lb", "*", "LbaasV1", ")", "GetLoadBalancer", "(", "clusterName", "string", ",", "service", "*", "v1", ".", "Service", ")", "(", "*", "v1", ".", "LoadBalancerStatus", ",", "bool", ",", "error", ")", "{", "loadBalancerName", ":=", "cloudprovider", ".", "GetLoadBalancerName", "(", "service", ")", "\n", "vip", ",", "err", ":=", "getVipByName", "(", "lb", ".", "network", ",", "loadBalancerName", ")", "\n", "if", "err", "==", "ErrNotFound", "{", "return", "nil", ",", "false", ",", "nil", "\n", "}", "\n", "if", "vip", "==", "nil", "{", "return", "nil", ",", "false", ",", "err", "\n", "}", "\n", "status", ":=", "&", "v1", ".", "LoadBalancerStatus", "{", "}", "\n", "status", ".", "Ingress", "=", "[", "]", "v1", ".", "LoadBalancerIngress", "{", "{", "IP", ":", "vip", ".", "Address", "}", "}", "\n", "return", "status", ",", "true", ",", "err", "\n", "}" ]
// GetLoadBalancer gets a load balancer
[ "GetLoadBalancer", "gets", "a", "load", "balancer" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_loadbalancer.go#L1201-L1215
train
kubernetes-incubator/external-storage
openebs/pkg/v1/maya_api.go
GetMayaClusterIP
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 }
go
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 }
[ "func", "(", "v", "OpenEBSVolume", ")", "GetMayaClusterIP", "(", "client", "kubernetes", ".", "Interface", ")", "(", "string", ",", "error", ")", "{", "clusterIP", ":=", "\"127.0.0.1\"", "\n", "namespace", ":=", "os", ".", "Getenv", "(", "\"OPENEBS_NAMESPACE\"", ")", "\n", "if", "namespace", "==", "\"\"", "{", "namespace", "=", "\"default\"", "\n", "}", "\n", "glog", ".", "Info", "(", "\"OpenEBS volume provisioner namespace \"", ",", "namespace", ")", "\n", "sc", ",", "err", ":=", "client", ".", "CoreV1", "(", ")", ".", "Services", "(", "namespace", ")", ".", "Get", "(", "\"maya-apiserver-service\"", ",", "metav1", ".", "GetOptions", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Errorf", "(", "\"Error getting maya-apiserver IP Address: %v\"", ",", "err", ")", "\n", "}", "\n", "clusterIP", "=", "sc", ".", "Spec", ".", "ClusterIP", "\n", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"Maya Cluster IP: %v\"", ",", "clusterIP", ")", "\n", "return", "clusterIP", ",", "err", "\n", "}" ]
//GetMayaClusterIP returns maya-apiserver IP address
[ "GetMayaClusterIP", "returns", "maya", "-", "apiserver", "IP", "address" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/openebs/pkg/v1/maya_api.go#L55-L74
train
kubernetes-incubator/external-storage
openebs/pkg/v1/maya_api.go
CreateVolume
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 }
go
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 }
[ "func", "(", "v", "OpenEBSVolume", ")", "CreateVolume", "(", "vs", "mayav1", ".", "VolumeSpec", ")", "(", "string", ",", "error", ")", "{", "addr", ":=", "os", ".", "Getenv", "(", "\"MAPI_ADDR\"", ")", "\n", "if", "addr", "==", "\"\"", "{", "err", ":=", "errors", ".", "New", "(", "\"MAPI_ADDR environment variable not set\"", ")", "\n", "glog", ".", "Errorf", "(", "\"Error getting maya-apiserver IP Address: %v\"", ",", "err", ")", "\n", "return", "\"Error getting maya-apiserver IP Address\"", ",", "err", "\n", "}", "\n", "url", ":=", "addr", "+", "\"/latest/volumes/\"", "\n", "vs", ".", "Kind", "=", "\"PersistentVolumeClaim\"", "\n", "vs", ".", "APIVersion", "=", "\"v1\"", "\n", "yamlValue", ",", "_", ":=", "yaml", ".", "Marshal", "(", "vs", ")", "\n", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"[DEBUG] volume Spec Created:\\n%v\\n\"", ",", "\\n", ")", "\n", "\\n", "\n", "string", "(", "yamlValue", ")", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"POST\"", ",", "url", ",", "bytes", ".", "NewBuffer", "(", "yamlValue", ")", ")", "\n", "req", ".", "Header", ".", "Add", "(", "\"Content-Type\"", ",", "\"application/yaml\"", ")", "\n", "c", ":=", "&", "http", ".", "Client", "{", "Timeout", ":", "timeout", ",", "}", "\n", "resp", ",", "err", ":=", "c", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Errorf", "(", "\"Error when connecting maya-apiserver %v\"", ",", "err", ")", "\n", "return", "\"Could not connect to maya-apiserver\"", ",", "err", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Errorf", "(", "\"Unable to read response from maya-apiserver %v\"", ",", "err", ")", "\n", "return", "\"Unable to read response from maya-apiserver\"", ",", "err", "\n", "}", "\n", "code", ":=", "resp", ".", "StatusCode", "\n", "if", "code", "!=", "http", ".", "StatusOK", "{", "glog", ".", "Errorf", "(", "\"Status error: %v\\n\"", ",", "\\n", ")", "\n", "http", ".", "StatusText", "(", "code", ")", "\n", "}", "\n", "}" ]
// CreateVolume to create the Vsm through a API call to m-apiserver
[ "CreateVolume", "to", "create", "the", "Vsm", "through", "a", "API", "call", "to", "m", "-", "apiserver" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/openebs/pkg/v1/maya_api.go#L77-L123
train
kubernetes-incubator/external-storage
openebs/pkg/v1/maya_api.go
ListVolume
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) }
go
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) }
[ "func", "(", "v", "OpenEBSVolume", ")", "ListVolume", "(", "vname", "string", ",", "obj", "interface", "{", "}", ")", "error", "{", "addr", ":=", "os", ".", "Getenv", "(", "\"MAPI_ADDR\"", ")", "\n", "if", "addr", "==", "\"\"", "{", "err", ":=", "errors", ".", "New", "(", "\"MAPI_ADDR environment variable not set\"", ")", "\n", "glog", ".", "Errorf", "(", "\"Error getting mayaapi-server IP Address: %v\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "url", ":=", "addr", "+", "\"/latest/volumes/info/\"", "+", "vname", "\n", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"[DEBUG] Get details for Volume :%v\"", ",", "string", "(", "vname", ")", ")", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"GET\"", ",", "url", ",", "nil", ")", "\n", "c", ":=", "&", "http", ".", "Client", "{", "Timeout", ":", "timeout", ",", "}", "\n", "resp", ",", "err", ":=", "c", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Errorf", "(", "\"Error when connecting to maya-apiserver %v\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "code", ":=", "resp", ".", "StatusCode", "\n", "if", "code", "!=", "http", ".", "StatusOK", "{", "glog", ".", "Errorf", "(", "\"HTTP Status error from maya-apiserver: %v\\n\"", ",", "\\n", ")", "\n", "http", ".", "StatusText", "(", "code", ")", "\n", "}", "\n", "return", "err", "\n", "glog", ".", "V", "(", "2", ")", ".", "Info", "(", "\"volume Details Successfully Retrieved\"", ")", "\n", "}" ]
// ListVolume to get the info of Vsm through a API call to m-apiserver
[ "ListVolume", "to", "get", "the", "info", "of", "Vsm", "through", "a", "API", "call", "to", "m", "-", "apiserver" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/openebs/pkg/v1/maya_api.go#L126-L156
train
kubernetes-incubator/external-storage
aws/efs/cmd/efs-provisioner/efs-provisioner.go
NewEFSProvisioner
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), } }
go
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), } }
[ "func", "NewEFSProvisioner", "(", "client", "kubernetes", ".", "Interface", ")", "controller", ".", "Provisioner", "{", "fileSystemID", ":=", "os", ".", "Getenv", "(", "fileSystemIDKey", ")", "\n", "if", "fileSystemID", "==", "\"\"", "{", "klog", ".", "Fatalf", "(", "\"environment variable %s is not set! Please set it.\"", ",", "fileSystemIDKey", ")", "\n", "}", "\n", "awsRegion", ":=", "os", ".", "Getenv", "(", "awsRegionKey", ")", "\n", "if", "awsRegion", "==", "\"\"", "{", "klog", ".", "Fatalf", "(", "\"environment variable %s is not set! Please set it.\"", ",", "awsRegionKey", ")", "\n", "}", "\n", "dnsName", ":=", "os", ".", "Getenv", "(", "dnsNameKey", ")", "\n", "klog", ".", "Errorf", "(", "\"%v\"", ",", "dnsName", ")", "\n", "if", "dnsName", "==", "\"\"", "{", "dnsName", "=", "getDNSName", "(", "fileSystemID", ",", "awsRegion", ")", "\n", "}", "\n", "mountpoint", ",", "source", ",", "err", ":=", "getMount", "(", "dnsName", ")", "\n", "if", "err", "!=", "nil", "{", "klog", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "sess", ",", "err", ":=", "session", ".", "NewSession", "(", ")", "\n", "if", "err", "!=", "nil", "{", "klog", ".", "Warningf", "(", "\"couldn't create an AWS session: %v\"", ",", "err", ")", "\n", "}", "\n", "svc", ":=", "efs", ".", "New", "(", "sess", ",", "&", "aws", ".", "Config", "{", "Region", ":", "aws", ".", "String", "(", "awsRegion", ")", "}", ")", "\n", "params", ":=", "&", "efs", ".", "DescribeFileSystemsInput", "{", "FileSystemId", ":", "aws", ".", "String", "(", "fileSystemID", ")", ",", "}", "\n", "_", ",", "err", "=", "svc", ".", "DescribeFileSystems", "(", "params", ")", "\n", "if", "err", "!=", "nil", "{", "klog", ".", "Warningf", "(", "\"couldn't confirm that the EFS file system exists: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "&", "efsProvisioner", "{", "dnsName", ":", "dnsName", ",", "mountpoint", ":", "mountpoint", ",", "source", ":", "source", ",", "allocator", ":", "gidallocator", ".", "New", "(", "client", ")", ",", "}", "\n", "}" ]
// NewEFSProvisioner creates an AWS EFS volume provisioner
[ "NewEFSProvisioner", "creates", "an", "AWS", "EFS", "volume", "provisioner" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/aws/efs/cmd/efs-provisioner/efs-provisioner.go#L57-L100
train
kubernetes-incubator/external-storage
local-volume/provisioner/pkg/util/api_util.go
CreatePV
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 }
go
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 }
[ "func", "(", "u", "*", "apiUtil", ")", "CreatePV", "(", "pv", "*", "v1", ".", "PersistentVolume", ")", "(", "*", "v1", ".", "PersistentVolume", ",", "error", ")", "{", "startTime", ":=", "time", ".", "Now", "(", ")", "\n", "metrics", ".", "APIServerRequestsTotal", ".", "WithLabelValues", "(", "metrics", ".", "APIServerRequestCreate", ")", ".", "Inc", "(", ")", "\n", "pv", ",", "err", ":=", "u", ".", "client", ".", "CoreV1", "(", ")", ".", "PersistentVolumes", "(", ")", ".", "Create", "(", "pv", ")", "\n", "metrics", ".", "APIServerRequestsDurationSeconds", ".", "WithLabelValues", "(", "metrics", ".", "APIServerRequestCreate", ")", ".", "Observe", "(", "time", ".", "Since", "(", "startTime", ")", ".", "Seconds", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "metrics", ".", "APIServerRequestsFailedTotal", ".", "WithLabelValues", "(", "metrics", ".", "APIServerRequestCreate", ")", ".", "Inc", "(", ")", "\n", "}", "\n", "return", "pv", ",", "err", "\n", "}" ]
// CreatePV will create a PersistentVolume
[ "CreatePV", "will", "create", "a", "PersistentVolume" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/api_util.go#L60-L69
train
kubernetes-incubator/external-storage
local-volume/provisioner/pkg/util/api_util.go
DeletePV
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 }
go
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 }
[ "func", "(", "u", "*", "apiUtil", ")", "DeletePV", "(", "pvName", "string", ")", "error", "{", "startTime", ":=", "time", ".", "Now", "(", ")", "\n", "metrics", ".", "APIServerRequestsTotal", ".", "WithLabelValues", "(", "metrics", ".", "APIServerRequestDelete", ")", ".", "Inc", "(", ")", "\n", "err", ":=", "u", ".", "client", ".", "CoreV1", "(", ")", ".", "PersistentVolumes", "(", ")", ".", "Delete", "(", "pvName", ",", "&", "metav1", ".", "DeleteOptions", "{", "}", ")", "\n", "metrics", ".", "APIServerRequestsDurationSeconds", ".", "WithLabelValues", "(", "metrics", ".", "APIServerRequestDelete", ")", ".", "Observe", "(", "time", ".", "Since", "(", "startTime", ")", ".", "Seconds", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "metrics", ".", "APIServerRequestsFailedTotal", ".", "WithLabelValues", "(", "metrics", ".", "APIServerRequestDelete", ")", ".", "Inc", "(", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// DeletePV will delete a PersistentVolume
[ "DeletePV", "will", "delete", "a", "PersistentVolume" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/api_util.go#L72-L81
train
kubernetes-incubator/external-storage
local-volume/provisioner/pkg/util/api_util.go
NewFakeAPIUtil
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, } }
go
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, } }
[ "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", ",", "}", "\n", "}" ]
// NewFakeAPIUtil returns an APIUtil object that can be used for unit testing
[ "NewFakeAPIUtil", "returns", "an", "APIUtil", "object", "that", "can", "be", "used", "for", "unit", "testing" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/api_util.go#L113-L122
train
kubernetes-incubator/external-storage
local-volume/provisioner/pkg/util/api_util.go
CreatePV
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 }
go
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 }
[ "func", "(", "u", "*", "FakeAPIUtil", ")", "CreatePV", "(", "pv", "*", "v1", ".", "PersistentVolume", ")", "(", "*", "v1", ".", "PersistentVolume", ",", "error", ")", "{", "if", "u", ".", "shouldFail", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"API failed\"", ")", "\n", "}", "\n", "u", ".", "createdPVs", "[", "pv", ".", "Name", "]", "=", "pv", "\n", "u", ".", "cache", ".", "AddPV", "(", "pv", ")", "\n", "return", "pv", ",", "nil", "\n", "}" ]
// CreatePV will add the PV to the created list and cache
[ "CreatePV", "will", "add", "the", "PV", "to", "the", "created", "list", "and", "cache" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/api_util.go#L125-L133
train
kubernetes-incubator/external-storage
local-volume/provisioner/pkg/util/api_util.go
DeletePV
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) }
go
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) }
[ "func", "(", "u", "*", "FakeAPIUtil", ")", "DeletePV", "(", "pvName", "string", ")", "error", "{", "if", "u", ".", "shouldFail", "{", "return", "fmt", ".", "Errorf", "(", "\"API failed\"", ")", "\n", "}", "\n", "pv", ",", "exists", ":=", "u", ".", "cache", ".", "GetPV", "(", "pvName", ")", "\n", "if", "exists", "{", "u", ".", "deletedPVs", "[", "pvName", "]", "=", "pv", "\n", "delete", "(", "u", ".", "createdPVs", ",", "pvName", ")", "\n", "u", ".", "cache", ".", "DeletePV", "(", "pvName", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "NewNotFound", "(", "v1", ".", "Resource", "(", "\"persistentvolumes\"", ")", ",", "pvName", ")", "\n", "}" ]
// DeletePV will delete the PV from the created list and cache, and also add it to the deleted list
[ "DeletePV", "will", "delete", "the", "PV", "from", "the", "created", "list", "and", "cache", "and", "also", "add", "it", "to", "the", "deleted", "list" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/api_util.go#L136-L149
train
kubernetes-incubator/external-storage
local-volume/provisioner/pkg/util/api_util.go
GetAndResetCreatedPVs
func (u *FakeAPIUtil) GetAndResetCreatedPVs() map[string]*v1.PersistentVolume { createdPVs := u.createdPVs u.createdPVs = map[string]*v1.PersistentVolume{} return createdPVs }
go
func (u *FakeAPIUtil) GetAndResetCreatedPVs() map[string]*v1.PersistentVolume { createdPVs := u.createdPVs u.createdPVs = map[string]*v1.PersistentVolume{} return createdPVs }
[ "func", "(", "u", "*", "FakeAPIUtil", ")", "GetAndResetCreatedPVs", "(", ")", "map", "[", "string", "]", "*", "v1", ".", "PersistentVolume", "{", "createdPVs", ":=", "u", ".", "createdPVs", "\n", "u", ".", "createdPVs", "=", "map", "[", "string", "]", "*", "v1", ".", "PersistentVolume", "{", "}", "\n", "return", "createdPVs", "\n", "}" ]
// GetAndResetCreatedPVs returns createdPVs and resets the map // This is only for testing
[ "GetAndResetCreatedPVs", "returns", "createdPVs", "and", "resets", "the", "map", "This", "is", "only", "for", "testing" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/api_util.go#L153-L157
train
kubernetes-incubator/external-storage
local-volume/provisioner/pkg/util/api_util.go
GetAndResetDeletedPVs
func (u *FakeAPIUtil) GetAndResetDeletedPVs() map[string]*v1.PersistentVolume { deletedPVs := u.deletedPVs u.deletedPVs = map[string]*v1.PersistentVolume{} return deletedPVs }
go
func (u *FakeAPIUtil) GetAndResetDeletedPVs() map[string]*v1.PersistentVolume { deletedPVs := u.deletedPVs u.deletedPVs = map[string]*v1.PersistentVolume{} return deletedPVs }
[ "func", "(", "u", "*", "FakeAPIUtil", ")", "GetAndResetDeletedPVs", "(", ")", "map", "[", "string", "]", "*", "v1", ".", "PersistentVolume", "{", "deletedPVs", ":=", "u", ".", "deletedPVs", "\n", "u", ".", "deletedPVs", "=", "map", "[", "string", "]", "*", "v1", ".", "PersistentVolume", "{", "}", "\n", "return", "deletedPVs", "\n", "}" ]
// GetAndResetDeletedPVs returns createdPVs and resets the map // This is only for testing
[ "GetAndResetDeletedPVs", "returns", "createdPVs", "and", "resets", "the", "map", "This", "is", "only", "for", "testing" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/api_util.go#L161-L165
train
kubernetes-incubator/external-storage
local-volume/provisioner/pkg/util/api_util.go
CreateJob
func (u *FakeAPIUtil) CreateJob(job *batch_v1.Job) error { u.CreatedJobs[job.Namespace+"/"+job.Name] = job return nil }
go
func (u *FakeAPIUtil) CreateJob(job *batch_v1.Job) error { u.CreatedJobs[job.Namespace+"/"+job.Name] = job return nil }
[ "func", "(", "u", "*", "FakeAPIUtil", ")", "CreateJob", "(", "job", "*", "batch_v1", ".", "Job", ")", "error", "{", "u", ".", "CreatedJobs", "[", "job", ".", "Namespace", "+", "\"/\"", "+", "job", ".", "Name", "]", "=", "job", "\n", "return", "nil", "\n", "}" ]
// CreateJob mocks job create method.
[ "CreateJob", "mocks", "job", "create", "method", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/api_util.go#L168-L171
train
kubernetes-incubator/external-storage
local-volume/provisioner/pkg/util/api_util.go
DeleteJob
func (u *FakeAPIUtil) DeleteJob(jobName string, namespace string) error { u.DeletedJobs[namespace+"/"+jobName] = jobName return nil }
go
func (u *FakeAPIUtil) DeleteJob(jobName string, namespace string) error { u.DeletedJobs[namespace+"/"+jobName] = jobName return nil }
[ "func", "(", "u", "*", "FakeAPIUtil", ")", "DeleteJob", "(", "jobName", "string", ",", "namespace", "string", ")", "error", "{", "u", ".", "DeletedJobs", "[", "namespace", "+", "\"/\"", "+", "jobName", "]", "=", "jobName", "\n", "return", "nil", "\n", "}" ]
// DeleteJob mocks delete jon method.
[ "DeleteJob", "mocks", "delete", "jon", "method", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/api_util.go#L174-L177
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/aws/aws.go
getInstancesByRegex
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 }
go
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 }
[ "func", "(", "c", "*", "Cloud", ")", "getInstancesByRegex", "(", "regex", "string", ")", "(", "[", "]", "types", ".", "NodeName", ",", "error", ")", "{", "filters", ":=", "[", "]", "*", "ec2", ".", "Filter", "{", "newEc2Filter", "(", "\"instance-state-name\"", ",", "\"running\"", ")", "}", "\n", "instances", ",", "err", ":=", "c", ".", "describeInstances", "(", "filters", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "types", ".", "NodeName", "{", "}", ",", "err", "\n", "}", "\n", "if", "len", "(", "instances", ")", "==", "0", "{", "return", "[", "]", "types", ".", "NodeName", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"no instances returned\"", ")", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "regex", ",", "\"'\"", ")", "&&", "strings", ".", "HasSuffix", "(", "regex", ",", "\"'\"", ")", "{", "glog", ".", "Infof", "(", "\"Stripping quotes around regex (%s)\"", ",", "regex", ")", "\n", "regex", "=", "regex", "[", "1", ":", "len", "(", "regex", ")", "-", "1", "]", "\n", "}", "\n", "re", ",", "err", ":=", "regexp", ".", "Compile", "(", "regex", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "types", ".", "NodeName", "{", "}", ",", "err", "\n", "}", "\n", "matchingInstances", ":=", "[", "]", "types", ".", "NodeName", "{", "}", "\n", "for", "_", ",", "instance", ":=", "range", "instances", "{", "if", "orEmpty", "(", "instance", ".", "State", ".", "Name", ")", "==", "\"pending\"", "{", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"Skipping EC2 instance (pending): %s\"", ",", "*", "instance", ".", "InstanceId", ")", "\n", "continue", "\n", "}", "\n", "nodeName", ":=", "mapInstanceToNodeName", "(", "instance", ")", "\n", "if", "nodeName", "==", "\"\"", "{", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"Skipping EC2 instance (no PrivateDNSName): %s\"", ",", "aws", ".", "StringValue", "(", "instance", ".", "InstanceId", ")", ")", "\n", "continue", "\n", "}", "\n", "for", "_", ",", "tag", ":=", "range", "instance", ".", "Tags", "{", "if", "orEmpty", "(", "tag", ".", "Key", ")", "==", "\"Name\"", "&&", "re", ".", "MatchString", "(", "orEmpty", "(", "tag", ".", "Value", ")", ")", "{", "matchingInstances", "=", "append", "(", "matchingInstances", ",", "nodeName", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"Matched EC2 instances: %s\"", ",", "matchingInstances", ")", "\n", "return", "matchingInstances", ",", "nil", "\n", "}" ]
// Return a list of instances matching regex string.
[ "Return", "a", "list", "of", "instances", "matching", "regex", "string", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L1085-L1132
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/aws/aws.go
getMountDevice
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 }
go
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 }
[ "func", "(", "c", "*", "Cloud", ")", "getMountDevice", "(", "i", "*", "awsInstance", ",", "info", "*", "ec2", ".", "Instance", ",", "volumeID", "awsVolumeID", ",", "assign", "bool", ")", "(", "assigned", "mountDevice", ",", "alreadyAttached", "bool", ",", "err", "error", ")", "{", "instanceType", ":=", "i", ".", "getInstanceType", "(", ")", "\n", "if", "instanceType", "==", "nil", "{", "return", "\"\"", ",", "false", ",", "fmt", ".", "Errorf", "(", "\"could not get instance type for instance: %s\"", ",", "i", ".", "awsID", ")", "\n", "}", "\n", "deviceMappings", ":=", "map", "[", "mountDevice", "]", "awsVolumeID", "{", "}", "\n", "for", "_", ",", "blockDevice", ":=", "range", "info", ".", "BlockDeviceMappings", "{", "name", ":=", "aws", ".", "StringValue", "(", "blockDevice", ".", "DeviceName", ")", "\n", "if", "strings", ".", "HasPrefix", "(", "name", ",", "\"/dev/sd\"", ")", "{", "name", "=", "name", "[", "7", ":", "]", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "name", ",", "\"/dev/xvd\"", ")", "{", "name", "=", "name", "[", "8", ":", "]", "\n", "}", "\n", "if", "len", "(", "name", ")", "<", "1", "||", "len", "(", "name", ")", ">", "2", "{", "glog", ".", "Warningf", "(", "\"Unexpected EBS DeviceName: %q\"", ",", "aws", ".", "StringValue", "(", "blockDevice", ".", "DeviceName", ")", ")", "\n", "}", "\n", "deviceMappings", "[", "mountDevice", "(", "name", ")", "]", "=", "awsVolumeID", "(", "aws", ".", "StringValue", "(", "blockDevice", ".", "Ebs", ".", "VolumeId", ")", ")", "\n", "}", "\n", "c", ".", "attachingMutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "attachingMutex", ".", "Unlock", "(", ")", "\n", "for", "mountDevice", ",", "volume", ":=", "range", "c", ".", "attaching", "[", "i", ".", "nodeName", "]", "{", "deviceMappings", "[", "mountDevice", "]", "=", "volume", "\n", "}", "\n", "for", "mountDevice", ",", "mappingVolumeID", ":=", "range", "deviceMappings", "{", "if", "volumeID", "==", "mappingVolumeID", "{", "if", "assign", "{", "glog", ".", "Warningf", "(", "\"Got assignment call for already-assigned volume: %s@%s\"", ",", "mountDevice", ",", "mappingVolumeID", ")", "\n", "}", "\n", "return", "mountDevice", ",", "true", ",", "nil", "\n", "}", "\n", "}", "\n", "if", "!", "assign", "{", "return", "mountDevice", "(", "\"\"", ")", ",", "false", ",", "nil", "\n", "}", "\n", "deviceAllocator", ":=", "c", ".", "deviceAllocators", "[", "i", ".", "nodeName", "]", "\n", "if", "deviceAllocator", "==", "nil", "{", "deviceAllocator", "=", "NewDeviceAllocator", "(", "0", ")", "\n", "c", ".", "deviceAllocators", "[", "i", ".", "nodeName", "]", "=", "deviceAllocator", "\n", "}", "\n", "chosen", ",", "err", ":=", "deviceAllocator", ".", "GetNext", "(", "deviceMappings", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Warningf", "(", "\"Could not assign a mount device. mappings=%v, error: %v\"", ",", "deviceMappings", ",", "err", ")", "\n", "return", "\"\"", ",", "false", ",", "fmt", ".", "Errorf", "(", "\"Too many EBS volumes attached to node %s\"", ",", "i", ".", "nodeName", ")", "\n", "}", "\n", "attaching", ":=", "c", ".", "attaching", "[", "i", ".", "nodeName", "]", "\n", "if", "attaching", "==", "nil", "{", "attaching", "=", "make", "(", "map", "[", "mountDevice", "]", "awsVolumeID", ")", "\n", "c", ".", "attaching", "[", "i", ".", "nodeName", "]", "=", "attaching", "\n", "}", "\n", "attaching", "[", "chosen", "]", "=", "volumeID", "\n", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"Assigned mount device %s -> volume %s\"", ",", "chosen", ",", "volumeID", ")", "\n", "return", "chosen", ",", "false", ",", "nil", "\n", "}" ]
// 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.
[ "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", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L1271-L1344
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/aws/aws.go
describeVolume
func (d *awsDisk) describeVolume() (*ec2.Volume, error) { volumeID := d.awsID request := &ec2.DescribeVolumesInput{ VolumeIds: []*string{volumeID.awsString()}, } volumes, err := d.ec2.DescribeVolumes(request) if err != nil { return nil, fmt.Errorf("error querying ec2 for volume %q: %v", volumeID, err) } if len(volumes) == 0 { return nil, fmt.Errorf("no volumes found for volume %q", volumeID) } if len(volumes) > 1 { return nil, fmt.Errorf("multiple volumes found for volume %q", volumeID) } return volumes[0], nil }
go
func (d *awsDisk) describeVolume() (*ec2.Volume, error) { volumeID := d.awsID request := &ec2.DescribeVolumesInput{ VolumeIds: []*string{volumeID.awsString()}, } volumes, err := d.ec2.DescribeVolumes(request) if err != nil { return nil, fmt.Errorf("error querying ec2 for volume %q: %v", volumeID, err) } if len(volumes) == 0 { return nil, fmt.Errorf("no volumes found for volume %q", volumeID) } if len(volumes) > 1 { return nil, fmt.Errorf("multiple volumes found for volume %q", volumeID) } return volumes[0], nil }
[ "func", "(", "d", "*", "awsDisk", ")", "describeVolume", "(", ")", "(", "*", "ec2", ".", "Volume", ",", "error", ")", "{", "volumeID", ":=", "d", ".", "awsID", "\n", "request", ":=", "&", "ec2", ".", "DescribeVolumesInput", "{", "VolumeIds", ":", "[", "]", "*", "string", "{", "volumeID", ".", "awsString", "(", ")", "}", ",", "}", "\n", "volumes", ",", "err", ":=", "d", ".", "ec2", ".", "DescribeVolumes", "(", "request", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"error querying ec2 for volume %q: %v\"", ",", "volumeID", ",", "err", ")", "\n", "}", "\n", "if", "len", "(", "volumes", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"no volumes found for volume %q\"", ",", "volumeID", ")", "\n", "}", "\n", "if", "len", "(", "volumes", ")", ">", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"multiple volumes found for volume %q\"", ",", "volumeID", ")", "\n", "}", "\n", "return", "volumes", "[", "0", "]", ",", "nil", "\n", "}" ]
// Gets the full information about this volume from the EC2 API
[ "Gets", "the", "full", "information", "about", "this", "volume", "from", "the", "EC2", "API" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L1388-L1406
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/aws/aws.go
waitForAttachmentStatus
func (d *awsDisk) waitForAttachmentStatus(status string) (*ec2.VolumeAttachment, error) { backoff := wait.Backoff{ Duration: volumeAttachmentStatusInitialDelay, Factor: volumeAttachmentStatusFactor, Steps: volumeAttachmentStatusSteps, } // Because of rate limiting, we often see errors from describeVolume // So we tolerate a limited number of failures. // But once we see more than 10 errors in a row, we return the error describeErrorCount := 0 var attachment *ec2.VolumeAttachment err := wait.ExponentialBackoff(backoff, func() (bool, error) { info, err := d.describeVolume() if err != nil { describeErrorCount++ if describeErrorCount > volumeAttachmentStatusConsecutiveErrorLimit { // report the error return false, err } glog.Warningf("Ignoring error from describe volume; will retry: %q", err) return false, nil } describeErrorCount = 0 if len(info.Attachments) > 1 { // Shouldn't happen; log so we know if it is glog.Warningf("Found multiple attachments for volume %q: %v", d.awsID, info) } attachmentStatus := "" for _, a := range info.Attachments { if attachmentStatus != "" { // Shouldn't happen; log so we know if it is glog.Warningf("Found multiple attachments for volume %q: %v", d.awsID, info) } if a.State != nil { attachment = a attachmentStatus = *a.State } else { // Shouldn't happen; log so we know if it is glog.Warningf("Ignoring nil attachment state for volume %q: %v", d.awsID, a) } } if attachmentStatus == "" { attachmentStatus = "detached" } if attachmentStatus == status { // Attachment is in requested state, finish waiting return true, nil } // continue waiting glog.V(2).Infof("Waiting for volume %q state: actual=%s, desired=%s", d.awsID, attachmentStatus, status) return false, nil }) return attachment, err }
go
func (d *awsDisk) waitForAttachmentStatus(status string) (*ec2.VolumeAttachment, error) { backoff := wait.Backoff{ Duration: volumeAttachmentStatusInitialDelay, Factor: volumeAttachmentStatusFactor, Steps: volumeAttachmentStatusSteps, } // Because of rate limiting, we often see errors from describeVolume // So we tolerate a limited number of failures. // But once we see more than 10 errors in a row, we return the error describeErrorCount := 0 var attachment *ec2.VolumeAttachment err := wait.ExponentialBackoff(backoff, func() (bool, error) { info, err := d.describeVolume() if err != nil { describeErrorCount++ if describeErrorCount > volumeAttachmentStatusConsecutiveErrorLimit { // report the error return false, err } glog.Warningf("Ignoring error from describe volume; will retry: %q", err) return false, nil } describeErrorCount = 0 if len(info.Attachments) > 1 { // Shouldn't happen; log so we know if it is glog.Warningf("Found multiple attachments for volume %q: %v", d.awsID, info) } attachmentStatus := "" for _, a := range info.Attachments { if attachmentStatus != "" { // Shouldn't happen; log so we know if it is glog.Warningf("Found multiple attachments for volume %q: %v", d.awsID, info) } if a.State != nil { attachment = a attachmentStatus = *a.State } else { // Shouldn't happen; log so we know if it is glog.Warningf("Ignoring nil attachment state for volume %q: %v", d.awsID, a) } } if attachmentStatus == "" { attachmentStatus = "detached" } if attachmentStatus == status { // Attachment is in requested state, finish waiting return true, nil } // continue waiting glog.V(2).Infof("Waiting for volume %q state: actual=%s, desired=%s", d.awsID, attachmentStatus, status) return false, nil }) return attachment, err }
[ "func", "(", "d", "*", "awsDisk", ")", "waitForAttachmentStatus", "(", "status", "string", ")", "(", "*", "ec2", ".", "VolumeAttachment", ",", "error", ")", "{", "backoff", ":=", "wait", ".", "Backoff", "{", "Duration", ":", "volumeAttachmentStatusInitialDelay", ",", "Factor", ":", "volumeAttachmentStatusFactor", ",", "Steps", ":", "volumeAttachmentStatusSteps", ",", "}", "\n", "describeErrorCount", ":=", "0", "\n", "var", "attachment", "*", "ec2", ".", "VolumeAttachment", "\n", "err", ":=", "wait", ".", "ExponentialBackoff", "(", "backoff", ",", "func", "(", ")", "(", "bool", ",", "error", ")", "{", "info", ",", "err", ":=", "d", ".", "describeVolume", "(", ")", "\n", "if", "err", "!=", "nil", "{", "describeErrorCount", "++", "\n", "if", "describeErrorCount", ">", "volumeAttachmentStatusConsecutiveErrorLimit", "{", "return", "false", ",", "err", "\n", "}", "\n", "glog", ".", "Warningf", "(", "\"Ignoring error from describe volume; will retry: %q\"", ",", "err", ")", "\n", "return", "false", ",", "nil", "\n", "}", "\n", "describeErrorCount", "=", "0", "\n", "if", "len", "(", "info", ".", "Attachments", ")", ">", "1", "{", "glog", ".", "Warningf", "(", "\"Found multiple attachments for volume %q: %v\"", ",", "d", ".", "awsID", ",", "info", ")", "\n", "}", "\n", "attachmentStatus", ":=", "\"\"", "\n", "for", "_", ",", "a", ":=", "range", "info", ".", "Attachments", "{", "if", "attachmentStatus", "!=", "\"\"", "{", "glog", ".", "Warningf", "(", "\"Found multiple attachments for volume %q: %v\"", ",", "d", ".", "awsID", ",", "info", ")", "\n", "}", "\n", "if", "a", ".", "State", "!=", "nil", "{", "attachment", "=", "a", "\n", "attachmentStatus", "=", "*", "a", ".", "State", "\n", "}", "else", "{", "glog", ".", "Warningf", "(", "\"Ignoring nil attachment state for volume %q: %v\"", ",", "d", ".", "awsID", ",", "a", ")", "\n", "}", "\n", "}", "\n", "if", "attachmentStatus", "==", "\"\"", "{", "attachmentStatus", "=", "\"detached\"", "\n", "}", "\n", "if", "attachmentStatus", "==", "status", "{", "return", "true", ",", "nil", "\n", "}", "\n", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"Waiting for volume %q state: actual=%s, desired=%s\"", ",", "d", ".", "awsID", ",", "attachmentStatus", ",", "status", ")", "\n", "return", "false", ",", "nil", "\n", "}", ")", "\n", "return", "attachment", ",", "err", "\n", "}" ]
// waitForAttachmentStatus polls until the attachment status is the expected value // On success, it returns the last attachment state.
[ "waitForAttachmentStatus", "polls", "until", "the", "attachment", "status", "is", "the", "expected", "value", "On", "success", "it", "returns", "the", "last", "attachment", "state", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L1410-L1466
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/aws/aws.go
deleteVolume
func (d *awsDisk) deleteVolume() (bool, error) { request := &ec2.DeleteVolumeInput{VolumeId: d.awsID.awsString()} _, err := d.ec2.DeleteVolume(request) if err != nil { if awsError, ok := err.(awserr.Error); ok { if awsError.Code() == "InvalidVolume.NotFound" { return false, nil } if awsError.Code() == "VolumeInUse" { return false, volume.NewDeletedVolumeInUseError(err.Error()) } } return false, fmt.Errorf("error deleting EBS volume %q: %v", d.awsID, err) } return true, nil }
go
func (d *awsDisk) deleteVolume() (bool, error) { request := &ec2.DeleteVolumeInput{VolumeId: d.awsID.awsString()} _, err := d.ec2.DeleteVolume(request) if err != nil { if awsError, ok := err.(awserr.Error); ok { if awsError.Code() == "InvalidVolume.NotFound" { return false, nil } if awsError.Code() == "VolumeInUse" { return false, volume.NewDeletedVolumeInUseError(err.Error()) } } return false, fmt.Errorf("error deleting EBS volume %q: %v", d.awsID, err) } return true, nil }
[ "func", "(", "d", "*", "awsDisk", ")", "deleteVolume", "(", ")", "(", "bool", ",", "error", ")", "{", "request", ":=", "&", "ec2", ".", "DeleteVolumeInput", "{", "VolumeId", ":", "d", ".", "awsID", ".", "awsString", "(", ")", "}", "\n", "_", ",", "err", ":=", "d", ".", "ec2", ".", "DeleteVolume", "(", "request", ")", "\n", "if", "err", "!=", "nil", "{", "if", "awsError", ",", "ok", ":=", "err", ".", "(", "awserr", ".", "Error", ")", ";", "ok", "{", "if", "awsError", ".", "Code", "(", ")", "==", "\"InvalidVolume.NotFound\"", "{", "return", "false", ",", "nil", "\n", "}", "\n", "if", "awsError", ".", "Code", "(", ")", "==", "\"VolumeInUse\"", "{", "return", "false", ",", "volume", ".", "NewDeletedVolumeInUseError", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "\n", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"error deleting EBS volume %q: %v\"", ",", "d", ".", "awsID", ",", "err", ")", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}" ]
// Deletes the EBS disk
[ "Deletes", "the", "EBS", "disk" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L1469-L1484
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/aws/aws.go
getAwsInstance
func (c *Cloud) getAwsInstance(nodeName types.NodeName) (*awsInstance, error) { var awsInstance *awsInstance if nodeName == "" { awsInstance = c.selfAWSInstance } else { instance, err := c.getInstanceByNodeName(nodeName) if err != nil { return nil, err } awsInstance = newAWSInstance(c.ec2, instance) } return awsInstance, nil }
go
func (c *Cloud) getAwsInstance(nodeName types.NodeName) (*awsInstance, error) { var awsInstance *awsInstance if nodeName == "" { awsInstance = c.selfAWSInstance } else { instance, err := c.getInstanceByNodeName(nodeName) if err != nil { return nil, err } awsInstance = newAWSInstance(c.ec2, instance) } return awsInstance, nil }
[ "func", "(", "c", "*", "Cloud", ")", "getAwsInstance", "(", "nodeName", "types", ".", "NodeName", ")", "(", "*", "awsInstance", ",", "error", ")", "{", "var", "awsInstance", "*", "awsInstance", "\n", "if", "nodeName", "==", "\"\"", "{", "awsInstance", "=", "c", ".", "selfAWSInstance", "\n", "}", "else", "{", "instance", ",", "err", ":=", "c", ".", "getInstanceByNodeName", "(", "nodeName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "awsInstance", "=", "newAWSInstance", "(", "c", ".", "ec2", ",", "instance", ")", "\n", "}", "\n", "return", "awsInstance", ",", "nil", "\n", "}" ]
// Gets the awsInstance with for the node with the specified nodeName, or the 'self' instance if nodeName == ""
[ "Gets", "the", "awsInstance", "with", "for", "the", "node", "with", "the", "specified", "nodeName", "or", "the", "self", "instance", "if", "nodeName", "==" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L1513-L1527
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/aws/aws.go
GetVolumeLabels
func (c *Cloud) GetVolumeLabels(volumeName KubernetesVolumeID) (map[string]string, error) { awsDisk, err := newAWSDisk(c, volumeName) if err != nil { return nil, err } info, err := awsDisk.describeVolume() if err != nil { return nil, err } labels := make(map[string]string) az := aws.StringValue(info.AvailabilityZone) if az == "" { return nil, fmt.Errorf("volume did not have AZ information: %q", *info.VolumeId) } labels[apis.LabelZoneFailureDomain] = az region, err := azToRegion(az) if err != nil { return nil, err } labels[apis.LabelZoneRegion] = region return labels, nil }
go
func (c *Cloud) GetVolumeLabels(volumeName KubernetesVolumeID) (map[string]string, error) { awsDisk, err := newAWSDisk(c, volumeName) if err != nil { return nil, err } info, err := awsDisk.describeVolume() if err != nil { return nil, err } labels := make(map[string]string) az := aws.StringValue(info.AvailabilityZone) if az == "" { return nil, fmt.Errorf("volume did not have AZ information: %q", *info.VolumeId) } labels[apis.LabelZoneFailureDomain] = az region, err := azToRegion(az) if err != nil { return nil, err } labels[apis.LabelZoneRegion] = region return labels, nil }
[ "func", "(", "c", "*", "Cloud", ")", "GetVolumeLabels", "(", "volumeName", "KubernetesVolumeID", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "awsDisk", ",", "err", ":=", "newAWSDisk", "(", "c", ",", "volumeName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "info", ",", "err", ":=", "awsDisk", ".", "describeVolume", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "labels", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "az", ":=", "aws", ".", "StringValue", "(", "info", ".", "AvailabilityZone", ")", "\n", "if", "az", "==", "\"\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"volume did not have AZ information: %q\"", ",", "*", "info", ".", "VolumeId", ")", "\n", "}", "\n", "labels", "[", "apis", ".", "LabelZoneFailureDomain", "]", "=", "az", "\n", "region", ",", "err", ":=", "azToRegion", "(", "az", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "labels", "[", "apis", ".", "LabelZoneRegion", "]", "=", "region", "\n", "return", "labels", ",", "nil", "\n", "}" ]
// GetVolumeLabels implements Volumes.GetVolumeLabels
[ "GetVolumeLabels", "implements", "Volumes", ".", "GetVolumeLabels" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L1772-L1795
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/aws/aws.go
DisksAreAttached
func (c *Cloud) DisksAreAttached(nodeDisks map[types.NodeName][]KubernetesVolumeID) (map[types.NodeName]map[KubernetesVolumeID]bool, error) { attached := make(map[types.NodeName]map[KubernetesVolumeID]bool) if len(nodeDisks) == 0 { return attached, nil } dnsNameSlice := []string{} for nodeName, diskNames := range nodeDisks { for _, diskName := range diskNames { setNodeDisk(attached, diskName, nodeName, false) } dnsNameSlice = append(dnsNameSlice, mapNodeNameToPrivateDNSName(nodeName)) } awsInstances, err := c.getInstancesByNodeNames(dnsNameSlice) if err != nil { // When there is an error fetching instance information // it is safer to return nil and let volume information not be touched. return nil, err } if len(awsInstances) == 0 { glog.V(2).Infof("DisksAreAttached will assume no disks are attached to any node on AWS cluster.") return attached, nil } awsInstanceMap := make(map[types.NodeName]*ec2.Instance) for _, awsInstance := range awsInstances { awsInstanceMap[mapInstanceToNodeName(awsInstance)] = awsInstance } // Note that we check that the volume is attached to the correct node, not that it is attached to _a_ node for nodeName, diskNames := range nodeDisks { awsInstance := awsInstanceMap[nodeName] if awsInstance == nil { // If instance no longer exists, safe to assume volume is not attached. glog.Warningf( "Node %q does not exist. DisksAreAttached will assume disks %v are not attached to it.", nodeName, diskNames) continue } idToDiskName := make(map[awsVolumeID]KubernetesVolumeID) for _, diskName := range diskNames { volumeID, err := diskName.mapToAWSVolumeID() if err != nil { return nil, fmt.Errorf("error mapping volume spec %q to aws id: %v", diskName, err) } idToDiskName[volumeID] = diskName } for _, blockDevice := range awsInstance.BlockDeviceMappings { volumeID := awsVolumeID(aws.StringValue(blockDevice.Ebs.VolumeId)) diskName, found := idToDiskName[volumeID] if found { // Disk is still attached to node setNodeDisk(attached, diskName, nodeName, true) } } } return attached, nil }
go
func (c *Cloud) DisksAreAttached(nodeDisks map[types.NodeName][]KubernetesVolumeID) (map[types.NodeName]map[KubernetesVolumeID]bool, error) { attached := make(map[types.NodeName]map[KubernetesVolumeID]bool) if len(nodeDisks) == 0 { return attached, nil } dnsNameSlice := []string{} for nodeName, diskNames := range nodeDisks { for _, diskName := range diskNames { setNodeDisk(attached, diskName, nodeName, false) } dnsNameSlice = append(dnsNameSlice, mapNodeNameToPrivateDNSName(nodeName)) } awsInstances, err := c.getInstancesByNodeNames(dnsNameSlice) if err != nil { // When there is an error fetching instance information // it is safer to return nil and let volume information not be touched. return nil, err } if len(awsInstances) == 0 { glog.V(2).Infof("DisksAreAttached will assume no disks are attached to any node on AWS cluster.") return attached, nil } awsInstanceMap := make(map[types.NodeName]*ec2.Instance) for _, awsInstance := range awsInstances { awsInstanceMap[mapInstanceToNodeName(awsInstance)] = awsInstance } // Note that we check that the volume is attached to the correct node, not that it is attached to _a_ node for nodeName, diskNames := range nodeDisks { awsInstance := awsInstanceMap[nodeName] if awsInstance == nil { // If instance no longer exists, safe to assume volume is not attached. glog.Warningf( "Node %q does not exist. DisksAreAttached will assume disks %v are not attached to it.", nodeName, diskNames) continue } idToDiskName := make(map[awsVolumeID]KubernetesVolumeID) for _, diskName := range diskNames { volumeID, err := diskName.mapToAWSVolumeID() if err != nil { return nil, fmt.Errorf("error mapping volume spec %q to aws id: %v", diskName, err) } idToDiskName[volumeID] = diskName } for _, blockDevice := range awsInstance.BlockDeviceMappings { volumeID := awsVolumeID(aws.StringValue(blockDevice.Ebs.VolumeId)) diskName, found := idToDiskName[volumeID] if found { // Disk is still attached to node setNodeDisk(attached, diskName, nodeName, true) } } } return attached, nil }
[ "func", "(", "c", "*", "Cloud", ")", "DisksAreAttached", "(", "nodeDisks", "map", "[", "types", ".", "NodeName", "]", "[", "]", "KubernetesVolumeID", ")", "(", "map", "[", "types", ".", "NodeName", "]", "map", "[", "KubernetesVolumeID", "]", "bool", ",", "error", ")", "{", "attached", ":=", "make", "(", "map", "[", "types", ".", "NodeName", "]", "map", "[", "KubernetesVolumeID", "]", "bool", ")", "\n", "if", "len", "(", "nodeDisks", ")", "==", "0", "{", "return", "attached", ",", "nil", "\n", "}", "\n", "dnsNameSlice", ":=", "[", "]", "string", "{", "}", "\n", "for", "nodeName", ",", "diskNames", ":=", "range", "nodeDisks", "{", "for", "_", ",", "diskName", ":=", "range", "diskNames", "{", "setNodeDisk", "(", "attached", ",", "diskName", ",", "nodeName", ",", "false", ")", "\n", "}", "\n", "dnsNameSlice", "=", "append", "(", "dnsNameSlice", ",", "mapNodeNameToPrivateDNSName", "(", "nodeName", ")", ")", "\n", "}", "\n", "awsInstances", ",", "err", ":=", "c", ".", "getInstancesByNodeNames", "(", "dnsNameSlice", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "awsInstances", ")", "==", "0", "{", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"DisksAreAttached will assume no disks are attached to any node on AWS cluster.\"", ")", "\n", "return", "attached", ",", "nil", "\n", "}", "\n", "awsInstanceMap", ":=", "make", "(", "map", "[", "types", ".", "NodeName", "]", "*", "ec2", ".", "Instance", ")", "\n", "for", "_", ",", "awsInstance", ":=", "range", "awsInstances", "{", "awsInstanceMap", "[", "mapInstanceToNodeName", "(", "awsInstance", ")", "]", "=", "awsInstance", "\n", "}", "\n", "for", "nodeName", ",", "diskNames", ":=", "range", "nodeDisks", "{", "awsInstance", ":=", "awsInstanceMap", "[", "nodeName", "]", "\n", "if", "awsInstance", "==", "nil", "{", "glog", ".", "Warningf", "(", "\"Node %q does not exist. DisksAreAttached will assume disks %v are not attached to it.\"", ",", "nodeName", ",", "diskNames", ")", "\n", "continue", "\n", "}", "\n", "idToDiskName", ":=", "make", "(", "map", "[", "awsVolumeID", "]", "KubernetesVolumeID", ")", "\n", "for", "_", ",", "diskName", ":=", "range", "diskNames", "{", "volumeID", ",", "err", ":=", "diskName", ".", "mapToAWSVolumeID", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"error mapping volume spec %q to aws id: %v\"", ",", "diskName", ",", "err", ")", "\n", "}", "\n", "idToDiskName", "[", "volumeID", "]", "=", "diskName", "\n", "}", "\n", "for", "_", ",", "blockDevice", ":=", "range", "awsInstance", ".", "BlockDeviceMappings", "{", "volumeID", ":=", "awsVolumeID", "(", "aws", ".", "StringValue", "(", "blockDevice", ".", "Ebs", ".", "VolumeId", ")", ")", "\n", "diskName", ",", "found", ":=", "idToDiskName", "[", "volumeID", "]", "\n", "if", "found", "{", "setNodeDisk", "(", "attached", ",", "diskName", ",", "nodeName", ",", "true", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "attached", ",", "nil", "\n", "}" ]
// DisksAreAttached checks whether disks are attached
[ "DisksAreAttached", "checks", "whether", "disks", "are", "attached" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L1844-L1908
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/aws/aws.go
CreateSnapshot
func (c *Cloud) CreateSnapshot(snapshotOptions *SnapshotOptions) (snapshotID string, status string, err error) { request := &ec2.CreateSnapshotInput{} request.VolumeId = aws.String(snapshotOptions.VolumeID) request.DryRun = aws.Bool(false) descriptions := "Created by Kubernetes for volume " + snapshotOptions.VolumeID request.Description = aws.String(descriptions) res, err := c.ec2.CreateSnapshot(request) if err != nil { return "", "", err } if res == nil { return "", "", fmt.Errorf("nil CreateSnapshotResponse") } if snapshotOptions.Tags != nil { awsID := awsVolumeID(aws.StringValue(res.SnapshotId)) // apply tags if err := c.tagging.createTags(c.ec2, string(awsID), ResourceLifecycleOwned, *snapshotOptions.Tags); err != nil { _, delerr := c.DeleteSnapshot(*res.SnapshotId) if delerr != nil { return "", "", fmt.Errorf("error tagging snapshot %s, could not delete the snapshot: %v", *res.SnapshotId, delerr) } return "", "", fmt.Errorf("error tagging snapshot %s: %v", *res.SnapshotId, err) } } return *res.SnapshotId, *res.State, nil }
go
func (c *Cloud) CreateSnapshot(snapshotOptions *SnapshotOptions) (snapshotID string, status string, err error) { request := &ec2.CreateSnapshotInput{} request.VolumeId = aws.String(snapshotOptions.VolumeID) request.DryRun = aws.Bool(false) descriptions := "Created by Kubernetes for volume " + snapshotOptions.VolumeID request.Description = aws.String(descriptions) res, err := c.ec2.CreateSnapshot(request) if err != nil { return "", "", err } if res == nil { return "", "", fmt.Errorf("nil CreateSnapshotResponse") } if snapshotOptions.Tags != nil { awsID := awsVolumeID(aws.StringValue(res.SnapshotId)) // apply tags if err := c.tagging.createTags(c.ec2, string(awsID), ResourceLifecycleOwned, *snapshotOptions.Tags); err != nil { _, delerr := c.DeleteSnapshot(*res.SnapshotId) if delerr != nil { return "", "", fmt.Errorf("error tagging snapshot %s, could not delete the snapshot: %v", *res.SnapshotId, delerr) } return "", "", fmt.Errorf("error tagging snapshot %s: %v", *res.SnapshotId, err) } } return *res.SnapshotId, *res.State, nil }
[ "func", "(", "c", "*", "Cloud", ")", "CreateSnapshot", "(", "snapshotOptions", "*", "SnapshotOptions", ")", "(", "snapshotID", "string", ",", "status", "string", ",", "err", "error", ")", "{", "request", ":=", "&", "ec2", ".", "CreateSnapshotInput", "{", "}", "\n", "request", ".", "VolumeId", "=", "aws", ".", "String", "(", "snapshotOptions", ".", "VolumeID", ")", "\n", "request", ".", "DryRun", "=", "aws", ".", "Bool", "(", "false", ")", "\n", "descriptions", ":=", "\"Created by Kubernetes for volume \"", "+", "snapshotOptions", ".", "VolumeID", "\n", "request", ".", "Description", "=", "aws", ".", "String", "(", "descriptions", ")", "\n", "res", ",", "err", ":=", "c", ".", "ec2", ".", "CreateSnapshot", "(", "request", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "\"\"", ",", "err", "\n", "}", "\n", "if", "res", "==", "nil", "{", "return", "\"\"", ",", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"nil CreateSnapshotResponse\"", ")", "\n", "}", "\n", "if", "snapshotOptions", ".", "Tags", "!=", "nil", "{", "awsID", ":=", "awsVolumeID", "(", "aws", ".", "StringValue", "(", "res", ".", "SnapshotId", ")", ")", "\n", "if", "err", ":=", "c", ".", "tagging", ".", "createTags", "(", "c", ".", "ec2", ",", "string", "(", "awsID", ")", ",", "ResourceLifecycleOwned", ",", "*", "snapshotOptions", ".", "Tags", ")", ";", "err", "!=", "nil", "{", "_", ",", "delerr", ":=", "c", ".", "DeleteSnapshot", "(", "*", "res", ".", "SnapshotId", ")", "\n", "if", "delerr", "!=", "nil", "{", "return", "\"\"", ",", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"error tagging snapshot %s, could not delete the snapshot: %v\"", ",", "*", "res", ".", "SnapshotId", ",", "delerr", ")", "\n", "}", "\n", "return", "\"\"", ",", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"error tagging snapshot %s: %v\"", ",", "*", "res", ".", "SnapshotId", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "*", "res", ".", "SnapshotId", ",", "*", "res", ".", "State", ",", "nil", "\n", "}" ]
// CreateSnapshot creates an EBS volume snapshot
[ "CreateSnapshot", "creates", "an", "EBS", "volume", "snapshot" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L1911-L1937
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/aws/aws.go
DeleteSnapshot
func (c *Cloud) DeleteSnapshot(snapshotID string) (bool, error) { request := &ec2.DeleteSnapshotInput{} request.SnapshotId = aws.String(snapshotID) _, err := c.ec2.DeleteSnapshot(request) if err != nil { return false, err } return true, nil }
go
func (c *Cloud) DeleteSnapshot(snapshotID string) (bool, error) { request := &ec2.DeleteSnapshotInput{} request.SnapshotId = aws.String(snapshotID) _, err := c.ec2.DeleteSnapshot(request) if err != nil { return false, err } return true, nil }
[ "func", "(", "c", "*", "Cloud", ")", "DeleteSnapshot", "(", "snapshotID", "string", ")", "(", "bool", ",", "error", ")", "{", "request", ":=", "&", "ec2", ".", "DeleteSnapshotInput", "{", "}", "\n", "request", ".", "SnapshotId", "=", "aws", ".", "String", "(", "snapshotID", ")", "\n", "_", ",", "err", ":=", "c", ".", "ec2", ".", "DeleteSnapshot", "(", "request", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}" ]
// DeleteSnapshot deletes an EBS volume snapshot
[ "DeleteSnapshot", "deletes", "an", "EBS", "volume", "snapshot" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L1940-L1949
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/aws/aws.go
DescribeSnapshot
func (c *Cloud) DescribeSnapshot(snapshotID string) (status string, isCompleted bool, err error) { request := &ec2.DescribeSnapshotsInput{ SnapshotIds: []*string{ aws.String(snapshotID), }, } result, err := c.ec2.DescribeSnapshots(request) if err != nil { return "", false, err } if len(result) != 1 { return "", false, fmt.Errorf("wrong result from DescribeSnapshots: %#v", result) } if result[0].State == nil { return "", false, fmt.Errorf("missing state from DescribeSnapshots: %#v", result) } if *result[0].State == ec2.SnapshotStateCompleted { return *result[0].State, true, nil } if *result[0].State == ec2.SnapshotStateError { return *result[0].State, false, fmt.Errorf("snapshot state is error: %s", *result[0].StateMessage) } if *result[0].State == ec2.SnapshotStatePending { return *result[0].State, false, nil } return *result[0].State, false, fmt.Errorf("unknown state") }
go
func (c *Cloud) DescribeSnapshot(snapshotID string) (status string, isCompleted bool, err error) { request := &ec2.DescribeSnapshotsInput{ SnapshotIds: []*string{ aws.String(snapshotID), }, } result, err := c.ec2.DescribeSnapshots(request) if err != nil { return "", false, err } if len(result) != 1 { return "", false, fmt.Errorf("wrong result from DescribeSnapshots: %#v", result) } if result[0].State == nil { return "", false, fmt.Errorf("missing state from DescribeSnapshots: %#v", result) } if *result[0].State == ec2.SnapshotStateCompleted { return *result[0].State, true, nil } if *result[0].State == ec2.SnapshotStateError { return *result[0].State, false, fmt.Errorf("snapshot state is error: %s", *result[0].StateMessage) } if *result[0].State == ec2.SnapshotStatePending { return *result[0].State, false, nil } return *result[0].State, false, fmt.Errorf("unknown state") }
[ "func", "(", "c", "*", "Cloud", ")", "DescribeSnapshot", "(", "snapshotID", "string", ")", "(", "status", "string", ",", "isCompleted", "bool", ",", "err", "error", ")", "{", "request", ":=", "&", "ec2", ".", "DescribeSnapshotsInput", "{", "SnapshotIds", ":", "[", "]", "*", "string", "{", "aws", ".", "String", "(", "snapshotID", ")", ",", "}", ",", "}", "\n", "result", ",", "err", ":=", "c", ".", "ec2", ".", "DescribeSnapshots", "(", "request", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "false", ",", "err", "\n", "}", "\n", "if", "len", "(", "result", ")", "!=", "1", "{", "return", "\"\"", ",", "false", ",", "fmt", ".", "Errorf", "(", "\"wrong result from DescribeSnapshots: %#v\"", ",", "result", ")", "\n", "}", "\n", "if", "result", "[", "0", "]", ".", "State", "==", "nil", "{", "return", "\"\"", ",", "false", ",", "fmt", ".", "Errorf", "(", "\"missing state from DescribeSnapshots: %#v\"", ",", "result", ")", "\n", "}", "\n", "if", "*", "result", "[", "0", "]", ".", "State", "==", "ec2", ".", "SnapshotStateCompleted", "{", "return", "*", "result", "[", "0", "]", ".", "State", ",", "true", ",", "nil", "\n", "}", "\n", "if", "*", "result", "[", "0", "]", ".", "State", "==", "ec2", ".", "SnapshotStateError", "{", "return", "*", "result", "[", "0", "]", ".", "State", ",", "false", ",", "fmt", ".", "Errorf", "(", "\"snapshot state is error: %s\"", ",", "*", "result", "[", "0", "]", ".", "StateMessage", ")", "\n", "}", "\n", "if", "*", "result", "[", "0", "]", ".", "State", "==", "ec2", ".", "SnapshotStatePending", "{", "return", "*", "result", "[", "0", "]", ".", "State", ",", "false", ",", "nil", "\n", "}", "\n", "return", "*", "result", "[", "0", "]", ".", "State", ",", "false", ",", "fmt", ".", "Errorf", "(", "\"unknown state\"", ")", "\n", "}" ]
// DescribeSnapshot returns the status of the snapshot
[ "DescribeSnapshot", "returns", "the", "status", "of", "the", "snapshot" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L1952-L1978
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/aws/aws.go
FindSnapshot
func (c *Cloud) FindSnapshot(tags map[string]string) ([]string, []string, error) { request := &ec2.DescribeSnapshotsInput{} for k, v := range tags { filter := &ec2.Filter{} filter.SetName(k) filter.SetValues([]*string{&v}) request.Filters = append(request.Filters, filter) } result, err := c.ec2.DescribeSnapshots(request) if err != nil { return nil, nil, err } var snapshotIDs, statuses []string for _, snapshot := range result { id := *snapshot.SnapshotId status := *snapshot.State glog.Infof("found %s, status %s", id, status) snapshotIDs = append(snapshotIDs, id) statuses = append(statuses, status) } return snapshotIDs, statuses, nil }
go
func (c *Cloud) FindSnapshot(tags map[string]string) ([]string, []string, error) { request := &ec2.DescribeSnapshotsInput{} for k, v := range tags { filter := &ec2.Filter{} filter.SetName(k) filter.SetValues([]*string{&v}) request.Filters = append(request.Filters, filter) } result, err := c.ec2.DescribeSnapshots(request) if err != nil { return nil, nil, err } var snapshotIDs, statuses []string for _, snapshot := range result { id := *snapshot.SnapshotId status := *snapshot.State glog.Infof("found %s, status %s", id, status) snapshotIDs = append(snapshotIDs, id) statuses = append(statuses, status) } return snapshotIDs, statuses, nil }
[ "func", "(", "c", "*", "Cloud", ")", "FindSnapshot", "(", "tags", "map", "[", "string", "]", "string", ")", "(", "[", "]", "string", ",", "[", "]", "string", ",", "error", ")", "{", "request", ":=", "&", "ec2", ".", "DescribeSnapshotsInput", "{", "}", "\n", "for", "k", ",", "v", ":=", "range", "tags", "{", "filter", ":=", "&", "ec2", ".", "Filter", "{", "}", "\n", "filter", ".", "SetName", "(", "k", ")", "\n", "filter", ".", "SetValues", "(", "[", "]", "*", "string", "{", "&", "v", "}", ")", "\n", "request", ".", "Filters", "=", "append", "(", "request", ".", "Filters", ",", "filter", ")", "\n", "}", "\n", "result", ",", "err", ":=", "c", ".", "ec2", ".", "DescribeSnapshots", "(", "request", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "var", "snapshotIDs", ",", "statuses", "[", "]", "string", "\n", "for", "_", ",", "snapshot", ":=", "range", "result", "{", "id", ":=", "*", "snapshot", ".", "SnapshotId", "\n", "status", ":=", "*", "snapshot", ".", "State", "\n", "glog", ".", "Infof", "(", "\"found %s, status %s\"", ",", "id", ",", "status", ")", "\n", "snapshotIDs", "=", "append", "(", "snapshotIDs", ",", "id", ")", "\n", "statuses", "=", "append", "(", "statuses", ",", "status", ")", "\n", "}", "\n", "return", "snapshotIDs", ",", "statuses", ",", "nil", "\n", "}" ]
// FindSnapshot returns the found snapshot
[ "FindSnapshot", "returns", "the", "found", "snapshot" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L1981-L2004
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/aws/aws.go
findSecurityGroup
func (c *Cloud) findSecurityGroup(securityGroupID string) (*ec2.SecurityGroup, error) { describeSecurityGroupsRequest := &ec2.DescribeSecurityGroupsInput{ GroupIds: []*string{&securityGroupID}, } // We don't apply our tag filters because we are retrieving by ID groups, err := c.ec2.DescribeSecurityGroups(describeSecurityGroupsRequest) if err != nil { glog.Warningf("Error retrieving security group: %q", err) return nil, err } if len(groups) == 0 { return nil, nil } if len(groups) != 1 { // This should not be possible - ids should be unique return nil, fmt.Errorf("multiple security groups found with same id %q", securityGroupID) } group := groups[0] return group, nil }
go
func (c *Cloud) findSecurityGroup(securityGroupID string) (*ec2.SecurityGroup, error) { describeSecurityGroupsRequest := &ec2.DescribeSecurityGroupsInput{ GroupIds: []*string{&securityGroupID}, } // We don't apply our tag filters because we are retrieving by ID groups, err := c.ec2.DescribeSecurityGroups(describeSecurityGroupsRequest) if err != nil { glog.Warningf("Error retrieving security group: %q", err) return nil, err } if len(groups) == 0 { return nil, nil } if len(groups) != 1 { // This should not be possible - ids should be unique return nil, fmt.Errorf("multiple security groups found with same id %q", securityGroupID) } group := groups[0] return group, nil }
[ "func", "(", "c", "*", "Cloud", ")", "findSecurityGroup", "(", "securityGroupID", "string", ")", "(", "*", "ec2", ".", "SecurityGroup", ",", "error", ")", "{", "describeSecurityGroupsRequest", ":=", "&", "ec2", ".", "DescribeSecurityGroupsInput", "{", "GroupIds", ":", "[", "]", "*", "string", "{", "&", "securityGroupID", "}", ",", "}", "\n", "groups", ",", "err", ":=", "c", ".", "ec2", ".", "DescribeSecurityGroups", "(", "describeSecurityGroupsRequest", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Warningf", "(", "\"Error retrieving security group: %q\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "groups", ")", "==", "0", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "if", "len", "(", "groups", ")", "!=", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"multiple security groups found with same id %q\"", ",", "securityGroupID", ")", "\n", "}", "\n", "group", ":=", "groups", "[", "0", "]", "\n", "return", "group", ",", "nil", "\n", "}" ]
// Retrieves the specified security group from the AWS API, or returns nil if not found
[ "Retrieves", "the", "specified", "security", "group", "from", "the", "AWS", "API", "or", "returns", "nil", "if", "not", "found" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L2054-L2075
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/aws/aws.go
setSecurityGroupIngress
func (c *Cloud) setSecurityGroupIngress(securityGroupID string, permissions IPPermissionSet) (bool, error) { group, err := c.findSecurityGroup(securityGroupID) if err != nil { glog.Warning("Error retrieving security group", err) return false, err } if group == nil { return false, fmt.Errorf("security group not found: %s", securityGroupID) } glog.V(2).Infof("Existing security group ingress: %s %v", securityGroupID, group.IpPermissions) actual := NewIPPermissionSet(group.IpPermissions...) // EC2 groups rules together, for example combining: // // { Port=80, Range=[A] } and { Port=80, Range=[B] } // // into { Port=80, Range=[A,B] } // // We have to ungroup them, because otherwise the logic becomes really // complicated, and also because if we have Range=[A,B] and we try to // add Range=[A] then EC2 complains about a duplicate rule. permissions = permissions.Ungroup() actual = actual.Ungroup() remove := actual.Difference(permissions) add := permissions.Difference(actual) if add.Len() == 0 && remove.Len() == 0 { return false, nil } // TODO: There is a limit in VPC of 100 rules per security group, so we // probably should try grouping or combining to fit under this limit. // But this is only used on the ELB security group currently, so it // would require (ports * CIDRS) > 100. Also, it isn't obvious exactly // how removing single permissions from compound rules works, and we // don't want to accidentally open more than intended while we're // applying changes. if add.Len() != 0 { glog.V(2).Infof("Adding security group ingress: %s %v", securityGroupID, add.List()) request := &ec2.AuthorizeSecurityGroupIngressInput{} request.GroupId = &securityGroupID request.IpPermissions = add.List() _, err = c.ec2.AuthorizeSecurityGroupIngress(request) if err != nil { return false, fmt.Errorf("error authorizing security group ingress: %v", err) } } if remove.Len() != 0 { glog.V(2).Infof("Remove security group ingress: %s %v", securityGroupID, remove.List()) request := &ec2.RevokeSecurityGroupIngressInput{} request.GroupId = &securityGroupID request.IpPermissions = remove.List() _, err = c.ec2.RevokeSecurityGroupIngress(request) if err != nil { return false, fmt.Errorf("error revoking security group ingress: %v", err) } } return true, nil }
go
func (c *Cloud) setSecurityGroupIngress(securityGroupID string, permissions IPPermissionSet) (bool, error) { group, err := c.findSecurityGroup(securityGroupID) if err != nil { glog.Warning("Error retrieving security group", err) return false, err } if group == nil { return false, fmt.Errorf("security group not found: %s", securityGroupID) } glog.V(2).Infof("Existing security group ingress: %s %v", securityGroupID, group.IpPermissions) actual := NewIPPermissionSet(group.IpPermissions...) // EC2 groups rules together, for example combining: // // { Port=80, Range=[A] } and { Port=80, Range=[B] } // // into { Port=80, Range=[A,B] } // // We have to ungroup them, because otherwise the logic becomes really // complicated, and also because if we have Range=[A,B] and we try to // add Range=[A] then EC2 complains about a duplicate rule. permissions = permissions.Ungroup() actual = actual.Ungroup() remove := actual.Difference(permissions) add := permissions.Difference(actual) if add.Len() == 0 && remove.Len() == 0 { return false, nil } // TODO: There is a limit in VPC of 100 rules per security group, so we // probably should try grouping or combining to fit under this limit. // But this is only used on the ELB security group currently, so it // would require (ports * CIDRS) > 100. Also, it isn't obvious exactly // how removing single permissions from compound rules works, and we // don't want to accidentally open more than intended while we're // applying changes. if add.Len() != 0 { glog.V(2).Infof("Adding security group ingress: %s %v", securityGroupID, add.List()) request := &ec2.AuthorizeSecurityGroupIngressInput{} request.GroupId = &securityGroupID request.IpPermissions = add.List() _, err = c.ec2.AuthorizeSecurityGroupIngress(request) if err != nil { return false, fmt.Errorf("error authorizing security group ingress: %v", err) } } if remove.Len() != 0 { glog.V(2).Infof("Remove security group ingress: %s %v", securityGroupID, remove.List()) request := &ec2.RevokeSecurityGroupIngressInput{} request.GroupId = &securityGroupID request.IpPermissions = remove.List() _, err = c.ec2.RevokeSecurityGroupIngress(request) if err != nil { return false, fmt.Errorf("error revoking security group ingress: %v", err) } } return true, nil }
[ "func", "(", "c", "*", "Cloud", ")", "setSecurityGroupIngress", "(", "securityGroupID", "string", ",", "permissions", "IPPermissionSet", ")", "(", "bool", ",", "error", ")", "{", "group", ",", "err", ":=", "c", ".", "findSecurityGroup", "(", "securityGroupID", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Warning", "(", "\"Error retrieving security group\"", ",", "err", ")", "\n", "return", "false", ",", "err", "\n", "}", "\n", "if", "group", "==", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"security group not found: %s\"", ",", "securityGroupID", ")", "\n", "}", "\n", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"Existing security group ingress: %s %v\"", ",", "securityGroupID", ",", "group", ".", "IpPermissions", ")", "\n", "actual", ":=", "NewIPPermissionSet", "(", "group", ".", "IpPermissions", "...", ")", "\n", "permissions", "=", "permissions", ".", "Ungroup", "(", ")", "\n", "actual", "=", "actual", ".", "Ungroup", "(", ")", "\n", "remove", ":=", "actual", ".", "Difference", "(", "permissions", ")", "\n", "add", ":=", "permissions", ".", "Difference", "(", "actual", ")", "\n", "if", "add", ".", "Len", "(", ")", "==", "0", "&&", "remove", ".", "Len", "(", ")", "==", "0", "{", "return", "false", ",", "nil", "\n", "}", "\n", "if", "add", ".", "Len", "(", ")", "!=", "0", "{", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"Adding security group ingress: %s %v\"", ",", "securityGroupID", ",", "add", ".", "List", "(", ")", ")", "\n", "request", ":=", "&", "ec2", ".", "AuthorizeSecurityGroupIngressInput", "{", "}", "\n", "request", ".", "GroupId", "=", "&", "securityGroupID", "\n", "request", ".", "IpPermissions", "=", "add", ".", "List", "(", ")", "\n", "_", ",", "err", "=", "c", ".", "ec2", ".", "AuthorizeSecurityGroupIngress", "(", "request", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"error authorizing security group ingress: %v\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "if", "remove", ".", "Len", "(", ")", "!=", "0", "{", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"Remove security group ingress: %s %v\"", ",", "securityGroupID", ",", "remove", ".", "List", "(", ")", ")", "\n", "request", ":=", "&", "ec2", ".", "RevokeSecurityGroupIngressInput", "{", "}", "\n", "request", ".", "GroupId", "=", "&", "securityGroupID", "\n", "request", ".", "IpPermissions", "=", "remove", ".", "List", "(", ")", "\n", "_", ",", "err", "=", "c", ".", "ec2", ".", "RevokeSecurityGroupIngress", "(", "request", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"error revoking security group ingress: %v\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}" ]
// Makes sure the security group ingress is exactly the specified permissions // Returns true if and only if changes were made // The security group must already exist
[ "Makes", "sure", "the", "security", "group", "ingress", "is", "exactly", "the", "specified", "permissions", "Returns", "true", "if", "and", "only", "if", "changes", "were", "made", "The", "security", "group", "must", "already", "exist" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L2156-L2221
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/aws/aws.go
findSecurityGroupForInstance
func findSecurityGroupForInstance(instance *ec2.Instance, taggedSecurityGroups map[string]*ec2.SecurityGroup) (*ec2.GroupIdentifier, error) { instanceID := aws.StringValue(instance.InstanceId) var tagged []*ec2.GroupIdentifier var untagged []*ec2.GroupIdentifier for _, group := range instance.SecurityGroups { groupID := aws.StringValue(group.GroupId) if groupID == "" { glog.Warningf("Ignoring security group without id for instance %q: %v", instanceID, group) continue } _, isTagged := taggedSecurityGroups[groupID] if isTagged { tagged = append(tagged, group) } else { untagged = append(untagged, group) } } if len(tagged) > 0 { // We create instances with one SG // If users create multiple SGs, they must tag one of them as being k8s owned if len(tagged) != 1 { return nil, fmt.Errorf("Multiple tagged security groups found for instance %s; ensure only the k8s security group is tagged", instanceID) } return tagged[0], nil } if len(untagged) > 0 { // For back-compat, we will allow a single untagged SG if len(untagged) != 1 { return nil, fmt.Errorf("Multiple untagged security groups found for instance %s; ensure the k8s security group is tagged", instanceID) } return untagged[0], nil } glog.Warningf("No security group found for instance %q", instanceID) return nil, nil }
go
func findSecurityGroupForInstance(instance *ec2.Instance, taggedSecurityGroups map[string]*ec2.SecurityGroup) (*ec2.GroupIdentifier, error) { instanceID := aws.StringValue(instance.InstanceId) var tagged []*ec2.GroupIdentifier var untagged []*ec2.GroupIdentifier for _, group := range instance.SecurityGroups { groupID := aws.StringValue(group.GroupId) if groupID == "" { glog.Warningf("Ignoring security group without id for instance %q: %v", instanceID, group) continue } _, isTagged := taggedSecurityGroups[groupID] if isTagged { tagged = append(tagged, group) } else { untagged = append(untagged, group) } } if len(tagged) > 0 { // We create instances with one SG // If users create multiple SGs, they must tag one of them as being k8s owned if len(tagged) != 1 { return nil, fmt.Errorf("Multiple tagged security groups found for instance %s; ensure only the k8s security group is tagged", instanceID) } return tagged[0], nil } if len(untagged) > 0 { // For back-compat, we will allow a single untagged SG if len(untagged) != 1 { return nil, fmt.Errorf("Multiple untagged security groups found for instance %s; ensure the k8s security group is tagged", instanceID) } return untagged[0], nil } glog.Warningf("No security group found for instance %q", instanceID) return nil, nil }
[ "func", "findSecurityGroupForInstance", "(", "instance", "*", "ec2", ".", "Instance", ",", "taggedSecurityGroups", "map", "[", "string", "]", "*", "ec2", ".", "SecurityGroup", ")", "(", "*", "ec2", ".", "GroupIdentifier", ",", "error", ")", "{", "instanceID", ":=", "aws", ".", "StringValue", "(", "instance", ".", "InstanceId", ")", "\n", "var", "tagged", "[", "]", "*", "ec2", ".", "GroupIdentifier", "\n", "var", "untagged", "[", "]", "*", "ec2", ".", "GroupIdentifier", "\n", "for", "_", ",", "group", ":=", "range", "instance", ".", "SecurityGroups", "{", "groupID", ":=", "aws", ".", "StringValue", "(", "group", ".", "GroupId", ")", "\n", "if", "groupID", "==", "\"\"", "{", "glog", ".", "Warningf", "(", "\"Ignoring security group without id for instance %q: %v\"", ",", "instanceID", ",", "group", ")", "\n", "continue", "\n", "}", "\n", "_", ",", "isTagged", ":=", "taggedSecurityGroups", "[", "groupID", "]", "\n", "if", "isTagged", "{", "tagged", "=", "append", "(", "tagged", ",", "group", ")", "\n", "}", "else", "{", "untagged", "=", "append", "(", "untagged", ",", "group", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "tagged", ")", ">", "0", "{", "if", "len", "(", "tagged", ")", "!=", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Multiple tagged security groups found for instance %s; ensure only the k8s security group is tagged\"", ",", "instanceID", ")", "\n", "}", "\n", "return", "tagged", "[", "0", "]", ",", "nil", "\n", "}", "\n", "if", "len", "(", "untagged", ")", ">", "0", "{", "if", "len", "(", "untagged", ")", "!=", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Multiple untagged security groups found for instance %s; ensure the k8s security group is tagged\"", ",", "instanceID", ")", "\n", "}", "\n", "return", "untagged", "[", "0", "]", ",", "nil", "\n", "}", "\n", "glog", ".", "Warningf", "(", "\"No security group found for instance %q\"", ",", "instanceID", ")", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// Returns the first security group for an instance, or nil // We only create instances with one security group, so we don't expect multiple security groups. // However, if there are multiple security groups, we will choose the one tagged with our cluster filter. // Otherwise we will return an error.
[ "Returns", "the", "first", "security", "group", "for", "an", "instance", "or", "nil", "We", "only", "create", "instances", "with", "one", "security", "group", "so", "we", "don", "t", "expect", "multiple", "security", "groups", ".", "However", "if", "there", "are", "multiple", "security", "groups", "we", "will", "choose", "the", "one", "tagged", "with", "our", "cluster", "filter", ".", "Otherwise", "we", "will", "return", "an", "error", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L2957-L2995
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/aws/aws.go
getInstanceByID
func (c *Cloud) getInstanceByID(instanceID string) (*ec2.Instance, error) { instances, err := c.getInstancesByIDs([]*string{&instanceID}) if err != nil { return nil, err } if len(instances) == 0 { return nil, cloudprovider.ErrInstanceNotFound } if len(instances) > 1 { return nil, fmt.Errorf("multiple instances found for instance: %s", instanceID) } return instances[instanceID], nil }
go
func (c *Cloud) getInstanceByID(instanceID string) (*ec2.Instance, error) { instances, err := c.getInstancesByIDs([]*string{&instanceID}) if err != nil { return nil, err } if len(instances) == 0 { return nil, cloudprovider.ErrInstanceNotFound } if len(instances) > 1 { return nil, fmt.Errorf("multiple instances found for instance: %s", instanceID) } return instances[instanceID], nil }
[ "func", "(", "c", "*", "Cloud", ")", "getInstanceByID", "(", "instanceID", "string", ")", "(", "*", "ec2", ".", "Instance", ",", "error", ")", "{", "instances", ",", "err", ":=", "c", ".", "getInstancesByIDs", "(", "[", "]", "*", "string", "{", "&", "instanceID", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "instances", ")", "==", "0", "{", "return", "nil", ",", "cloudprovider", ".", "ErrInstanceNotFound", "\n", "}", "\n", "if", "len", "(", "instances", ")", ">", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"multiple instances found for instance: %s\"", ",", "instanceID", ")", "\n", "}", "\n", "return", "instances", "[", "instanceID", "]", ",", "nil", "\n", "}" ]
// Returns the instance with the specified ID
[ "Returns", "the", "instance", "with", "the", "specified", "ID" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L3282-L3296
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/aws/aws.go
getInstanceByNodeName
func (c *Cloud) getInstanceByNodeName(nodeName types.NodeName) (*ec2.Instance, error) { instance, err := c.findInstanceByNodeName(nodeName) if err == nil && instance == nil { return nil, cloudprovider.ErrInstanceNotFound } return instance, err }
go
func (c *Cloud) getInstanceByNodeName(nodeName types.NodeName) (*ec2.Instance, error) { instance, err := c.findInstanceByNodeName(nodeName) if err == nil && instance == nil { return nil, cloudprovider.ErrInstanceNotFound } return instance, err }
[ "func", "(", "c", "*", "Cloud", ")", "getInstanceByNodeName", "(", "nodeName", "types", ".", "NodeName", ")", "(", "*", "ec2", ".", "Instance", ",", "error", ")", "{", "instance", ",", "err", ":=", "c", ".", "findInstanceByNodeName", "(", "nodeName", ")", "\n", "if", "err", "==", "nil", "&&", "instance", "==", "nil", "{", "return", "nil", ",", "cloudprovider", ".", "ErrInstanceNotFound", "\n", "}", "\n", "return", "instance", ",", "err", "\n", "}" ]
// Returns the instance with the specified node name // Like findInstanceByNodeName, but returns error if node not found
[ "Returns", "the", "instance", "with", "the", "specified", "node", "name", "Like", "findInstanceByNodeName", "but", "returns", "error", "if", "node", "not", "found" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/aws.go#L3437-L3443
train
kubernetes-incubator/external-storage
gluster/glusterfs/pkg/volume/provision.go
NewGlusterfsProvisioner
func NewGlusterfsProvisioner(config *rest.Config, client kubernetes.Interface) controller.Provisioner { klog.Infof("Creating NewGlusterfsProvisioner.") return newGlusterfsProvisionerInternal(config, client) }
go
func NewGlusterfsProvisioner(config *rest.Config, client kubernetes.Interface) controller.Provisioner { klog.Infof("Creating NewGlusterfsProvisioner.") return newGlusterfsProvisionerInternal(config, client) }
[ "func", "NewGlusterfsProvisioner", "(", "config", "*", "rest", ".", "Config", ",", "client", "kubernetes", ".", "Interface", ")", "controller", ".", "Provisioner", "{", "klog", ".", "Infof", "(", "\"Creating NewGlusterfsProvisioner.\"", ")", "\n", "return", "newGlusterfsProvisionerInternal", "(", "config", ",", "client", ")", "\n", "}" ]
// NewGlusterfsProvisioner creates a new glusterfs simple provisioner
[ "NewGlusterfsProvisioner", "creates", "a", "new", "glusterfs", "simple", "provisioner" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/gluster/glusterfs/pkg/volume/provision.go#L44-L47
train
kubernetes-incubator/external-storage
local-volume/provisioner/pkg/cache/cache.go
GetPV
func (cache *VolumeCache) GetPV(pvName string) (*v1.PersistentVolume, bool) { cache.mutex.Lock() defer cache.mutex.Unlock() pv, exists := cache.pvs[pvName] return pv, exists }
go
func (cache *VolumeCache) GetPV(pvName string) (*v1.PersistentVolume, bool) { cache.mutex.Lock() defer cache.mutex.Unlock() pv, exists := cache.pvs[pvName] return pv, exists }
[ "func", "(", "cache", "*", "VolumeCache", ")", "GetPV", "(", "pvName", "string", ")", "(", "*", "v1", ".", "PersistentVolume", ",", "bool", ")", "{", "cache", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "cache", ".", "mutex", ".", "Unlock", "(", ")", "\n", "pv", ",", "exists", ":=", "cache", ".", "pvs", "[", "pvName", "]", "\n", "return", "pv", ",", "exists", "\n", "}" ]
// GetPV returns the PV object given the PV name
[ "GetPV", "returns", "the", "PV", "object", "given", "the", "PV", "name" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/cache/cache.go#L41-L47
train
kubernetes-incubator/external-storage
local-volume/provisioner/pkg/cache/cache.go
AddPV
func (cache *VolumeCache) AddPV(pv *v1.PersistentVolume) { cache.mutex.Lock() defer cache.mutex.Unlock() cache.pvs[pv.Name] = pv glog.Infof("Added pv %q to cache", pv.Name) }
go
func (cache *VolumeCache) AddPV(pv *v1.PersistentVolume) { cache.mutex.Lock() defer cache.mutex.Unlock() cache.pvs[pv.Name] = pv glog.Infof("Added pv %q to cache", pv.Name) }
[ "func", "(", "cache", "*", "VolumeCache", ")", "AddPV", "(", "pv", "*", "v1", ".", "PersistentVolume", ")", "{", "cache", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "cache", ".", "mutex", ".", "Unlock", "(", ")", "\n", "cache", ".", "pvs", "[", "pv", ".", "Name", "]", "=", "pv", "\n", "glog", ".", "Infof", "(", "\"Added pv %q to cache\"", ",", "pv", ".", "Name", ")", "\n", "}" ]
// AddPV adds the PV object to the cache
[ "AddPV", "adds", "the", "PV", "object", "to", "the", "cache" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/cache/cache.go#L50-L56
train
kubernetes-incubator/external-storage
local-volume/provisioner/pkg/cache/cache.go
DeletePV
func (cache *VolumeCache) DeletePV(pvName string) { cache.mutex.Lock() defer cache.mutex.Unlock() delete(cache.pvs, pvName) glog.Infof("Deleted pv %q from cache", pvName) }
go
func (cache *VolumeCache) DeletePV(pvName string) { cache.mutex.Lock() defer cache.mutex.Unlock() delete(cache.pvs, pvName) glog.Infof("Deleted pv %q from cache", pvName) }
[ "func", "(", "cache", "*", "VolumeCache", ")", "DeletePV", "(", "pvName", "string", ")", "{", "cache", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "cache", ".", "mutex", ".", "Unlock", "(", ")", "\n", "delete", "(", "cache", ".", "pvs", ",", "pvName", ")", "\n", "glog", ".", "Infof", "(", "\"Deleted pv %q from cache\"", ",", "pvName", ")", "\n", "}" ]
// DeletePV deletes the PV object from the cache
[ "DeletePV", "deletes", "the", "PV", "object", "from", "the", "cache" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/cache/cache.go#L68-L74
train
kubernetes-incubator/external-storage
local-volume/provisioner/pkg/cache/cache.go
ListPVs
func (cache *VolumeCache) ListPVs() []*v1.PersistentVolume { cache.mutex.Lock() defer cache.mutex.Unlock() pvs := []*v1.PersistentVolume{} for _, pv := range cache.pvs { pvs = append(pvs, pv) } return pvs }
go
func (cache *VolumeCache) ListPVs() []*v1.PersistentVolume { cache.mutex.Lock() defer cache.mutex.Unlock() pvs := []*v1.PersistentVolume{} for _, pv := range cache.pvs { pvs = append(pvs, pv) } return pvs }
[ "func", "(", "cache", "*", "VolumeCache", ")", "ListPVs", "(", ")", "[", "]", "*", "v1", ".", "PersistentVolume", "{", "cache", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "cache", ".", "mutex", ".", "Unlock", "(", ")", "\n", "pvs", ":=", "[", "]", "*", "v1", ".", "PersistentVolume", "{", "}", "\n", "for", "_", ",", "pv", ":=", "range", "cache", ".", "pvs", "{", "pvs", "=", "append", "(", "pvs", ",", "pv", ")", "\n", "}", "\n", "return", "pvs", "\n", "}" ]
// ListPVs returns a list of all the PVs in the cache
[ "ListPVs", "returns", "a", "list", "of", "all", "the", "PVs", "in", "the", "cache" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/cache/cache.go#L77-L86
train
kubernetes-incubator/external-storage
nfs/pkg/server/server.go
Setup
func Setup(ganeshaConfig string, gracePeriod uint) error { // Start rpcbind if it is not started yet cmd := exec.Command("/usr/sbin/rpcinfo", "127.0.0.1") if err := cmd.Run(); err != nil { cmd = exec.Command("/usr/sbin/rpcbind", "-w") if out, err := cmd.CombinedOutput(); err != nil { return fmt.Errorf("Starting rpcbind failed with error: %v, output: %s", err, out) } } cmd = exec.Command("/usr/sbin/rpc.statd") if out, err := cmd.CombinedOutput(); err != nil { return fmt.Errorf("rpc.statd failed with error: %v, output: %s", err, out) } // Start dbus, needed for ganesha dynamic exports cmd = exec.Command("dbus-daemon", "--system") if out, err := cmd.CombinedOutput(); err != nil { return fmt.Errorf("dbus-daemon failed with error: %v, output: %s", err, out) } err := setRlimitNOFILE() if err != nil { glog.Warningf("Error setting RLIMIT_NOFILE, there may be 'Too many open files' errors later: %v", err) } // Use defaultGaneshaConfigContents if the ganeshaConfig doesn't exist yet if _, err = os.Stat(ganeshaConfig); os.IsNotExist(err) { err = ioutil.WriteFile(ganeshaConfig, defaultGaneshaConfigContents, 0600) if err != nil { return fmt.Errorf("error writing ganesha config %s: %v", ganeshaConfig, err) } } err = setGracePeriod(ganeshaConfig, gracePeriod) if err != nil { return fmt.Errorf("error setting grace period to ganesha config: %v", err) } err = setFsidDevice(ganeshaConfig, true) if err != nil { return fmt.Errorf("error setting fsid device to ganesha config: %v", err) } return nil }
go
func Setup(ganeshaConfig string, gracePeriod uint) error { // Start rpcbind if it is not started yet cmd := exec.Command("/usr/sbin/rpcinfo", "127.0.0.1") if err := cmd.Run(); err != nil { cmd = exec.Command("/usr/sbin/rpcbind", "-w") if out, err := cmd.CombinedOutput(); err != nil { return fmt.Errorf("Starting rpcbind failed with error: %v, output: %s", err, out) } } cmd = exec.Command("/usr/sbin/rpc.statd") if out, err := cmd.CombinedOutput(); err != nil { return fmt.Errorf("rpc.statd failed with error: %v, output: %s", err, out) } // Start dbus, needed for ganesha dynamic exports cmd = exec.Command("dbus-daemon", "--system") if out, err := cmd.CombinedOutput(); err != nil { return fmt.Errorf("dbus-daemon failed with error: %v, output: %s", err, out) } err := setRlimitNOFILE() if err != nil { glog.Warningf("Error setting RLIMIT_NOFILE, there may be 'Too many open files' errors later: %v", err) } // Use defaultGaneshaConfigContents if the ganeshaConfig doesn't exist yet if _, err = os.Stat(ganeshaConfig); os.IsNotExist(err) { err = ioutil.WriteFile(ganeshaConfig, defaultGaneshaConfigContents, 0600) if err != nil { return fmt.Errorf("error writing ganesha config %s: %v", ganeshaConfig, err) } } err = setGracePeriod(ganeshaConfig, gracePeriod) if err != nil { return fmt.Errorf("error setting grace period to ganesha config: %v", err) } err = setFsidDevice(ganeshaConfig, true) if err != nil { return fmt.Errorf("error setting fsid device to ganesha config: %v", err) } return nil }
[ "func", "Setup", "(", "ganeshaConfig", "string", ",", "gracePeriod", "uint", ")", "error", "{", "cmd", ":=", "exec", ".", "Command", "(", "\"/usr/sbin/rpcinfo\"", ",", "\"127.0.0.1\"", ")", "\n", "if", "err", ":=", "cmd", ".", "Run", "(", ")", ";", "err", "!=", "nil", "{", "cmd", "=", "exec", ".", "Command", "(", "\"/usr/sbin/rpcbind\"", ",", "\"-w\"", ")", "\n", "if", "out", ",", "err", ":=", "cmd", ".", "CombinedOutput", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Starting rpcbind failed with error: %v, output: %s\"", ",", "err", ",", "out", ")", "\n", "}", "\n", "}", "\n", "cmd", "=", "exec", ".", "Command", "(", "\"/usr/sbin/rpc.statd\"", ")", "\n", "if", "out", ",", "err", ":=", "cmd", ".", "CombinedOutput", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"rpc.statd failed with error: %v, output: %s\"", ",", "err", ",", "out", ")", "\n", "}", "\n", "cmd", "=", "exec", ".", "Command", "(", "\"dbus-daemon\"", ",", "\"--system\"", ")", "\n", "if", "out", ",", "err", ":=", "cmd", ".", "CombinedOutput", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"dbus-daemon failed with error: %v, output: %s\"", ",", "err", ",", "out", ")", "\n", "}", "\n", "err", ":=", "setRlimitNOFILE", "(", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Warningf", "(", "\"Error setting RLIMIT_NOFILE, there may be 'Too many open files' errors later: %v\"", ",", "err", ")", "\n", "}", "\n", "if", "_", ",", "err", "=", "os", ".", "Stat", "(", "ganeshaConfig", ")", ";", "os", ".", "IsNotExist", "(", "err", ")", "{", "err", "=", "ioutil", ".", "WriteFile", "(", "ganeshaConfig", ",", "defaultGaneshaConfigContents", ",", "0600", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"error writing ganesha config %s: %v\"", ",", "ganeshaConfig", ",", "err", ")", "\n", "}", "\n", "}", "\n", "err", "=", "setGracePeriod", "(", "ganeshaConfig", ",", "gracePeriod", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"error setting grace period to ganesha config: %v\"", ",", "err", ")", "\n", "}", "\n", "err", "=", "setFsidDevice", "(", "ganeshaConfig", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"error setting fsid device to ganesha config: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Setup sets up various prerequisites and settings for the server. If an error // is encountered at any point it returns it instantly
[ "Setup", "sets", "up", "various", "prerequisites", "and", "settings", "for", "the", "server", ".", "If", "an", "error", "is", "encountered", "at", "any", "point", "it", "returns", "it", "instantly" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/nfs/pkg/server/server.go#L77-L120
train
kubernetes-incubator/external-storage
gluster/block/cmd/glusterblock-provisioner/glusterblock-provisioner.go
NewGlusterBlockProvisioner
func NewGlusterBlockProvisioner(client kubernetes.Interface, id string) controller.Provisioner { return &glusterBlockProvisioner{ client: client, identity: id, } }
go
func NewGlusterBlockProvisioner(client kubernetes.Interface, id string) controller.Provisioner { return &glusterBlockProvisioner{ client: client, identity: id, } }
[ "func", "NewGlusterBlockProvisioner", "(", "client", "kubernetes", ".", "Interface", ",", "id", "string", ")", "controller", ".", "Provisioner", "{", "return", "&", "glusterBlockProvisioner", "{", "client", ":", "client", ",", "identity", ":", "id", ",", "}", "\n", "}" ]
//NewGlusterBlockProvisioner create a new provisioner.
[ "NewGlusterBlockProvisioner", "create", "a", "new", "provisioner", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/gluster/block/cmd/glusterblock-provisioner/glusterblock-provisioner.go#L150-L155
train
kubernetes-incubator/external-storage
gluster/block/cmd/glusterblock-provisioner/glusterblock-provisioner.go
createVolume
func (p *glusterBlockProvisioner) createVolume(volSizeInt int, blockVol string, config *provisionerConfig) (*glusterBlockVolume, error) { blockRes := &glusterBlockVolume{} sizeStr := strconv.Itoa(volSizeInt) haCountStr := strconv.Itoa(config.haCount) klog.V(2).Infof("create block volume of size %d and configuration %+v", volSizeInt, config) // Possible opModes are gluster-block and heketi: switch config.opMode { // An experimental/Test Mode: case glusterBlockOpmode: gBlockCreateErr := p.glusterBlockExecCreate(blockRes, config, sizeStr, haCountStr, blockVol) if gBlockCreateErr != nil { klog.Errorf("gluster block volume creation failed: %v", gBlockCreateErr) return nil, fmt.Errorf("gluster block volume creation failed: %v", gBlockCreateErr) } case heketiOpmode: hBlockCreateErr := p.heketiBlockVolCreate(blockRes, config, volSizeInt, haCountStr, blockVol) if hBlockCreateErr != nil { klog.Errorf("heketi block volume creation failed: %v", hBlockCreateErr) return nil, fmt.Errorf("heketi block volume creation failed: %v", hBlockCreateErr) } default: return nil, fmt.Errorf("error parsing value for 'opmode' for volume plugin %s", provisionerName) } return blockRes, nil }
go
func (p *glusterBlockProvisioner) createVolume(volSizeInt int, blockVol string, config *provisionerConfig) (*glusterBlockVolume, error) { blockRes := &glusterBlockVolume{} sizeStr := strconv.Itoa(volSizeInt) haCountStr := strconv.Itoa(config.haCount) klog.V(2).Infof("create block volume of size %d and configuration %+v", volSizeInt, config) // Possible opModes are gluster-block and heketi: switch config.opMode { // An experimental/Test Mode: case glusterBlockOpmode: gBlockCreateErr := p.glusterBlockExecCreate(blockRes, config, sizeStr, haCountStr, blockVol) if gBlockCreateErr != nil { klog.Errorf("gluster block volume creation failed: %v", gBlockCreateErr) return nil, fmt.Errorf("gluster block volume creation failed: %v", gBlockCreateErr) } case heketiOpmode: hBlockCreateErr := p.heketiBlockVolCreate(blockRes, config, volSizeInt, haCountStr, blockVol) if hBlockCreateErr != nil { klog.Errorf("heketi block volume creation failed: %v", hBlockCreateErr) return nil, fmt.Errorf("heketi block volume creation failed: %v", hBlockCreateErr) } default: return nil, fmt.Errorf("error parsing value for 'opmode' for volume plugin %s", provisionerName) } return blockRes, nil }
[ "func", "(", "p", "*", "glusterBlockProvisioner", ")", "createVolume", "(", "volSizeInt", "int", ",", "blockVol", "string", ",", "config", "*", "provisionerConfig", ")", "(", "*", "glusterBlockVolume", ",", "error", ")", "{", "blockRes", ":=", "&", "glusterBlockVolume", "{", "}", "\n", "sizeStr", ":=", "strconv", ".", "Itoa", "(", "volSizeInt", ")", "\n", "haCountStr", ":=", "strconv", ".", "Itoa", "(", "config", ".", "haCount", ")", "\n", "klog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"create block volume of size %d and configuration %+v\"", ",", "volSizeInt", ",", "config", ")", "\n", "switch", "config", ".", "opMode", "{", "case", "glusterBlockOpmode", ":", "gBlockCreateErr", ":=", "p", ".", "glusterBlockExecCreate", "(", "blockRes", ",", "config", ",", "sizeStr", ",", "haCountStr", ",", "blockVol", ")", "\n", "if", "gBlockCreateErr", "!=", "nil", "{", "klog", ".", "Errorf", "(", "\"gluster block volume creation failed: %v\"", ",", "gBlockCreateErr", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"gluster block volume creation failed: %v\"", ",", "gBlockCreateErr", ")", "\n", "}", "\n", "case", "heketiOpmode", ":", "hBlockCreateErr", ":=", "p", ".", "heketiBlockVolCreate", "(", "blockRes", ",", "config", ",", "volSizeInt", ",", "haCountStr", ",", "blockVol", ")", "\n", "if", "hBlockCreateErr", "!=", "nil", "{", "klog", ".", "Errorf", "(", "\"heketi block volume creation failed: %v\"", ",", "hBlockCreateErr", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"heketi block volume creation failed: %v\"", ",", "hBlockCreateErr", ")", "\n", "}", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"error parsing value for 'opmode' for volume plugin %s\"", ",", "provisionerName", ")", "\n", "}", "\n", "return", "blockRes", ",", "nil", "\n", "}" ]
// createVolume creates a gluster block volume i.e. the storage asset.
[ "createVolume", "creates", "a", "gluster", "block", "volume", "i", ".", "e", ".", "the", "storage", "asset", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/gluster/block/cmd/glusterblock-provisioner/glusterblock-provisioner.go#L374-L405
train
kubernetes-incubator/external-storage
gluster/block/cmd/glusterblock-provisioner/glusterblock-provisioner.go
sortTargetPortal
func (p *glusterBlockProvisioner) sortTargetPortal(vol *iscsiSpec) error { if len(vol.Portals) == 0 { return fmt.Errorf("portal is empty") } if len(vol.Portals) == 1 && vol.Portals[0] != "" { vol.TargetPortal = vol.Portals[0] vol.Portals = nil } else { portals := vol.Portals vol.Portals = nil for _, v := range portals { if v != "" && vol.TargetPortal == "" { vol.TargetPortal = v continue } else { vol.Portals = append(vol.Portals, v) } } } return nil }
go
func (p *glusterBlockProvisioner) sortTargetPortal(vol *iscsiSpec) error { if len(vol.Portals) == 0 { return fmt.Errorf("portal is empty") } if len(vol.Portals) == 1 && vol.Portals[0] != "" { vol.TargetPortal = vol.Portals[0] vol.Portals = nil } else { portals := vol.Portals vol.Portals = nil for _, v := range portals { if v != "" && vol.TargetPortal == "" { vol.TargetPortal = v continue } else { vol.Portals = append(vol.Portals, v) } } } return nil }
[ "func", "(", "p", "*", "glusterBlockProvisioner", ")", "sortTargetPortal", "(", "vol", "*", "iscsiSpec", ")", "error", "{", "if", "len", "(", "vol", ".", "Portals", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"portal is empty\"", ")", "\n", "}", "\n", "if", "len", "(", "vol", ".", "Portals", ")", "==", "1", "&&", "vol", ".", "Portals", "[", "0", "]", "!=", "\"\"", "{", "vol", ".", "TargetPortal", "=", "vol", ".", "Portals", "[", "0", "]", "\n", "vol", ".", "Portals", "=", "nil", "\n", "}", "else", "{", "portals", ":=", "vol", ".", "Portals", "\n", "vol", ".", "Portals", "=", "nil", "\n", "for", "_", ",", "v", ":=", "range", "portals", "{", "if", "v", "!=", "\"\"", "&&", "vol", ".", "TargetPortal", "==", "\"\"", "{", "vol", ".", "TargetPortal", "=", "v", "\n", "continue", "\n", "}", "else", "{", "vol", ".", "Portals", "=", "append", "(", "vol", ".", "Portals", ",", "v", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
//sortTargetPortal extract TP
[ "sortTargetPortal", "extract", "TP" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/gluster/block/cmd/glusterblock-provisioner/glusterblock-provisioner.go#L660-L681
train
kubernetes-incubator/external-storage
local-volume/provisioner/pkg/util/volume_util_unsupported.go
IsBlock
func (u *volumeUtil) IsBlock(fullPath string) (bool, error) { return false, fmt.Errorf("IsBlock is unsupported in this build") }
go
func (u *volumeUtil) IsBlock(fullPath string) (bool, error) { return false, fmt.Errorf("IsBlock is unsupported in this build") }
[ "func", "(", "u", "*", "volumeUtil", ")", "IsBlock", "(", "fullPath", "string", ")", "(", "bool", ",", "error", ")", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"IsBlock is unsupported in this build\"", ")", "\n", "}" ]
// IsBlock for unsupported platform returns error.
[ "IsBlock", "for", "unsupported", "platform", "returns", "error", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/volume_util_unsupported.go#L32-L34
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/aws/volumes.go
mapToAWSVolumeID
func (name KubernetesVolumeID) mapToAWSVolumeID() (awsVolumeID, error) { // name looks like aws://availability-zone/awsVolumeId // The original idea of the URL-style name was to put the AZ into the // host, so we could find the AZ immediately from the name without // querying the API. But it turns out we don't actually need it for // multi-AZ clusters, as we put the AZ into the labels on the PV instead. // However, if in future we want to support multi-AZ cluster // volume-awareness without using PersistentVolumes, we likely will // want the AZ in the host. s := string(name) if !strings.HasPrefix(s, "aws://") { // Assume a bare aws volume id (vol-1234...) // Build a URL with an empty host (AZ) s = "aws://" + "" + "/" + s } url, err := url.Parse(s) if err != nil { // TODO: Maybe we should pass a URL into the Volume functions return "", fmt.Errorf("Invalid disk name (%s): %v", name, err) } if url.Scheme != "aws" { return "", fmt.Errorf("Invalid scheme for AWS volume (%s)", name) } awsID := url.Path awsID = strings.Trim(awsID, "/") // We sanity check the resulting volume; the two known formats are // vol-12345678 and vol-12345678abcdef01 // TODO: Regex match? if strings.Contains(awsID, "/") || !strings.HasPrefix(awsID, "vol-") { return "", fmt.Errorf("Invalid format for AWS volume (%s)", name) } return awsVolumeID(awsID), nil }
go
func (name KubernetesVolumeID) mapToAWSVolumeID() (awsVolumeID, error) { // name looks like aws://availability-zone/awsVolumeId // The original idea of the URL-style name was to put the AZ into the // host, so we could find the AZ immediately from the name without // querying the API. But it turns out we don't actually need it for // multi-AZ clusters, as we put the AZ into the labels on the PV instead. // However, if in future we want to support multi-AZ cluster // volume-awareness without using PersistentVolumes, we likely will // want the AZ in the host. s := string(name) if !strings.HasPrefix(s, "aws://") { // Assume a bare aws volume id (vol-1234...) // Build a URL with an empty host (AZ) s = "aws://" + "" + "/" + s } url, err := url.Parse(s) if err != nil { // TODO: Maybe we should pass a URL into the Volume functions return "", fmt.Errorf("Invalid disk name (%s): %v", name, err) } if url.Scheme != "aws" { return "", fmt.Errorf("Invalid scheme for AWS volume (%s)", name) } awsID := url.Path awsID = strings.Trim(awsID, "/") // We sanity check the resulting volume; the two known formats are // vol-12345678 and vol-12345678abcdef01 // TODO: Regex match? if strings.Contains(awsID, "/") || !strings.HasPrefix(awsID, "vol-") { return "", fmt.Errorf("Invalid format for AWS volume (%s)", name) } return awsVolumeID(awsID), nil }
[ "func", "(", "name", "KubernetesVolumeID", ")", "mapToAWSVolumeID", "(", ")", "(", "awsVolumeID", ",", "error", ")", "{", "s", ":=", "string", "(", "name", ")", "\n", "if", "!", "strings", ".", "HasPrefix", "(", "s", ",", "\"aws://\"", ")", "{", "s", "=", "\"aws://\"", "+", "\"\"", "+", "\"/\"", "+", "s", "\n", "}", "\n", "url", ",", "err", ":=", "url", ".", "Parse", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"Invalid disk name (%s): %v\"", ",", "name", ",", "err", ")", "\n", "}", "\n", "if", "url", ".", "Scheme", "!=", "\"aws\"", "{", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"Invalid scheme for AWS volume (%s)\"", ",", "name", ")", "\n", "}", "\n", "awsID", ":=", "url", ".", "Path", "\n", "awsID", "=", "strings", ".", "Trim", "(", "awsID", ",", "\"/\"", ")", "\n", "if", "strings", ".", "Contains", "(", "awsID", ",", "\"/\"", ")", "||", "!", "strings", ".", "HasPrefix", "(", "awsID", ",", "\"vol-\"", ")", "{", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"Invalid format for AWS volume (%s)\"", ",", "name", ")", "\n", "}", "\n", "return", "awsVolumeID", "(", "awsID", ")", ",", "nil", "\n", "}" ]
// mapToAWSVolumeID extracts the awsVolumeID from the KubernetesVolumeID
[ "mapToAWSVolumeID", "extracts", "the", "awsVolumeID", "from", "the", "KubernetesVolumeID" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/volumes.go#L46-L84
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/openstack/openstack.go
LoadBalancer
func (os *OpenStack) LoadBalancer() (cloudprovider.LoadBalancer, bool) { glog.V(4).Info("openstack.LoadBalancer() called") // TODO: Search for and support Rackspace loadbalancer API, and others. network, err := os.NewNetworkV2() if err != nil { return nil, false } compute, err := os.NewComputeV2() if err != nil { return nil, false } lbVersion := os.lbOpts.LBVersion if lbVersion == "" { // No version specified, try newest supported by server netExts, err := networkExtensions(network) if err != nil { glog.Warningf("Failed to list neutron extensions: %v", err) return nil, false } if netExts["lbaasv2"] { lbVersion = "v2" } else if netExts["lbaas"] { lbVersion = "v1" } else { glog.Warningf("Failed to find neutron LBaaS extension (v1 or v2)") return nil, false } glog.V(3).Infof("Using LBaaS extension %v", lbVersion) } glog.V(1).Info("Claiming to support LoadBalancer") if lbVersion == "v2" { return &LbaasV2{LoadBalancer{network, compute, os.lbOpts}}, true } else if lbVersion == "v1" { return &LbaasV1{LoadBalancer{network, compute, os.lbOpts}}, true } else { glog.Warningf("Config error: unrecognised lb-version \"%v\"", lbVersion) return nil, false } }
go
func (os *OpenStack) LoadBalancer() (cloudprovider.LoadBalancer, bool) { glog.V(4).Info("openstack.LoadBalancer() called") // TODO: Search for and support Rackspace loadbalancer API, and others. network, err := os.NewNetworkV2() if err != nil { return nil, false } compute, err := os.NewComputeV2() if err != nil { return nil, false } lbVersion := os.lbOpts.LBVersion if lbVersion == "" { // No version specified, try newest supported by server netExts, err := networkExtensions(network) if err != nil { glog.Warningf("Failed to list neutron extensions: %v", err) return nil, false } if netExts["lbaasv2"] { lbVersion = "v2" } else if netExts["lbaas"] { lbVersion = "v1" } else { glog.Warningf("Failed to find neutron LBaaS extension (v1 or v2)") return nil, false } glog.V(3).Infof("Using LBaaS extension %v", lbVersion) } glog.V(1).Info("Claiming to support LoadBalancer") if lbVersion == "v2" { return &LbaasV2{LoadBalancer{network, compute, os.lbOpts}}, true } else if lbVersion == "v1" { return &LbaasV1{LoadBalancer{network, compute, os.lbOpts}}, true } else { glog.Warningf("Config error: unrecognised lb-version \"%v\"", lbVersion) return nil, false } }
[ "func", "(", "os", "*", "OpenStack", ")", "LoadBalancer", "(", ")", "(", "cloudprovider", ".", "LoadBalancer", ",", "bool", ")", "{", "glog", ".", "V", "(", "4", ")", ".", "Info", "(", "\"openstack.LoadBalancer() called\"", ")", "\n", "network", ",", "err", ":=", "os", ".", "NewNetworkV2", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "false", "\n", "}", "\n", "compute", ",", "err", ":=", "os", ".", "NewComputeV2", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "false", "\n", "}", "\n", "lbVersion", ":=", "os", ".", "lbOpts", ".", "LBVersion", "\n", "if", "lbVersion", "==", "\"\"", "{", "netExts", ",", "err", ":=", "networkExtensions", "(", "network", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Warningf", "(", "\"Failed to list neutron extensions: %v\"", ",", "err", ")", "\n", "return", "nil", ",", "false", "\n", "}", "\n", "if", "netExts", "[", "\"lbaasv2\"", "]", "{", "lbVersion", "=", "\"v2\"", "\n", "}", "else", "if", "netExts", "[", "\"lbaas\"", "]", "{", "lbVersion", "=", "\"v1\"", "\n", "}", "else", "{", "glog", ".", "Warningf", "(", "\"Failed to find neutron LBaaS extension (v1 or v2)\"", ")", "\n", "return", "nil", ",", "false", "\n", "}", "\n", "glog", ".", "V", "(", "3", ")", ".", "Infof", "(", "\"Using LBaaS extension %v\"", ",", "lbVersion", ")", "\n", "}", "\n", "glog", ".", "V", "(", "1", ")", ".", "Info", "(", "\"Claiming to support LoadBalancer\"", ")", "\n", "if", "lbVersion", "==", "\"v2\"", "{", "return", "&", "LbaasV2", "{", "LoadBalancer", "{", "network", ",", "compute", ",", "os", ".", "lbOpts", "}", "}", ",", "true", "\n", "}", "else", "if", "lbVersion", "==", "\"v1\"", "{", "return", "&", "LbaasV1", "{", "LoadBalancer", "{", "network", ",", "compute", ",", "os", ".", "lbOpts", "}", "}", ",", "true", "\n", "}", "else", "{", "glog", ".", "Warningf", "(", "\"Config error: unrecognised lb-version \\\"%v\\\"\"", ",", "\\\"", ")", "\n", "\\\"", "\n", "}", "\n", "}" ]
// LoadBalancer returns a load balancer
[ "LoadBalancer", "returns", "a", "load", "balancer" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack.go#L250-L294
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/openstack/openstack.go
Routes
func (os *OpenStack) Routes() (cloudprovider.Routes, bool) { glog.V(4).Info("openstack.Routes() called") network, err := os.NewNetworkV2() if err != nil { return nil, false } netExts, err := networkExtensions(network) if err != nil { glog.Warningf("Failed to list neutron extensions: %v", err) return nil, false } if !netExts["extraroute"] { glog.V(3).Infof("Neutron extraroute extension not found, required for Routes support") return nil, false } compute, err := os.NewComputeV2() if err != nil { return nil, false } r, err := NewRoutes(compute, network, os.routeOpts) if err != nil { glog.Warningf("Error initialising Routes support: %v", err) return nil, false } glog.V(1).Info("Claiming to support Routes") return r, true }
go
func (os *OpenStack) Routes() (cloudprovider.Routes, bool) { glog.V(4).Info("openstack.Routes() called") network, err := os.NewNetworkV2() if err != nil { return nil, false } netExts, err := networkExtensions(network) if err != nil { glog.Warningf("Failed to list neutron extensions: %v", err) return nil, false } if !netExts["extraroute"] { glog.V(3).Infof("Neutron extraroute extension not found, required for Routes support") return nil, false } compute, err := os.NewComputeV2() if err != nil { return nil, false } r, err := NewRoutes(compute, network, os.routeOpts) if err != nil { glog.Warningf("Error initialising Routes support: %v", err) return nil, false } glog.V(1).Info("Claiming to support Routes") return r, true }
[ "func", "(", "os", "*", "OpenStack", ")", "Routes", "(", ")", "(", "cloudprovider", ".", "Routes", ",", "bool", ")", "{", "glog", ".", "V", "(", "4", ")", ".", "Info", "(", "\"openstack.Routes() called\"", ")", "\n", "network", ",", "err", ":=", "os", ".", "NewNetworkV2", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "false", "\n", "}", "\n", "netExts", ",", "err", ":=", "networkExtensions", "(", "network", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Warningf", "(", "\"Failed to list neutron extensions: %v\"", ",", "err", ")", "\n", "return", "nil", ",", "false", "\n", "}", "\n", "if", "!", "netExts", "[", "\"extraroute\"", "]", "{", "glog", ".", "V", "(", "3", ")", ".", "Infof", "(", "\"Neutron extraroute extension not found, required for Routes support\"", ")", "\n", "return", "nil", ",", "false", "\n", "}", "\n", "compute", ",", "err", ":=", "os", ".", "NewComputeV2", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "false", "\n", "}", "\n", "r", ",", "err", ":=", "NewRoutes", "(", "compute", ",", "network", ",", "os", ".", "routeOpts", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Warningf", "(", "\"Error initialising Routes support: %v\"", ",", "err", ")", "\n", "return", "nil", ",", "false", "\n", "}", "\n", "glog", ".", "V", "(", "1", ")", ".", "Info", "(", "\"Claiming to support Routes\"", ")", "\n", "return", "r", ",", "true", "\n", "}" ]
// Routes returns cloud provider routes
[ "Routes", "returns", "cloud", "provider", "routes" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack.go#L497-L530
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/openstack/openstack.go
Zones
func (os *OpenStack) Zones() (cloudprovider.Zones, bool) { glog.V(1).Info("Claiming to support Zones") return os, true }
go
func (os *OpenStack) Zones() (cloudprovider.Zones, bool) { glog.V(1).Info("Claiming to support Zones") return os, true }
[ "func", "(", "os", "*", "OpenStack", ")", "Zones", "(", ")", "(", "cloudprovider", ".", "Zones", ",", "bool", ")", "{", "glog", ".", "V", "(", "1", ")", ".", "Info", "(", "\"Claiming to support Zones\"", ")", "\n", "return", "os", ",", "true", "\n", "}" ]
// Zones returns cloud provider zones
[ "Zones", "returns", "cloud", "provider", "zones" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack.go#L533-L537
train
kubernetes-incubator/external-storage
snapshot/pkg/cloudprovider/providers/openstack/openstack.go
GetZone
func (os *OpenStack) GetZone() (cloudprovider.Zone, error) { md, err := getMetadata() if err != nil { return cloudprovider.Zone{}, err } zone := cloudprovider.Zone{ FailureDomain: md.AvailabilityZone, Region: os.region, } glog.V(1).Infof("Current zone is %v", zone) return zone, nil }
go
func (os *OpenStack) GetZone() (cloudprovider.Zone, error) { md, err := getMetadata() if err != nil { return cloudprovider.Zone{}, err } zone := cloudprovider.Zone{ FailureDomain: md.AvailabilityZone, Region: os.region, } glog.V(1).Infof("Current zone is %v", zone) return zone, nil }
[ "func", "(", "os", "*", "OpenStack", ")", "GetZone", "(", ")", "(", "cloudprovider", ".", "Zone", ",", "error", ")", "{", "md", ",", "err", ":=", "getMetadata", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "cloudprovider", ".", "Zone", "{", "}", ",", "err", "\n", "}", "\n", "zone", ":=", "cloudprovider", ".", "Zone", "{", "FailureDomain", ":", "md", ".", "AvailabilityZone", ",", "Region", ":", "os", ".", "region", ",", "}", "\n", "glog", ".", "V", "(", "1", ")", ".", "Infof", "(", "\"Current zone is %v\"", ",", "zone", ")", "\n", "return", "zone", ",", "nil", "\n", "}" ]
// GetZone gets a zone from cloud provider
[ "GetZone", "gets", "a", "zone", "from", "cloud", "provider" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack.go#L540-L553
train
kubernetes-incubator/external-storage
snapshot/pkg/controller/snapshotter/snapshotter.go
NewVolumeSnapshotter
func NewVolumeSnapshotter( restClient *rest.RESTClient, scheme *runtime.Scheme, clientset kubernetes.Interface, asw cache.ActualStateOfWorld, volumePlugins *map[string]volume.Plugin) VolumeSnapshotter { return &volumeSnapshotter{ restClient: restClient, coreClient: clientset, scheme: scheme, actualStateOfWorld: asw, runningOperation: goroutinemap.NewGoRoutineMap(defaultExponentialBackOffOnError), volumePlugins: volumePlugins, } }
go
func NewVolumeSnapshotter( restClient *rest.RESTClient, scheme *runtime.Scheme, clientset kubernetes.Interface, asw cache.ActualStateOfWorld, volumePlugins *map[string]volume.Plugin) VolumeSnapshotter { return &volumeSnapshotter{ restClient: restClient, coreClient: clientset, scheme: scheme, actualStateOfWorld: asw, runningOperation: goroutinemap.NewGoRoutineMap(defaultExponentialBackOffOnError), volumePlugins: volumePlugins, } }
[ "func", "NewVolumeSnapshotter", "(", "restClient", "*", "rest", ".", "RESTClient", ",", "scheme", "*", "runtime", ".", "Scheme", ",", "clientset", "kubernetes", ".", "Interface", ",", "asw", "cache", ".", "ActualStateOfWorld", ",", "volumePlugins", "*", "map", "[", "string", "]", "volume", ".", "Plugin", ")", "VolumeSnapshotter", "{", "return", "&", "volumeSnapshotter", "{", "restClient", ":", "restClient", ",", "coreClient", ":", "clientset", ",", "scheme", ":", "scheme", ",", "actualStateOfWorld", ":", "asw", ",", "runningOperation", ":", "goroutinemap", ".", "NewGoRoutineMap", "(", "defaultExponentialBackOffOnError", ")", ",", "volumePlugins", ":", "volumePlugins", ",", "}", "\n", "}" ]
// NewVolumeSnapshotter create a new VolumeSnapshotter
[ "NewVolumeSnapshotter", "create", "a", "new", "VolumeSnapshotter" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/controller/snapshotter/snapshotter.go#L100-L114
train
kubernetes-incubator/external-storage
snapshot/pkg/controller/snapshotter/snapshotter.go
getPVFromVolumeSnapshot
func (vs *volumeSnapshotter) getPVFromVolumeSnapshot(uniqueSnapshotName string, snapshot *crdv1.VolumeSnapshot) (*v1.PersistentVolume, error) { pvcName := snapshot.Spec.PersistentVolumeClaimName if pvcName == "" { return nil, fmt.Errorf("The PVC name is not specified in snapshot %s", uniqueSnapshotName) } pvc, err := vs.coreClient.CoreV1().PersistentVolumeClaims(snapshot.Metadata.Namespace).Get(pvcName, metav1.GetOptions{}) if err != nil { return nil, fmt.Errorf("Failed to retrieve PVC %s from the API server: %q", pvcName, err) } if pvc.Status.Phase != v1.ClaimBound { return nil, fmt.Errorf("The PVC %s not yet bound to a PV, will not attempt to take a snapshot yet", pvcName) } pvName := pvc.Spec.VolumeName pv, err := vs.getPVFromName(pvName) if err != nil { return nil, fmt.Errorf("Failed to retrieve PV %s from the API server: %q", pvName, err) } return pv, nil }
go
func (vs *volumeSnapshotter) getPVFromVolumeSnapshot(uniqueSnapshotName string, snapshot *crdv1.VolumeSnapshot) (*v1.PersistentVolume, error) { pvcName := snapshot.Spec.PersistentVolumeClaimName if pvcName == "" { return nil, fmt.Errorf("The PVC name is not specified in snapshot %s", uniqueSnapshotName) } pvc, err := vs.coreClient.CoreV1().PersistentVolumeClaims(snapshot.Metadata.Namespace).Get(pvcName, metav1.GetOptions{}) if err != nil { return nil, fmt.Errorf("Failed to retrieve PVC %s from the API server: %q", pvcName, err) } if pvc.Status.Phase != v1.ClaimBound { return nil, fmt.Errorf("The PVC %s not yet bound to a PV, will not attempt to take a snapshot yet", pvcName) } pvName := pvc.Spec.VolumeName pv, err := vs.getPVFromName(pvName) if err != nil { return nil, fmt.Errorf("Failed to retrieve PV %s from the API server: %q", pvName, err) } return pv, nil }
[ "func", "(", "vs", "*", "volumeSnapshotter", ")", "getPVFromVolumeSnapshot", "(", "uniqueSnapshotName", "string", ",", "snapshot", "*", "crdv1", ".", "VolumeSnapshot", ")", "(", "*", "v1", ".", "PersistentVolume", ",", "error", ")", "{", "pvcName", ":=", "snapshot", ".", "Spec", ".", "PersistentVolumeClaimName", "\n", "if", "pvcName", "==", "\"\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"The PVC name is not specified in snapshot %s\"", ",", "uniqueSnapshotName", ")", "\n", "}", "\n", "pvc", ",", "err", ":=", "vs", ".", "coreClient", ".", "CoreV1", "(", ")", ".", "PersistentVolumeClaims", "(", "snapshot", ".", "Metadata", ".", "Namespace", ")", ".", "Get", "(", "pvcName", ",", "metav1", ".", "GetOptions", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Failed to retrieve PVC %s from the API server: %q\"", ",", "pvcName", ",", "err", ")", "\n", "}", "\n", "if", "pvc", ".", "Status", ".", "Phase", "!=", "v1", ".", "ClaimBound", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"The PVC %s not yet bound to a PV, will not attempt to take a snapshot yet\"", ",", "pvcName", ")", "\n", "}", "\n", "pvName", ":=", "pvc", ".", "Spec", ".", "VolumeName", "\n", "pv", ",", "err", ":=", "vs", ".", "getPVFromName", "(", "pvName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Failed to retrieve PV %s from the API server: %q\"", ",", "pvName", ",", "err", ")", "\n", "}", "\n", "return", "pv", ",", "nil", "\n", "}" ]
// Helper function to get PV from VolumeSnapshot
[ "Helper", "function", "to", "get", "PV", "from", "VolumeSnapshot" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/controller/snapshotter/snapshotter.go#L117-L137
train
kubernetes-incubator/external-storage
snapshot/pkg/controller/snapshotter/snapshotter.go
getPVFromName
func (vs *volumeSnapshotter) getPVFromName(pvName string) (*v1.PersistentVolume, error) { return vs.coreClient.CoreV1().PersistentVolumes().Get(pvName, metav1.GetOptions{}) }
go
func (vs *volumeSnapshotter) getPVFromName(pvName string) (*v1.PersistentVolume, error) { return vs.coreClient.CoreV1().PersistentVolumes().Get(pvName, metav1.GetOptions{}) }
[ "func", "(", "vs", "*", "volumeSnapshotter", ")", "getPVFromName", "(", "pvName", "string", ")", "(", "*", "v1", ".", "PersistentVolume", ",", "error", ")", "{", "return", "vs", ".", "coreClient", ".", "CoreV1", "(", ")", ".", "PersistentVolumes", "(", ")", ".", "Get", "(", "pvName", ",", "metav1", ".", "GetOptions", "{", "}", ")", "\n", "}" ]
// Helper function to get PV from PV name
[ "Helper", "function", "to", "get", "PV", "from", "PV", "name" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/controller/snapshotter/snapshotter.go#L140-L142
train
kubernetes-incubator/external-storage
snapshot/pkg/controller/snapshotter/snapshotter.go
getSnapshotDataFromSnapshot
func (vs *volumeSnapshotter) getSnapshotDataFromSnapshot(snapshot *crdv1.VolumeSnapshot) (*crdv1.VolumeSnapshotData, error) { var snapshotDataObj crdv1.VolumeSnapshotData snapshotDataName := snapshot.Spec.SnapshotDataName if snapshotDataName == "" { return nil, fmt.Errorf("Could not find snapshot data object: SnapshotDataName in snapshot spec is empty") } err := vs.restClient.Get(). Name(snapshotDataName). Resource(crdv1.VolumeSnapshotDataResourcePlural). Do().Into(&snapshotDataObj) if err != nil { glog.Errorf("Error retrieving the VolumeSnapshotData objects from API server: %v", err) return nil, fmt.Errorf("Could not get snapshot data object %s: %v", snapshotDataName, err) } return &snapshotDataObj, nil }
go
func (vs *volumeSnapshotter) getSnapshotDataFromSnapshot(snapshot *crdv1.VolumeSnapshot) (*crdv1.VolumeSnapshotData, error) { var snapshotDataObj crdv1.VolumeSnapshotData snapshotDataName := snapshot.Spec.SnapshotDataName if snapshotDataName == "" { return nil, fmt.Errorf("Could not find snapshot data object: SnapshotDataName in snapshot spec is empty") } err := vs.restClient.Get(). Name(snapshotDataName). Resource(crdv1.VolumeSnapshotDataResourcePlural). Do().Into(&snapshotDataObj) if err != nil { glog.Errorf("Error retrieving the VolumeSnapshotData objects from API server: %v", err) return nil, fmt.Errorf("Could not get snapshot data object %s: %v", snapshotDataName, err) } return &snapshotDataObj, nil }
[ "func", "(", "vs", "*", "volumeSnapshotter", ")", "getSnapshotDataFromSnapshot", "(", "snapshot", "*", "crdv1", ".", "VolumeSnapshot", ")", "(", "*", "crdv1", ".", "VolumeSnapshotData", ",", "error", ")", "{", "var", "snapshotDataObj", "crdv1", ".", "VolumeSnapshotData", "\n", "snapshotDataName", ":=", "snapshot", ".", "Spec", ".", "SnapshotDataName", "\n", "if", "snapshotDataName", "==", "\"\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Could not find snapshot data object: SnapshotDataName in snapshot spec is empty\"", ")", "\n", "}", "\n", "err", ":=", "vs", ".", "restClient", ".", "Get", "(", ")", ".", "Name", "(", "snapshotDataName", ")", ".", "Resource", "(", "crdv1", ".", "VolumeSnapshotDataResourcePlural", ")", ".", "Do", "(", ")", ".", "Into", "(", "&", "snapshotDataObj", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Errorf", "(", "\"Error retrieving the VolumeSnapshotData objects from API server: %v\"", ",", "err", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Could not get snapshot data object %s: %v\"", ",", "snapshotDataName", ",", "err", ")", "\n", "}", "\n", "return", "&", "snapshotDataObj", ",", "nil", "\n", "}" ]
// Helper function that looks up VolumeSnapshotData from a VolumeSnapshot
[ "Helper", "function", "that", "looks", "up", "VolumeSnapshotData", "from", "a", "VolumeSnapshot" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/controller/snapshotter/snapshotter.go#L182-L197
train
kubernetes-incubator/external-storage
snapshot/pkg/controller/snapshotter/snapshotter.go
updateSnapshotIfExists
func (vs *volumeSnapshotter) updateSnapshotIfExists(uniqueSnapshotName string, snapshot *crdv1.VolumeSnapshot) (string, *crdv1.VolumeSnapshot, error) { snapshotName := snapshot.Metadata.Name var snapshotDataObj *crdv1.VolumeSnapshotData var snapshotDataSource *crdv1.VolumeSnapshotDataSource var conditions *[]crdv1.VolumeSnapshotCondition var err error tags := vs.findVolumeSnapshotMetadata(snapshot) // If there is no tag returned, snapshotting is not triggered yet, return new state if tags == nil { glog.Infof("No tag can be found in snapshot metadata %s", uniqueSnapshotName) return statusNew, snapshot, nil } // Check whether snapshotData object is already created or not. If yes, snapshot is already // triggered through cloud provider, bind it and return pending state if snapshotDataObj = vs.getSnapshotDataFromSnapshotName(uniqueSnapshotName); snapshotDataObj != nil { glog.Infof("Find snapshot data object %s from snapshot %s", snapshotDataObj.Metadata.Name, uniqueSnapshotName) snapshotObj, err := vs.bindandUpdateVolumeSnapshot(snapshot, snapshotDataObj.Metadata.Name, nil) if err != nil { return statusError, snapshot, err } return statusPending, snapshotObj, nil } // Find snapshot through cloud provider by existing tags, and create VolumeSnapshotData if such snapshot is found snapshotDataSource, conditions, err = vs.findSnapshotByTags(snapshotName, snapshot) if err != nil { return statusNew, snapshot, nil } // Snapshot is found. Create VolumeSnapshotData, bind VolumeSnapshotData to VolumeSnapshot, and update VolumeSnapshot status glog.Infof("updateSnapshotIfExists: create VolumeSnapshotData object for VolumeSnapshot %s.", uniqueSnapshotName) pvName, ok := snapshot.Metadata.Labels[pvNameLabel] if !ok { return statusError, snapshot, fmt.Errorf("Could not find pv name from snapshot, this should not happen.") } snapshotDataObj, err = vs.createVolumeSnapshotData(snapshotName, pvName, snapshotDataSource, conditions) if err != nil { return statusError, snapshot, err } glog.Infof("updateSnapshotIfExists: update VolumeSnapshot status and bind VolumeSnapshotData to VolumeSnapshot %s.", uniqueSnapshotName) snapshotObj, err := vs.bindandUpdateVolumeSnapshot(snapshot, snapshotDataObj.Metadata.Name, conditions) if err != nil { return statusError, nil, err } return statusPending, snapshotObj, nil }
go
func (vs *volumeSnapshotter) updateSnapshotIfExists(uniqueSnapshotName string, snapshot *crdv1.VolumeSnapshot) (string, *crdv1.VolumeSnapshot, error) { snapshotName := snapshot.Metadata.Name var snapshotDataObj *crdv1.VolumeSnapshotData var snapshotDataSource *crdv1.VolumeSnapshotDataSource var conditions *[]crdv1.VolumeSnapshotCondition var err error tags := vs.findVolumeSnapshotMetadata(snapshot) // If there is no tag returned, snapshotting is not triggered yet, return new state if tags == nil { glog.Infof("No tag can be found in snapshot metadata %s", uniqueSnapshotName) return statusNew, snapshot, nil } // Check whether snapshotData object is already created or not. If yes, snapshot is already // triggered through cloud provider, bind it and return pending state if snapshotDataObj = vs.getSnapshotDataFromSnapshotName(uniqueSnapshotName); snapshotDataObj != nil { glog.Infof("Find snapshot data object %s from snapshot %s", snapshotDataObj.Metadata.Name, uniqueSnapshotName) snapshotObj, err := vs.bindandUpdateVolumeSnapshot(snapshot, snapshotDataObj.Metadata.Name, nil) if err != nil { return statusError, snapshot, err } return statusPending, snapshotObj, nil } // Find snapshot through cloud provider by existing tags, and create VolumeSnapshotData if such snapshot is found snapshotDataSource, conditions, err = vs.findSnapshotByTags(snapshotName, snapshot) if err != nil { return statusNew, snapshot, nil } // Snapshot is found. Create VolumeSnapshotData, bind VolumeSnapshotData to VolumeSnapshot, and update VolumeSnapshot status glog.Infof("updateSnapshotIfExists: create VolumeSnapshotData object for VolumeSnapshot %s.", uniqueSnapshotName) pvName, ok := snapshot.Metadata.Labels[pvNameLabel] if !ok { return statusError, snapshot, fmt.Errorf("Could not find pv name from snapshot, this should not happen.") } snapshotDataObj, err = vs.createVolumeSnapshotData(snapshotName, pvName, snapshotDataSource, conditions) if err != nil { return statusError, snapshot, err } glog.Infof("updateSnapshotIfExists: update VolumeSnapshot status and bind VolumeSnapshotData to VolumeSnapshot %s.", uniqueSnapshotName) snapshotObj, err := vs.bindandUpdateVolumeSnapshot(snapshot, snapshotDataObj.Metadata.Name, conditions) if err != nil { return statusError, nil, err } return statusPending, snapshotObj, nil }
[ "func", "(", "vs", "*", "volumeSnapshotter", ")", "updateSnapshotIfExists", "(", "uniqueSnapshotName", "string", ",", "snapshot", "*", "crdv1", ".", "VolumeSnapshot", ")", "(", "string", ",", "*", "crdv1", ".", "VolumeSnapshot", ",", "error", ")", "{", "snapshotName", ":=", "snapshot", ".", "Metadata", ".", "Name", "\n", "var", "snapshotDataObj", "*", "crdv1", ".", "VolumeSnapshotData", "\n", "var", "snapshotDataSource", "*", "crdv1", ".", "VolumeSnapshotDataSource", "\n", "var", "conditions", "*", "[", "]", "crdv1", ".", "VolumeSnapshotCondition", "\n", "var", "err", "error", "\n", "tags", ":=", "vs", ".", "findVolumeSnapshotMetadata", "(", "snapshot", ")", "\n", "if", "tags", "==", "nil", "{", "glog", ".", "Infof", "(", "\"No tag can be found in snapshot metadata %s\"", ",", "uniqueSnapshotName", ")", "\n", "return", "statusNew", ",", "snapshot", ",", "nil", "\n", "}", "\n", "if", "snapshotDataObj", "=", "vs", ".", "getSnapshotDataFromSnapshotName", "(", "uniqueSnapshotName", ")", ";", "snapshotDataObj", "!=", "nil", "{", "glog", ".", "Infof", "(", "\"Find snapshot data object %s from snapshot %s\"", ",", "snapshotDataObj", ".", "Metadata", ".", "Name", ",", "uniqueSnapshotName", ")", "\n", "snapshotObj", ",", "err", ":=", "vs", ".", "bindandUpdateVolumeSnapshot", "(", "snapshot", ",", "snapshotDataObj", ".", "Metadata", ".", "Name", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "statusError", ",", "snapshot", ",", "err", "\n", "}", "\n", "return", "statusPending", ",", "snapshotObj", ",", "nil", "\n", "}", "\n", "snapshotDataSource", ",", "conditions", ",", "err", "=", "vs", ".", "findSnapshotByTags", "(", "snapshotName", ",", "snapshot", ")", "\n", "if", "err", "!=", "nil", "{", "return", "statusNew", ",", "snapshot", ",", "nil", "\n", "}", "\n", "glog", ".", "Infof", "(", "\"updateSnapshotIfExists: create VolumeSnapshotData object for VolumeSnapshot %s.\"", ",", "uniqueSnapshotName", ")", "\n", "pvName", ",", "ok", ":=", "snapshot", ".", "Metadata", ".", "Labels", "[", "pvNameLabel", "]", "\n", "if", "!", "ok", "{", "return", "statusError", ",", "snapshot", ",", "fmt", ".", "Errorf", "(", "\"Could not find pv name from snapshot, this should not happen.\"", ")", "\n", "}", "\n", "snapshotDataObj", ",", "err", "=", "vs", ".", "createVolumeSnapshotData", "(", "snapshotName", ",", "pvName", ",", "snapshotDataSource", ",", "conditions", ")", "\n", "if", "err", "!=", "nil", "{", "return", "statusError", ",", "snapshot", ",", "err", "\n", "}", "\n", "glog", ".", "Infof", "(", "\"updateSnapshotIfExists: update VolumeSnapshot status and bind VolumeSnapshotData to VolumeSnapshot %s.\"", ",", "uniqueSnapshotName", ")", "\n", "snapshotObj", ",", "err", ":=", "vs", ".", "bindandUpdateVolumeSnapshot", "(", "snapshot", ",", "snapshotDataObj", ".", "Metadata", ".", "Name", ",", "conditions", ")", "\n", "if", "err", "!=", "nil", "{", "return", "statusError", ",", "nil", ",", "err", "\n", "}", "\n", "return", "statusPending", ",", "snapshotObj", ",", "nil", "\n", "}" ]
// Exame the given snapshot in detail and then return the status
[ "Exame", "the", "given", "snapshot", "in", "detail", "and", "then", "return", "the", "status" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/controller/snapshotter/snapshotter.go#L365-L409
train
kubernetes-incubator/external-storage
snapshot/pkg/controller/snapshotter/snapshotter.go
syncSnapshot
func (vs *volumeSnapshotter) syncSnapshot(uniqueSnapshotName string, snapshot *crdv1.VolumeSnapshot) func() error { return func() error { snapshotObj := snapshot status := vs.getSimplifiedSnapshotStatus(snapshot.Status.Conditions) var err error // When the condition is new, it is still possible that snapshot is already triggered but has not yet updated the condition. // Check the metadata and available VolumeSnapshotData objects and update the snapshot accordingly if status == statusNew { status, snapshotObj, err = vs.updateSnapshotIfExists(uniqueSnapshotName, snapshot) if err != nil { glog.Errorf("updateSnapshotIfExists has error %v", err) } } switch status { case statusReady: glog.Infof("Snapshot %s created successfully. Adding it to Actual State of World.", uniqueSnapshotName) vs.actualStateOfWorld.AddSnapshot(snapshot) return nil case statusError: glog.Infof("syncSnapshot: Error creating snapshot %s.", uniqueSnapshotName) return fmt.Errorf("Error creating snapshot %s", uniqueSnapshotName) case statusPending: glog.V(4).Infof("syncSnapshot: Snapshot %s is Pending.", uniqueSnapshotName) // Query the volume plugin for the status of the snapshot with snapshot id // from VolumeSnapshotData object. snapshotDataObj, err := vs.getSnapshotDataFromSnapshot(snapshotObj) if err != nil { return fmt.Errorf("Failed to find snapshot %v", err) } err = vs.waitForSnapshot(uniqueSnapshotName, snapshotObj, snapshotDataObj) if err != nil { return fmt.Errorf("Failed to check snapshot state %s with error %v", uniqueSnapshotName, err) } glog.Infof("syncSnapshot: Snapshot %s created successfully.", uniqueSnapshotName) return nil case statusNew: glog.Infof("syncSnapshot: Creating snapshot %s ...", uniqueSnapshotName) err = vs.createSnapshot(uniqueSnapshotName, snapshotObj) return err } return fmt.Errorf("Error occurred when creating snapshot %s, unknown status %s", uniqueSnapshotName, status) } }
go
func (vs *volumeSnapshotter) syncSnapshot(uniqueSnapshotName string, snapshot *crdv1.VolumeSnapshot) func() error { return func() error { snapshotObj := snapshot status := vs.getSimplifiedSnapshotStatus(snapshot.Status.Conditions) var err error // When the condition is new, it is still possible that snapshot is already triggered but has not yet updated the condition. // Check the metadata and available VolumeSnapshotData objects and update the snapshot accordingly if status == statusNew { status, snapshotObj, err = vs.updateSnapshotIfExists(uniqueSnapshotName, snapshot) if err != nil { glog.Errorf("updateSnapshotIfExists has error %v", err) } } switch status { case statusReady: glog.Infof("Snapshot %s created successfully. Adding it to Actual State of World.", uniqueSnapshotName) vs.actualStateOfWorld.AddSnapshot(snapshot) return nil case statusError: glog.Infof("syncSnapshot: Error creating snapshot %s.", uniqueSnapshotName) return fmt.Errorf("Error creating snapshot %s", uniqueSnapshotName) case statusPending: glog.V(4).Infof("syncSnapshot: Snapshot %s is Pending.", uniqueSnapshotName) // Query the volume plugin for the status of the snapshot with snapshot id // from VolumeSnapshotData object. snapshotDataObj, err := vs.getSnapshotDataFromSnapshot(snapshotObj) if err != nil { return fmt.Errorf("Failed to find snapshot %v", err) } err = vs.waitForSnapshot(uniqueSnapshotName, snapshotObj, snapshotDataObj) if err != nil { return fmt.Errorf("Failed to check snapshot state %s with error %v", uniqueSnapshotName, err) } glog.Infof("syncSnapshot: Snapshot %s created successfully.", uniqueSnapshotName) return nil case statusNew: glog.Infof("syncSnapshot: Creating snapshot %s ...", uniqueSnapshotName) err = vs.createSnapshot(uniqueSnapshotName, snapshotObj) return err } return fmt.Errorf("Error occurred when creating snapshot %s, unknown status %s", uniqueSnapshotName, status) } }
[ "func", "(", "vs", "*", "volumeSnapshotter", ")", "syncSnapshot", "(", "uniqueSnapshotName", "string", ",", "snapshot", "*", "crdv1", ".", "VolumeSnapshot", ")", "func", "(", ")", "error", "{", "return", "func", "(", ")", "error", "{", "snapshotObj", ":=", "snapshot", "\n", "status", ":=", "vs", ".", "getSimplifiedSnapshotStatus", "(", "snapshot", ".", "Status", ".", "Conditions", ")", "\n", "var", "err", "error", "\n", "if", "status", "==", "statusNew", "{", "status", ",", "snapshotObj", ",", "err", "=", "vs", ".", "updateSnapshotIfExists", "(", "uniqueSnapshotName", ",", "snapshot", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Errorf", "(", "\"updateSnapshotIfExists has error %v\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "switch", "status", "{", "case", "statusReady", ":", "glog", ".", "Infof", "(", "\"Snapshot %s created successfully. Adding it to Actual State of World.\"", ",", "uniqueSnapshotName", ")", "\n", "vs", ".", "actualStateOfWorld", ".", "AddSnapshot", "(", "snapshot", ")", "\n", "return", "nil", "\n", "case", "statusError", ":", "glog", ".", "Infof", "(", "\"syncSnapshot: Error creating snapshot %s.\"", ",", "uniqueSnapshotName", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"Error creating snapshot %s\"", ",", "uniqueSnapshotName", ")", "\n", "case", "statusPending", ":", "glog", ".", "V", "(", "4", ")", ".", "Infof", "(", "\"syncSnapshot: Snapshot %s is Pending.\"", ",", "uniqueSnapshotName", ")", "\n", "snapshotDataObj", ",", "err", ":=", "vs", ".", "getSnapshotDataFromSnapshot", "(", "snapshotObj", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Failed to find snapshot %v\"", ",", "err", ")", "\n", "}", "\n", "err", "=", "vs", ".", "waitForSnapshot", "(", "uniqueSnapshotName", ",", "snapshotObj", ",", "snapshotDataObj", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Failed to check snapshot state %s with error %v\"", ",", "uniqueSnapshotName", ",", "err", ")", "\n", "}", "\n", "glog", ".", "Infof", "(", "\"syncSnapshot: Snapshot %s created successfully.\"", ",", "uniqueSnapshotName", ")", "\n", "return", "nil", "\n", "case", "statusNew", ":", "glog", ".", "Infof", "(", "\"syncSnapshot: Creating snapshot %s ...\"", ",", "uniqueSnapshotName", ")", "\n", "err", "=", "vs", ".", "createSnapshot", "(", "uniqueSnapshotName", ",", "snapshotObj", ")", "\n", "return", "err", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"Error occurred when creating snapshot %s, unknown status %s\"", ",", "uniqueSnapshotName", ",", "status", ")", "\n", "}", "\n", "}" ]
// Below are the closures meant to build the functions for the GoRoutineMap operations. // syncSnapshot is the main controller method to decide what to do to create a snapshot.
[ "Below", "are", "the", "closures", "meant", "to", "build", "the", "functions", "for", "the", "GoRoutineMap", "operations", ".", "syncSnapshot", "is", "the", "main", "controller", "method", "to", "decide", "what", "to", "do", "to", "create", "a", "snapshot", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/controller/snapshotter/snapshotter.go#L413-L455
train
kubernetes-incubator/external-storage
snapshot/pkg/controller/snapshotter/snapshotter.go
createSnapshot
func (vs *volumeSnapshotter) createSnapshot(uniqueSnapshotName string, snapshot *crdv1.VolumeSnapshot) error { var snapshotDataSource *crdv1.VolumeSnapshotDataSource var snapStatus *[]crdv1.VolumeSnapshotCondition var err error var tags *map[string]string glog.Infof("createSnapshot: Creating snapshot %s through the plugin ...", uniqueSnapshotName) pv, err := vs.getPVFromVolumeSnapshot(uniqueSnapshotName, snapshot) if err != nil { return err } glog.Infof("createSnapshot: Creating metadata for snapshot %s.", uniqueSnapshotName) tags, err = vs.updateVolumeSnapshotMetadata(snapshot, pv.Name) if err != nil { return fmt.Errorf("Failed to update metadata for volume snapshot %s: %q", uniqueSnapshotName, err) } snapshotDataSource, snapStatus, err = vs.takeSnapshot(snapshot, pv, tags) if err != nil || snapshotDataSource == nil { return fmt.Errorf("Failed to take snapshot of the volume %s: %q", pv.Name, err) } glog.Infof("createSnapshot: create VolumeSnapshotData object for VolumeSnapshot %s.", uniqueSnapshotName) snapshotDataObj, err := vs.createVolumeSnapshotData(uniqueSnapshotName, pv.Name, snapshotDataSource, snapStatus) if err != nil { return err } glog.Infof("createSnapshot: Update VolumeSnapshot status and bind VolumeSnapshotData to VolumeSnapshot %s.", uniqueSnapshotName) snapshotObj, err := vs.bindandUpdateVolumeSnapshot(snapshot, snapshotDataObj.Metadata.Name, snapStatus) if err != nil { glog.Errorf("createSnapshot: Error updating volume snapshot %s: %v", uniqueSnapshotName, err) return fmt.Errorf("Failed to update VolumeSnapshot for snapshot %s", uniqueSnapshotName) } // Waiting for snapshot to be ready err = vs.waitForSnapshot(uniqueSnapshotName, snapshotObj, snapshotDataObj) if err != nil { return fmt.Errorf("Failed to create snapshot %s with error %v", uniqueSnapshotName, err) } glog.Infof("createSnapshot: Snapshot %s created successfully.", uniqueSnapshotName) return nil }
go
func (vs *volumeSnapshotter) createSnapshot(uniqueSnapshotName string, snapshot *crdv1.VolumeSnapshot) error { var snapshotDataSource *crdv1.VolumeSnapshotDataSource var snapStatus *[]crdv1.VolumeSnapshotCondition var err error var tags *map[string]string glog.Infof("createSnapshot: Creating snapshot %s through the plugin ...", uniqueSnapshotName) pv, err := vs.getPVFromVolumeSnapshot(uniqueSnapshotName, snapshot) if err != nil { return err } glog.Infof("createSnapshot: Creating metadata for snapshot %s.", uniqueSnapshotName) tags, err = vs.updateVolumeSnapshotMetadata(snapshot, pv.Name) if err != nil { return fmt.Errorf("Failed to update metadata for volume snapshot %s: %q", uniqueSnapshotName, err) } snapshotDataSource, snapStatus, err = vs.takeSnapshot(snapshot, pv, tags) if err != nil || snapshotDataSource == nil { return fmt.Errorf("Failed to take snapshot of the volume %s: %q", pv.Name, err) } glog.Infof("createSnapshot: create VolumeSnapshotData object for VolumeSnapshot %s.", uniqueSnapshotName) snapshotDataObj, err := vs.createVolumeSnapshotData(uniqueSnapshotName, pv.Name, snapshotDataSource, snapStatus) if err != nil { return err } glog.Infof("createSnapshot: Update VolumeSnapshot status and bind VolumeSnapshotData to VolumeSnapshot %s.", uniqueSnapshotName) snapshotObj, err := vs.bindandUpdateVolumeSnapshot(snapshot, snapshotDataObj.Metadata.Name, snapStatus) if err != nil { glog.Errorf("createSnapshot: Error updating volume snapshot %s: %v", uniqueSnapshotName, err) return fmt.Errorf("Failed to update VolumeSnapshot for snapshot %s", uniqueSnapshotName) } // Waiting for snapshot to be ready err = vs.waitForSnapshot(uniqueSnapshotName, snapshotObj, snapshotDataObj) if err != nil { return fmt.Errorf("Failed to create snapshot %s with error %v", uniqueSnapshotName, err) } glog.Infof("createSnapshot: Snapshot %s created successfully.", uniqueSnapshotName) return nil }
[ "func", "(", "vs", "*", "volumeSnapshotter", ")", "createSnapshot", "(", "uniqueSnapshotName", "string", ",", "snapshot", "*", "crdv1", ".", "VolumeSnapshot", ")", "error", "{", "var", "snapshotDataSource", "*", "crdv1", ".", "VolumeSnapshotDataSource", "\n", "var", "snapStatus", "*", "[", "]", "crdv1", ".", "VolumeSnapshotCondition", "\n", "var", "err", "error", "\n", "var", "tags", "*", "map", "[", "string", "]", "string", "\n", "glog", ".", "Infof", "(", "\"createSnapshot: Creating snapshot %s through the plugin ...\"", ",", "uniqueSnapshotName", ")", "\n", "pv", ",", "err", ":=", "vs", ".", "getPVFromVolumeSnapshot", "(", "uniqueSnapshotName", ",", "snapshot", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "glog", ".", "Infof", "(", "\"createSnapshot: Creating metadata for snapshot %s.\"", ",", "uniqueSnapshotName", ")", "\n", "tags", ",", "err", "=", "vs", ".", "updateVolumeSnapshotMetadata", "(", "snapshot", ",", "pv", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Failed to update metadata for volume snapshot %s: %q\"", ",", "uniqueSnapshotName", ",", "err", ")", "\n", "}", "\n", "snapshotDataSource", ",", "snapStatus", ",", "err", "=", "vs", ".", "takeSnapshot", "(", "snapshot", ",", "pv", ",", "tags", ")", "\n", "if", "err", "!=", "nil", "||", "snapshotDataSource", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Failed to take snapshot of the volume %s: %q\"", ",", "pv", ".", "Name", ",", "err", ")", "\n", "}", "\n", "glog", ".", "Infof", "(", "\"createSnapshot: create VolumeSnapshotData object for VolumeSnapshot %s.\"", ",", "uniqueSnapshotName", ")", "\n", "snapshotDataObj", ",", "err", ":=", "vs", ".", "createVolumeSnapshotData", "(", "uniqueSnapshotName", ",", "pv", ".", "Name", ",", "snapshotDataSource", ",", "snapStatus", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "glog", ".", "Infof", "(", "\"createSnapshot: Update VolumeSnapshot status and bind VolumeSnapshotData to VolumeSnapshot %s.\"", ",", "uniqueSnapshotName", ")", "\n", "snapshotObj", ",", "err", ":=", "vs", ".", "bindandUpdateVolumeSnapshot", "(", "snapshot", ",", "snapshotDataObj", ".", "Metadata", ".", "Name", ",", "snapStatus", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Errorf", "(", "\"createSnapshot: Error updating volume snapshot %s: %v\"", ",", "uniqueSnapshotName", ",", "err", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"Failed to update VolumeSnapshot for snapshot %s\"", ",", "uniqueSnapshotName", ")", "\n", "}", "\n", "err", "=", "vs", ".", "waitForSnapshot", "(", "uniqueSnapshotName", ",", "snapshotObj", ",", "snapshotDataObj", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Failed to create snapshot %s with error %v\"", ",", "uniqueSnapshotName", ",", "err", ")", "\n", "}", "\n", "glog", ".", "Infof", "(", "\"createSnapshot: Snapshot %s created successfully.\"", ",", "uniqueSnapshotName", ")", "\n", "return", "nil", "\n", "}" ]
// The function goes through the whole snapshot creation process. // 1. Update VolumeSnapshot metadata to include the snapshotted PV name, timestamp and snapshot uid, also generate tag for cloud provider // 2. Trigger the snapshot through cloud provider and attach the tag to the snapshot. // 3. Create the VolumeSnapshotData object with the snapshot id information returned from step 2. // 4. Bind the VolumeSnapshot and VolumeSnapshotData object // 5. Query the snapshot status through cloud provider and update the status until snapshot is ready or fails.
[ "The", "function", "goes", "through", "the", "whole", "snapshot", "creation", "process", ".", "1", ".", "Update", "VolumeSnapshot", "metadata", "to", "include", "the", "snapshotted", "PV", "name", "timestamp", "and", "snapshot", "uid", "also", "generate", "tag", "for", "cloud", "provider", "2", ".", "Trigger", "the", "snapshot", "through", "cloud", "provider", "and", "attach", "the", "tag", "to", "the", "snapshot", ".", "3", ".", "Create", "the", "VolumeSnapshotData", "object", "with", "the", "snapshot", "id", "information", "returned", "from", "step", "2", ".", "4", ".", "Bind", "the", "VolumeSnapshot", "and", "VolumeSnapshotData", "object", "5", ".", "Query", "the", "snapshot", "status", "through", "cloud", "provider", "and", "update", "the", "status", "until", "snapshot", "is", "ready", "or", "fails", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/controller/snapshotter/snapshotter.go#L486-L528
train
kubernetes-incubator/external-storage
snapshot/pkg/controller/snapshotter/snapshotter.go
updateVolumeSnapshotMetadata
func (vs *volumeSnapshotter) updateVolumeSnapshotMetadata(snapshot *crdv1.VolumeSnapshot, pvName string) (*map[string]string, error) { glog.Infof("In updateVolumeSnapshotMetadata") var snapshotObj crdv1.VolumeSnapshot // Need to get a fresh copy of the VolumeSnapshot from the API server err := vs.restClient.Get(). Name(snapshot.Metadata.Name). Resource(crdv1.VolumeSnapshotResourcePlural). Namespace(snapshot.Metadata.Namespace). Do().Into(&snapshotObj) if err != nil { return nil, fmt.Errorf("Error retrieving VolumeSnapshot %s from API server: %v", snapshot.Metadata.Name, err) } // Copy the snapshot object before updating it snapshotCopy := snapshotObj.DeepCopy() if snapshotCopy.Metadata.Labels == nil { snapshotCopy.Metadata.Labels = make(map[string]string) } snapshotCopy.Metadata.Labels[snapshotMetadataTimeStamp] = fmt.Sprintf("%d", time.Now().UnixNano()) snapshotCopy.Metadata.Labels[snapshotMetadataPVName] = pvName glog.Infof("updateVolumeSnapshotMetadata: Metadata UID: %s Metadata Name: %s Metadata Namespace: %s Setting tags in Metadata Labels: %#v.", snapshotCopy.Metadata.UID, snapshotCopy.Metadata.Name, snapshotCopy.Metadata.Namespace, snapshotCopy.Metadata.Labels) // TODO: Use Patch instead of Put to update the object? var result crdv1.VolumeSnapshot err = vs.restClient.Put(). Name(snapshot.Metadata.Name). Resource(crdv1.VolumeSnapshotResourcePlural). Namespace(snapshot.Metadata.Namespace). Body(snapshotCopy). Do().Into(&result) if err != nil { return nil, fmt.Errorf("Error updating snapshot object %s/%s on the API server: %v", snapshot.Metadata.Namespace, snapshot.Metadata.Name, err) } cloudTags := make(map[string]string) cloudTags[CloudSnapshotCreatedForVolumeSnapshotNamespaceTag] = result.Metadata.Namespace cloudTags[CloudSnapshotCreatedForVolumeSnapshotNameTag] = result.Metadata.Name cloudTags[CloudSnapshotCreatedForVolumeSnapshotUIDTag] = fmt.Sprintf("%v", result.Metadata.UID) cloudTags[CloudSnapshotCreatedForVolumeSnapshotTimestampTag] = result.Metadata.Labels[snapshotMetadataTimeStamp] glog.Infof("updateVolumeSnapshotMetadata: returning cloudTags [%#v]", cloudTags) return &cloudTags, nil }
go
func (vs *volumeSnapshotter) updateVolumeSnapshotMetadata(snapshot *crdv1.VolumeSnapshot, pvName string) (*map[string]string, error) { glog.Infof("In updateVolumeSnapshotMetadata") var snapshotObj crdv1.VolumeSnapshot // Need to get a fresh copy of the VolumeSnapshot from the API server err := vs.restClient.Get(). Name(snapshot.Metadata.Name). Resource(crdv1.VolumeSnapshotResourcePlural). Namespace(snapshot.Metadata.Namespace). Do().Into(&snapshotObj) if err != nil { return nil, fmt.Errorf("Error retrieving VolumeSnapshot %s from API server: %v", snapshot.Metadata.Name, err) } // Copy the snapshot object before updating it snapshotCopy := snapshotObj.DeepCopy() if snapshotCopy.Metadata.Labels == nil { snapshotCopy.Metadata.Labels = make(map[string]string) } snapshotCopy.Metadata.Labels[snapshotMetadataTimeStamp] = fmt.Sprintf("%d", time.Now().UnixNano()) snapshotCopy.Metadata.Labels[snapshotMetadataPVName] = pvName glog.Infof("updateVolumeSnapshotMetadata: Metadata UID: %s Metadata Name: %s Metadata Namespace: %s Setting tags in Metadata Labels: %#v.", snapshotCopy.Metadata.UID, snapshotCopy.Metadata.Name, snapshotCopy.Metadata.Namespace, snapshotCopy.Metadata.Labels) // TODO: Use Patch instead of Put to update the object? var result crdv1.VolumeSnapshot err = vs.restClient.Put(). Name(snapshot.Metadata.Name). Resource(crdv1.VolumeSnapshotResourcePlural). Namespace(snapshot.Metadata.Namespace). Body(snapshotCopy). Do().Into(&result) if err != nil { return nil, fmt.Errorf("Error updating snapshot object %s/%s on the API server: %v", snapshot.Metadata.Namespace, snapshot.Metadata.Name, err) } cloudTags := make(map[string]string) cloudTags[CloudSnapshotCreatedForVolumeSnapshotNamespaceTag] = result.Metadata.Namespace cloudTags[CloudSnapshotCreatedForVolumeSnapshotNameTag] = result.Metadata.Name cloudTags[CloudSnapshotCreatedForVolumeSnapshotUIDTag] = fmt.Sprintf("%v", result.Metadata.UID) cloudTags[CloudSnapshotCreatedForVolumeSnapshotTimestampTag] = result.Metadata.Labels[snapshotMetadataTimeStamp] glog.Infof("updateVolumeSnapshotMetadata: returning cloudTags [%#v]", cloudTags) return &cloudTags, nil }
[ "func", "(", "vs", "*", "volumeSnapshotter", ")", "updateVolumeSnapshotMetadata", "(", "snapshot", "*", "crdv1", ".", "VolumeSnapshot", ",", "pvName", "string", ")", "(", "*", "map", "[", "string", "]", "string", ",", "error", ")", "{", "glog", ".", "Infof", "(", "\"In updateVolumeSnapshotMetadata\"", ")", "\n", "var", "snapshotObj", "crdv1", ".", "VolumeSnapshot", "\n", "err", ":=", "vs", ".", "restClient", ".", "Get", "(", ")", ".", "Name", "(", "snapshot", ".", "Metadata", ".", "Name", ")", ".", "Resource", "(", "crdv1", ".", "VolumeSnapshotResourcePlural", ")", ".", "Namespace", "(", "snapshot", ".", "Metadata", ".", "Namespace", ")", ".", "Do", "(", ")", ".", "Into", "(", "&", "snapshotObj", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Error retrieving VolumeSnapshot %s from API server: %v\"", ",", "snapshot", ".", "Metadata", ".", "Name", ",", "err", ")", "\n", "}", "\n", "snapshotCopy", ":=", "snapshotObj", ".", "DeepCopy", "(", ")", "\n", "if", "snapshotCopy", ".", "Metadata", ".", "Labels", "==", "nil", "{", "snapshotCopy", ".", "Metadata", ".", "Labels", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "}", "\n", "snapshotCopy", ".", "Metadata", ".", "Labels", "[", "snapshotMetadataTimeStamp", "]", "=", "fmt", ".", "Sprintf", "(", "\"%d\"", ",", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", "\n", "snapshotCopy", ".", "Metadata", ".", "Labels", "[", "snapshotMetadataPVName", "]", "=", "pvName", "\n", "glog", ".", "Infof", "(", "\"updateVolumeSnapshotMetadata: Metadata UID: %s Metadata Name: %s Metadata Namespace: %s Setting tags in Metadata Labels: %#v.\"", ",", "snapshotCopy", ".", "Metadata", ".", "UID", ",", "snapshotCopy", ".", "Metadata", ".", "Name", ",", "snapshotCopy", ".", "Metadata", ".", "Namespace", ",", "snapshotCopy", ".", "Metadata", ".", "Labels", ")", "\n", "var", "result", "crdv1", ".", "VolumeSnapshot", "\n", "err", "=", "vs", ".", "restClient", ".", "Put", "(", ")", ".", "Name", "(", "snapshot", ".", "Metadata", ".", "Name", ")", ".", "Resource", "(", "crdv1", ".", "VolumeSnapshotResourcePlural", ")", ".", "Namespace", "(", "snapshot", ".", "Metadata", ".", "Namespace", ")", ".", "Body", "(", "snapshotCopy", ")", ".", "Do", "(", ")", ".", "Into", "(", "&", "result", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Error updating snapshot object %s/%s on the API server: %v\"", ",", "snapshot", ".", "Metadata", ".", "Namespace", ",", "snapshot", ".", "Metadata", ".", "Name", ",", "err", ")", "\n", "}", "\n", "cloudTags", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "cloudTags", "[", "CloudSnapshotCreatedForVolumeSnapshotNamespaceTag", "]", "=", "result", ".", "Metadata", ".", "Namespace", "\n", "cloudTags", "[", "CloudSnapshotCreatedForVolumeSnapshotNameTag", "]", "=", "result", ".", "Metadata", ".", "Name", "\n", "cloudTags", "[", "CloudSnapshotCreatedForVolumeSnapshotUIDTag", "]", "=", "fmt", ".", "Sprintf", "(", "\"%v\"", ",", "result", ".", "Metadata", ".", "UID", ")", "\n", "cloudTags", "[", "CloudSnapshotCreatedForVolumeSnapshotTimestampTag", "]", "=", "result", ".", "Metadata", ".", "Labels", "[", "snapshotMetadataTimeStamp", "]", "\n", "glog", ".", "Infof", "(", "\"updateVolumeSnapshotMetadata: returning cloudTags [%#v]\"", ",", "cloudTags", ")", "\n", "return", "&", "cloudTags", ",", "nil", "\n", "}" ]
// Update VolumeSnapshot object with current timestamp and associated PersistentVolume name in object's metadata
[ "Update", "VolumeSnapshot", "object", "with", "current", "timestamp", "and", "associated", "PersistentVolume", "name", "in", "object", "s", "metadata" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/controller/snapshotter/snapshotter.go#L700-L744
train
kubernetes-incubator/external-storage
snapshot/pkg/controller/snapshotter/snapshotter.go
propagateVolumeSnapshotCondition
func (vs *volumeSnapshotter) propagateVolumeSnapshotCondition(snapshotDataName string, condition *crdv1.VolumeSnapshotCondition) error { var snapshotDataObj crdv1.VolumeSnapshotData err := vs.restClient.Get(). Name(snapshotDataName). Resource(crdv1.VolumeSnapshotDataResourcePlural). Do().Into(&snapshotDataObj) if err != nil { return err } newCondition := &crdv1.VolumeSnapshotDataCondition{ Type: (crdv1.VolumeSnapshotDataConditionType)(condition.Type), Status: condition.Status, Message: condition.Message, LastTransitionTime: condition.LastTransitionTime, } oldStatus := snapshotDataObj.Status.DeepCopy() status := snapshotDataObj.Status isEqual := false if oldStatus.Conditions == nil || len(oldStatus.Conditions) == 0 || newCondition.Type != oldStatus.Conditions[len(oldStatus.Conditions)-1].Type { status.Conditions = append(status.Conditions, *newCondition) } else { oldCondition := oldStatus.Conditions[len(oldStatus.Conditions)-1] if newCondition.Status == oldCondition.Status { newCondition.LastTransitionTime = oldCondition.LastTransitionTime } status.Conditions[len(status.Conditions)-1] = *newCondition isEqual = newCondition.Type == oldCondition.Type && newCondition.Status == oldCondition.Status && newCondition.Reason == oldCondition.Reason && newCondition.Message == oldCondition.Message && newCondition.LastTransitionTime.Equal(&oldCondition.LastTransitionTime) } if !isEqual { var newSnapshotDataObj crdv1.VolumeSnapshotData snapshotDataObj.Status = status if snapshotDataObj.Status.CreationTimestamp.IsZero() && newCondition.Type == crdv1.VolumeSnapshotDataConditionReady { snapshotDataObj.Status.CreationTimestamp = newCondition.LastTransitionTime } err = vs.restClient.Put(). Name(snapshotDataName). Resource(crdv1.VolumeSnapshotDataResourcePlural). Body(&snapshotDataObj). Do().Into(&newSnapshotDataObj) if err != nil { return err } glog.Infof("VolumeSnapshot status propagated to VolumeSnapshotData") return nil } return nil }
go
func (vs *volumeSnapshotter) propagateVolumeSnapshotCondition(snapshotDataName string, condition *crdv1.VolumeSnapshotCondition) error { var snapshotDataObj crdv1.VolumeSnapshotData err := vs.restClient.Get(). Name(snapshotDataName). Resource(crdv1.VolumeSnapshotDataResourcePlural). Do().Into(&snapshotDataObj) if err != nil { return err } newCondition := &crdv1.VolumeSnapshotDataCondition{ Type: (crdv1.VolumeSnapshotDataConditionType)(condition.Type), Status: condition.Status, Message: condition.Message, LastTransitionTime: condition.LastTransitionTime, } oldStatus := snapshotDataObj.Status.DeepCopy() status := snapshotDataObj.Status isEqual := false if oldStatus.Conditions == nil || len(oldStatus.Conditions) == 0 || newCondition.Type != oldStatus.Conditions[len(oldStatus.Conditions)-1].Type { status.Conditions = append(status.Conditions, *newCondition) } else { oldCondition := oldStatus.Conditions[len(oldStatus.Conditions)-1] if newCondition.Status == oldCondition.Status { newCondition.LastTransitionTime = oldCondition.LastTransitionTime } status.Conditions[len(status.Conditions)-1] = *newCondition isEqual = newCondition.Type == oldCondition.Type && newCondition.Status == oldCondition.Status && newCondition.Reason == oldCondition.Reason && newCondition.Message == oldCondition.Message && newCondition.LastTransitionTime.Equal(&oldCondition.LastTransitionTime) } if !isEqual { var newSnapshotDataObj crdv1.VolumeSnapshotData snapshotDataObj.Status = status if snapshotDataObj.Status.CreationTimestamp.IsZero() && newCondition.Type == crdv1.VolumeSnapshotDataConditionReady { snapshotDataObj.Status.CreationTimestamp = newCondition.LastTransitionTime } err = vs.restClient.Put(). Name(snapshotDataName). Resource(crdv1.VolumeSnapshotDataResourcePlural). Body(&snapshotDataObj). Do().Into(&newSnapshotDataObj) if err != nil { return err } glog.Infof("VolumeSnapshot status propagated to VolumeSnapshotData") return nil } return nil }
[ "func", "(", "vs", "*", "volumeSnapshotter", ")", "propagateVolumeSnapshotCondition", "(", "snapshotDataName", "string", ",", "condition", "*", "crdv1", ".", "VolumeSnapshotCondition", ")", "error", "{", "var", "snapshotDataObj", "crdv1", ".", "VolumeSnapshotData", "\n", "err", ":=", "vs", ".", "restClient", ".", "Get", "(", ")", ".", "Name", "(", "snapshotDataName", ")", ".", "Resource", "(", "crdv1", ".", "VolumeSnapshotDataResourcePlural", ")", ".", "Do", "(", ")", ".", "Into", "(", "&", "snapshotDataObj", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "newCondition", ":=", "&", "crdv1", ".", "VolumeSnapshotDataCondition", "{", "Type", ":", "(", "crdv1", ".", "VolumeSnapshotDataConditionType", ")", "(", "condition", ".", "Type", ")", ",", "Status", ":", "condition", ".", "Status", ",", "Message", ":", "condition", ".", "Message", ",", "LastTransitionTime", ":", "condition", ".", "LastTransitionTime", ",", "}", "\n", "oldStatus", ":=", "snapshotDataObj", ".", "Status", ".", "DeepCopy", "(", ")", "\n", "status", ":=", "snapshotDataObj", ".", "Status", "\n", "isEqual", ":=", "false", "\n", "if", "oldStatus", ".", "Conditions", "==", "nil", "||", "len", "(", "oldStatus", ".", "Conditions", ")", "==", "0", "||", "newCondition", ".", "Type", "!=", "oldStatus", ".", "Conditions", "[", "len", "(", "oldStatus", ".", "Conditions", ")", "-", "1", "]", ".", "Type", "{", "status", ".", "Conditions", "=", "append", "(", "status", ".", "Conditions", ",", "*", "newCondition", ")", "\n", "}", "else", "{", "oldCondition", ":=", "oldStatus", ".", "Conditions", "[", "len", "(", "oldStatus", ".", "Conditions", ")", "-", "1", "]", "\n", "if", "newCondition", ".", "Status", "==", "oldCondition", ".", "Status", "{", "newCondition", ".", "LastTransitionTime", "=", "oldCondition", ".", "LastTransitionTime", "\n", "}", "\n", "status", ".", "Conditions", "[", "len", "(", "status", ".", "Conditions", ")", "-", "1", "]", "=", "*", "newCondition", "\n", "isEqual", "=", "newCondition", ".", "Type", "==", "oldCondition", ".", "Type", "&&", "newCondition", ".", "Status", "==", "oldCondition", ".", "Status", "&&", "newCondition", ".", "Reason", "==", "oldCondition", ".", "Reason", "&&", "newCondition", ".", "Message", "==", "oldCondition", ".", "Message", "&&", "newCondition", ".", "LastTransitionTime", ".", "Equal", "(", "&", "oldCondition", ".", "LastTransitionTime", ")", "\n", "}", "\n", "if", "!", "isEqual", "{", "var", "newSnapshotDataObj", "crdv1", ".", "VolumeSnapshotData", "\n", "snapshotDataObj", ".", "Status", "=", "status", "\n", "if", "snapshotDataObj", ".", "Status", ".", "CreationTimestamp", ".", "IsZero", "(", ")", "&&", "newCondition", ".", "Type", "==", "crdv1", ".", "VolumeSnapshotDataConditionReady", "{", "snapshotDataObj", ".", "Status", ".", "CreationTimestamp", "=", "newCondition", ".", "LastTransitionTime", "\n", "}", "\n", "err", "=", "vs", ".", "restClient", ".", "Put", "(", ")", ".", "Name", "(", "snapshotDataName", ")", ".", "Resource", "(", "crdv1", ".", "VolumeSnapshotDataResourcePlural", ")", ".", "Body", "(", "&", "snapshotDataObj", ")", ".", "Do", "(", ")", ".", "Into", "(", "&", "newSnapshotDataObj", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "glog", ".", "Infof", "(", "\"VolumeSnapshot status propagated to VolumeSnapshotData\"", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Propagates the VolumeSnapshot condition to VolumeSnapshotData
[ "Propagates", "the", "VolumeSnapshot", "condition", "to", "VolumeSnapshotData" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/controller/snapshotter/snapshotter.go#L747-L800
train
kubernetes-incubator/external-storage
snapshot/pkg/controller/snapshotter/snapshotter.go
UpdateVolumeSnapshotStatus
func (vs *volumeSnapshotter) UpdateVolumeSnapshotStatus(snapshot *crdv1.VolumeSnapshot, condition *crdv1.VolumeSnapshotCondition) (*crdv1.VolumeSnapshot, error) { var snapshotObj crdv1.VolumeSnapshot err := vs.restClient.Get(). Name(snapshot.Metadata.Name). Resource(crdv1.VolumeSnapshotResourcePlural). Namespace(snapshot.Metadata.Namespace). Do().Into(&snapshotObj) if err != nil { return nil, err } oldStatus := snapshotObj.Status.DeepCopy() status := snapshotObj.Status isEqual := false if oldStatus.Conditions == nil || len(oldStatus.Conditions) == 0 || condition.Type != oldStatus.Conditions[len(oldStatus.Conditions)-1].Type { status.Conditions = append(status.Conditions, *condition) } else { oldCondition := oldStatus.Conditions[len(oldStatus.Conditions)-1] if condition.Status == oldCondition.Status { condition.LastTransitionTime = oldCondition.LastTransitionTime } status.Conditions[len(status.Conditions)-1] = *condition isEqual = condition.Type == oldCondition.Type && condition.Status == oldCondition.Status && condition.Reason == oldCondition.Reason && condition.Message == oldCondition.Message && condition.LastTransitionTime.Equal(&oldCondition.LastTransitionTime) } if !isEqual { var newSnapshotObj crdv1.VolumeSnapshot snapshotObj.Status = status err = vs.restClient.Put(). Name(snapshot.Metadata.Name). Resource(crdv1.VolumeSnapshotResourcePlural). Namespace(snapshot.Metadata.Namespace). Body(&snapshotObj). Do().Into(&newSnapshotObj) if err != nil { return nil, err } glog.Infof("UpdateVolumeSnapshotStatus finishes %+v", newSnapshotObj) err = vs.propagateVolumeSnapshotCondition(snapshotObj.Spec.SnapshotDataName, &snapshotObj.Status.Conditions[len(snapshotObj.Status.Conditions)-1]) if err != nil { return nil, err } return &newSnapshotObj, nil } return snapshot, nil }
go
func (vs *volumeSnapshotter) UpdateVolumeSnapshotStatus(snapshot *crdv1.VolumeSnapshot, condition *crdv1.VolumeSnapshotCondition) (*crdv1.VolumeSnapshot, error) { var snapshotObj crdv1.VolumeSnapshot err := vs.restClient.Get(). Name(snapshot.Metadata.Name). Resource(crdv1.VolumeSnapshotResourcePlural). Namespace(snapshot.Metadata.Namespace). Do().Into(&snapshotObj) if err != nil { return nil, err } oldStatus := snapshotObj.Status.DeepCopy() status := snapshotObj.Status isEqual := false if oldStatus.Conditions == nil || len(oldStatus.Conditions) == 0 || condition.Type != oldStatus.Conditions[len(oldStatus.Conditions)-1].Type { status.Conditions = append(status.Conditions, *condition) } else { oldCondition := oldStatus.Conditions[len(oldStatus.Conditions)-1] if condition.Status == oldCondition.Status { condition.LastTransitionTime = oldCondition.LastTransitionTime } status.Conditions[len(status.Conditions)-1] = *condition isEqual = condition.Type == oldCondition.Type && condition.Status == oldCondition.Status && condition.Reason == oldCondition.Reason && condition.Message == oldCondition.Message && condition.LastTransitionTime.Equal(&oldCondition.LastTransitionTime) } if !isEqual { var newSnapshotObj crdv1.VolumeSnapshot snapshotObj.Status = status err = vs.restClient.Put(). Name(snapshot.Metadata.Name). Resource(crdv1.VolumeSnapshotResourcePlural). Namespace(snapshot.Metadata.Namespace). Body(&snapshotObj). Do().Into(&newSnapshotObj) if err != nil { return nil, err } glog.Infof("UpdateVolumeSnapshotStatus finishes %+v", newSnapshotObj) err = vs.propagateVolumeSnapshotCondition(snapshotObj.Spec.SnapshotDataName, &snapshotObj.Status.Conditions[len(snapshotObj.Status.Conditions)-1]) if err != nil { return nil, err } return &newSnapshotObj, nil } return snapshot, nil }
[ "func", "(", "vs", "*", "volumeSnapshotter", ")", "UpdateVolumeSnapshotStatus", "(", "snapshot", "*", "crdv1", ".", "VolumeSnapshot", ",", "condition", "*", "crdv1", ".", "VolumeSnapshotCondition", ")", "(", "*", "crdv1", ".", "VolumeSnapshot", ",", "error", ")", "{", "var", "snapshotObj", "crdv1", ".", "VolumeSnapshot", "\n", "err", ":=", "vs", ".", "restClient", ".", "Get", "(", ")", ".", "Name", "(", "snapshot", ".", "Metadata", ".", "Name", ")", ".", "Resource", "(", "crdv1", ".", "VolumeSnapshotResourcePlural", ")", ".", "Namespace", "(", "snapshot", ".", "Metadata", ".", "Namespace", ")", ".", "Do", "(", ")", ".", "Into", "(", "&", "snapshotObj", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "oldStatus", ":=", "snapshotObj", ".", "Status", ".", "DeepCopy", "(", ")", "\n", "status", ":=", "snapshotObj", ".", "Status", "\n", "isEqual", ":=", "false", "\n", "if", "oldStatus", ".", "Conditions", "==", "nil", "||", "len", "(", "oldStatus", ".", "Conditions", ")", "==", "0", "||", "condition", ".", "Type", "!=", "oldStatus", ".", "Conditions", "[", "len", "(", "oldStatus", ".", "Conditions", ")", "-", "1", "]", ".", "Type", "{", "status", ".", "Conditions", "=", "append", "(", "status", ".", "Conditions", ",", "*", "condition", ")", "\n", "}", "else", "{", "oldCondition", ":=", "oldStatus", ".", "Conditions", "[", "len", "(", "oldStatus", ".", "Conditions", ")", "-", "1", "]", "\n", "if", "condition", ".", "Status", "==", "oldCondition", ".", "Status", "{", "condition", ".", "LastTransitionTime", "=", "oldCondition", ".", "LastTransitionTime", "\n", "}", "\n", "status", ".", "Conditions", "[", "len", "(", "status", ".", "Conditions", ")", "-", "1", "]", "=", "*", "condition", "\n", "isEqual", "=", "condition", ".", "Type", "==", "oldCondition", ".", "Type", "&&", "condition", ".", "Status", "==", "oldCondition", ".", "Status", "&&", "condition", ".", "Reason", "==", "oldCondition", ".", "Reason", "&&", "condition", ".", "Message", "==", "oldCondition", ".", "Message", "&&", "condition", ".", "LastTransitionTime", ".", "Equal", "(", "&", "oldCondition", ".", "LastTransitionTime", ")", "\n", "}", "\n", "if", "!", "isEqual", "{", "var", "newSnapshotObj", "crdv1", ".", "VolumeSnapshot", "\n", "snapshotObj", ".", "Status", "=", "status", "\n", "err", "=", "vs", ".", "restClient", ".", "Put", "(", ")", ".", "Name", "(", "snapshot", ".", "Metadata", ".", "Name", ")", ".", "Resource", "(", "crdv1", ".", "VolumeSnapshotResourcePlural", ")", ".", "Namespace", "(", "snapshot", ".", "Metadata", ".", "Namespace", ")", ".", "Body", "(", "&", "snapshotObj", ")", ".", "Do", "(", ")", ".", "Into", "(", "&", "newSnapshotObj", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "glog", ".", "Infof", "(", "\"UpdateVolumeSnapshotStatus finishes %+v\"", ",", "newSnapshotObj", ")", "\n", "err", "=", "vs", ".", "propagateVolumeSnapshotCondition", "(", "snapshotObj", ".", "Spec", ".", "SnapshotDataName", ",", "&", "snapshotObj", ".", "Status", ".", "Conditions", "[", "len", "(", "snapshotObj", ".", "Status", ".", "Conditions", ")", "-", "1", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "newSnapshotObj", ",", "nil", "\n", "}", "\n", "return", "snapshot", ",", "nil", "\n", "}" ]
// Update VolumeSnapshot status if the condition is changed.
[ "Update", "VolumeSnapshot", "status", "if", "the", "condition", "is", "changed", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/controller/snapshotter/snapshotter.go#L803-L854
train
kubernetes-incubator/external-storage
snapshot/pkg/controller/snapshotter/snapshotter.go
bindandUpdateVolumeSnapshot
func (vs *volumeSnapshotter) bindandUpdateVolumeSnapshot(snapshot *crdv1.VolumeSnapshot, snapshotDataName string, status *[]crdv1.VolumeSnapshotCondition) (*crdv1.VolumeSnapshot, error) { var snapshotObj crdv1.VolumeSnapshot glog.Infof("In bindVolumeSnapshotDataToVolumeSnapshot") // Get a fresh copy of the VolumeSnapshot from the API server glog.Infof("bindVolumeSnapshotDataToVolumeSnapshot: Namespace %s Name %s", snapshot.Metadata.Namespace, snapshot.Metadata.Name) err := vs.restClient.Get(). Name(snapshot.Metadata.Name). Resource(crdv1.VolumeSnapshotResourcePlural). Namespace(snapshot.Metadata.Namespace). Do().Into(&snapshotObj) uniqueSnapshotName := cache.MakeSnapshotName(snapshot) // TODO: Is copy needed here? snapshotCopy := snapshotObj.DeepCopy() snapshotCopy.Spec.SnapshotDataName = snapshotDataName if status != nil { snapshotCopy.Status.Conditions = *status } glog.Infof("bindVolumeSnapshotDataToVolumeSnapshot: Updating VolumeSnapshot object [%#v]", snapshotCopy) // TODO: Make diff of the two objects and then use restClient.Patch to update it var result crdv1.VolumeSnapshot err = vs.restClient.Put(). Name(snapshot.Metadata.Name). Resource(crdv1.VolumeSnapshotResourcePlural). Namespace(snapshot.Metadata.Namespace). Body(snapshotCopy). Do().Into(&result) if err != nil { return nil, fmt.Errorf("Error updating snapshot object %s on the API server: %v", uniqueSnapshotName, err) } return &result, nil }
go
func (vs *volumeSnapshotter) bindandUpdateVolumeSnapshot(snapshot *crdv1.VolumeSnapshot, snapshotDataName string, status *[]crdv1.VolumeSnapshotCondition) (*crdv1.VolumeSnapshot, error) { var snapshotObj crdv1.VolumeSnapshot glog.Infof("In bindVolumeSnapshotDataToVolumeSnapshot") // Get a fresh copy of the VolumeSnapshot from the API server glog.Infof("bindVolumeSnapshotDataToVolumeSnapshot: Namespace %s Name %s", snapshot.Metadata.Namespace, snapshot.Metadata.Name) err := vs.restClient.Get(). Name(snapshot.Metadata.Name). Resource(crdv1.VolumeSnapshotResourcePlural). Namespace(snapshot.Metadata.Namespace). Do().Into(&snapshotObj) uniqueSnapshotName := cache.MakeSnapshotName(snapshot) // TODO: Is copy needed here? snapshotCopy := snapshotObj.DeepCopy() snapshotCopy.Spec.SnapshotDataName = snapshotDataName if status != nil { snapshotCopy.Status.Conditions = *status } glog.Infof("bindVolumeSnapshotDataToVolumeSnapshot: Updating VolumeSnapshot object [%#v]", snapshotCopy) // TODO: Make diff of the two objects and then use restClient.Patch to update it var result crdv1.VolumeSnapshot err = vs.restClient.Put(). Name(snapshot.Metadata.Name). Resource(crdv1.VolumeSnapshotResourcePlural). Namespace(snapshot.Metadata.Namespace). Body(snapshotCopy). Do().Into(&result) if err != nil { return nil, fmt.Errorf("Error updating snapshot object %s on the API server: %v", uniqueSnapshotName, err) } return &result, nil }
[ "func", "(", "vs", "*", "volumeSnapshotter", ")", "bindandUpdateVolumeSnapshot", "(", "snapshot", "*", "crdv1", ".", "VolumeSnapshot", ",", "snapshotDataName", "string", ",", "status", "*", "[", "]", "crdv1", ".", "VolumeSnapshotCondition", ")", "(", "*", "crdv1", ".", "VolumeSnapshot", ",", "error", ")", "{", "var", "snapshotObj", "crdv1", ".", "VolumeSnapshot", "\n", "glog", ".", "Infof", "(", "\"In bindVolumeSnapshotDataToVolumeSnapshot\"", ")", "\n", "glog", ".", "Infof", "(", "\"bindVolumeSnapshotDataToVolumeSnapshot: Namespace %s Name %s\"", ",", "snapshot", ".", "Metadata", ".", "Namespace", ",", "snapshot", ".", "Metadata", ".", "Name", ")", "\n", "err", ":=", "vs", ".", "restClient", ".", "Get", "(", ")", ".", "Name", "(", "snapshot", ".", "Metadata", ".", "Name", ")", ".", "Resource", "(", "crdv1", ".", "VolumeSnapshotResourcePlural", ")", ".", "Namespace", "(", "snapshot", ".", "Metadata", ".", "Namespace", ")", ".", "Do", "(", ")", ".", "Into", "(", "&", "snapshotObj", ")", "\n", "uniqueSnapshotName", ":=", "cache", ".", "MakeSnapshotName", "(", "snapshot", ")", "\n", "snapshotCopy", ":=", "snapshotObj", ".", "DeepCopy", "(", ")", "\n", "snapshotCopy", ".", "Spec", ".", "SnapshotDataName", "=", "snapshotDataName", "\n", "if", "status", "!=", "nil", "{", "snapshotCopy", ".", "Status", ".", "Conditions", "=", "*", "status", "\n", "}", "\n", "glog", ".", "Infof", "(", "\"bindVolumeSnapshotDataToVolumeSnapshot: Updating VolumeSnapshot object [%#v]\"", ",", "snapshotCopy", ")", "\n", "var", "result", "crdv1", ".", "VolumeSnapshot", "\n", "err", "=", "vs", ".", "restClient", ".", "Put", "(", ")", ".", "Name", "(", "snapshot", ".", "Metadata", ".", "Name", ")", ".", "Resource", "(", "crdv1", ".", "VolumeSnapshotResourcePlural", ")", ".", "Namespace", "(", "snapshot", ".", "Metadata", ".", "Namespace", ")", ".", "Body", "(", "snapshotCopy", ")", ".", "Do", "(", ")", ".", "Into", "(", "&", "result", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Error updating snapshot object %s on the API server: %v\"", ",", "uniqueSnapshotName", ",", "err", ")", "\n", "}", "\n", "return", "&", "result", ",", "nil", "\n", "}" ]
// Bind the VolumeSnapshot and VolumeSnapshotData and udpate the status
[ "Bind", "the", "VolumeSnapshot", "and", "VolumeSnapshotData", "and", "udpate", "the", "status" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/controller/snapshotter/snapshotter.go#L857-L891
train
kubernetes-incubator/external-storage
nfs-client/cmd/nfs-client-provisioner/provisioner.go
getClassForVolume
func (p *nfsProvisioner) getClassForVolume(pv *v1.PersistentVolume) (*storage.StorageClass, error) { if p.client == nil { return nil, fmt.Errorf("Cannot get kube client") } className := helper.GetPersistentVolumeClass(pv) if className == "" { return nil, fmt.Errorf("Volume has no storage class") } class, err := p.client.StorageV1().StorageClasses().Get(className, metav1.GetOptions{}) if err != nil { return nil, err } return class, nil }
go
func (p *nfsProvisioner) getClassForVolume(pv *v1.PersistentVolume) (*storage.StorageClass, error) { if p.client == nil { return nil, fmt.Errorf("Cannot get kube client") } className := helper.GetPersistentVolumeClass(pv) if className == "" { return nil, fmt.Errorf("Volume has no storage class") } class, err := p.client.StorageV1().StorageClasses().Get(className, metav1.GetOptions{}) if err != nil { return nil, err } return class, nil }
[ "func", "(", "p", "*", "nfsProvisioner", ")", "getClassForVolume", "(", "pv", "*", "v1", ".", "PersistentVolume", ")", "(", "*", "storage", ".", "StorageClass", ",", "error", ")", "{", "if", "p", ".", "client", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Cannot get kube client\"", ")", "\n", "}", "\n", "className", ":=", "helper", ".", "GetPersistentVolumeClass", "(", "pv", ")", "\n", "if", "className", "==", "\"\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Volume has no storage class\"", ")", "\n", "}", "\n", "class", ",", "err", ":=", "p", ".", "client", ".", "StorageV1", "(", ")", ".", "StorageClasses", "(", ")", ".", "Get", "(", "className", ",", "metav1", ".", "GetOptions", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "class", ",", "nil", "\n", "}" ]
// getClassForVolume returns StorageClass
[ "getClassForVolume", "returns", "StorageClass" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/nfs-client/cmd/nfs-client-provisioner/provisioner.go#L133-L146
train
kubernetes-incubator/external-storage
snapshot/pkg/controller/populator/desired_state_of_world_populator.go
NewDesiredStateOfWorldPopulator
func NewDesiredStateOfWorldPopulator( loopSleepDuration time.Duration, listSnapshotsRetryDuration time.Duration, snapshotStore k8scache.Store, desiredStateOfWorld cache.DesiredStateOfWorld) DesiredStateOfWorldPopulator { return &desiredStateOfWorldPopulator{ loopSleepDuration: loopSleepDuration, listSnapshotsRetryDuration: listSnapshotsRetryDuration, desiredStateOfWorld: desiredStateOfWorld, snapshotStore: snapshotStore, } }
go
func NewDesiredStateOfWorldPopulator( loopSleepDuration time.Duration, listSnapshotsRetryDuration time.Duration, snapshotStore k8scache.Store, desiredStateOfWorld cache.DesiredStateOfWorld) DesiredStateOfWorldPopulator { return &desiredStateOfWorldPopulator{ loopSleepDuration: loopSleepDuration, listSnapshotsRetryDuration: listSnapshotsRetryDuration, desiredStateOfWorld: desiredStateOfWorld, snapshotStore: snapshotStore, } }
[ "func", "NewDesiredStateOfWorldPopulator", "(", "loopSleepDuration", "time", ".", "Duration", ",", "listSnapshotsRetryDuration", "time", ".", "Duration", ",", "snapshotStore", "k8scache", ".", "Store", ",", "desiredStateOfWorld", "cache", ".", "DesiredStateOfWorld", ")", "DesiredStateOfWorldPopulator", "{", "return", "&", "desiredStateOfWorldPopulator", "{", "loopSleepDuration", ":", "loopSleepDuration", ",", "listSnapshotsRetryDuration", ":", "listSnapshotsRetryDuration", ",", "desiredStateOfWorld", ":", "desiredStateOfWorld", ",", "snapshotStore", ":", "snapshotStore", ",", "}", "\n", "}" ]
// NewDesiredStateOfWorldPopulator returns a new instance of DesiredStateOfWorldPopulator. // loopSleepDuration - the amount of time the populator loop sleeps between // successive executions // desiredStateOfWorld - the cache to populate
[ "NewDesiredStateOfWorldPopulator", "returns", "a", "new", "instance", "of", "DesiredStateOfWorldPopulator", ".", "loopSleepDuration", "-", "the", "amount", "of", "time", "the", "populator", "loop", "sleeps", "between", "successive", "executions", "desiredStateOfWorld", "-", "the", "cache", "to", "populate" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/controller/populator/desired_state_of_world_populator.go#L42-L53
train
kubernetes-incubator/external-storage
flex/pkg/volume/driver-call.go
NewDriverCall
func (plugin *flexProvisioner) NewDriverCall(execPath, command string) *DriverCall { return plugin.NewDriverCallWithTimeout(execPath, command, 0) }
go
func (plugin *flexProvisioner) NewDriverCall(execPath, command string) *DriverCall { return plugin.NewDriverCallWithTimeout(execPath, command, 0) }
[ "func", "(", "plugin", "*", "flexProvisioner", ")", "NewDriverCall", "(", "execPath", ",", "command", "string", ")", "*", "DriverCall", "{", "return", "plugin", ".", "NewDriverCallWithTimeout", "(", "execPath", ",", "command", ",", "0", ")", "\n", "}" ]
// NewDriverCall initialize the DriverCall
[ "NewDriverCall", "initialize", "the", "DriverCall" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/flex/pkg/volume/driver-call.go#L57-L59
train
kubernetes-incubator/external-storage
flex/pkg/volume/driver-call.go
NewDriverCallWithTimeout
func (plugin *flexProvisioner) NewDriverCallWithTimeout(execPath, command string, timeout time.Duration) *DriverCall { return &DriverCall{ Execpath: execPath, Command: command, Timeout: timeout, plugin: plugin, args: []string{command}, } }
go
func (plugin *flexProvisioner) NewDriverCallWithTimeout(execPath, command string, timeout time.Duration) *DriverCall { return &DriverCall{ Execpath: execPath, Command: command, Timeout: timeout, plugin: plugin, args: []string{command}, } }
[ "func", "(", "plugin", "*", "flexProvisioner", ")", "NewDriverCallWithTimeout", "(", "execPath", ",", "command", "string", ",", "timeout", "time", ".", "Duration", ")", "*", "DriverCall", "{", "return", "&", "DriverCall", "{", "Execpath", ":", "execPath", ",", "Command", ":", "command", ",", "Timeout", ":", "timeout", ",", "plugin", ":", "plugin", ",", "args", ":", "[", "]", "string", "{", "command", "}", ",", "}", "\n", "}" ]
//NewDriverCallWithTimeout return the DriverCall with timeout
[ "NewDriverCallWithTimeout", "return", "the", "DriverCall", "with", "timeout" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/flex/pkg/volume/driver-call.go#L62-L70
train
kubernetes-incubator/external-storage
flex/pkg/volume/driver-call.go
AppendSpec
func (dc *DriverCall) AppendSpec(volumeOptions, extraOptions map[string]string) error { optionsForDriver, err := NewOptionsForDriver(volumeOptions, extraOptions) if err != nil { return err } jsonBytes, err := json.Marshal(optionsForDriver) if err != nil { return fmt.Errorf("Failed to marshal spec, error: %s", err.Error()) } dc.Append(string(jsonBytes)) return nil }
go
func (dc *DriverCall) AppendSpec(volumeOptions, extraOptions map[string]string) error { optionsForDriver, err := NewOptionsForDriver(volumeOptions, extraOptions) if err != nil { return err } jsonBytes, err := json.Marshal(optionsForDriver) if err != nil { return fmt.Errorf("Failed to marshal spec, error: %s", err.Error()) } dc.Append(string(jsonBytes)) return nil }
[ "func", "(", "dc", "*", "DriverCall", ")", "AppendSpec", "(", "volumeOptions", ",", "extraOptions", "map", "[", "string", "]", "string", ")", "error", "{", "optionsForDriver", ",", "err", ":=", "NewOptionsForDriver", "(", "volumeOptions", ",", "extraOptions", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "jsonBytes", ",", "err", ":=", "json", ".", "Marshal", "(", "optionsForDriver", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Failed to marshal spec, error: %s\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "dc", ".", "Append", "(", "string", "(", "jsonBytes", ")", ")", "\n", "return", "nil", "\n", "}" ]
//AppendSpec add all option parameters to DriverCall
[ "AppendSpec", "add", "all", "option", "parameters", "to", "DriverCall" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/flex/pkg/volume/driver-call.go#L78-L91
train
kubernetes-incubator/external-storage
flex/pkg/volume/driver-call.go
Run
func (dc *DriverCall) Run() (*DriverStatus, error) { cmd := dc.plugin.runner.Command(dc.Execpath, dc.args...) timeout := false if dc.Timeout > 0 { timer := time.AfterFunc(dc.Timeout, func() { timeout = true cmd.Stop() }) defer timer.Stop() } output, execErr := cmd.CombinedOutput() if execErr != nil { if timeout { return nil, ErrorTimeout } _, err := handleCmdResponse(dc.Command, output) if err == nil { klog.Errorf("FlexVolume: driver bug: %s: exec error (%s) but no error in response.", dc.Execpath, execErr) return nil, execErr } klog.Warningf("FlexVolume: driver call failed: executable: %s, args: %s, error: %s, output: %q", dc.Execpath, dc.args, execErr.Error(), output) return nil, err } status, err := handleCmdResponse(dc.Command, output) if err != nil { return nil, err } return status, nil }
go
func (dc *DriverCall) Run() (*DriverStatus, error) { cmd := dc.plugin.runner.Command(dc.Execpath, dc.args...) timeout := false if dc.Timeout > 0 { timer := time.AfterFunc(dc.Timeout, func() { timeout = true cmd.Stop() }) defer timer.Stop() } output, execErr := cmd.CombinedOutput() if execErr != nil { if timeout { return nil, ErrorTimeout } _, err := handleCmdResponse(dc.Command, output) if err == nil { klog.Errorf("FlexVolume: driver bug: %s: exec error (%s) but no error in response.", dc.Execpath, execErr) return nil, execErr } klog.Warningf("FlexVolume: driver call failed: executable: %s, args: %s, error: %s, output: %q", dc.Execpath, dc.args, execErr.Error(), output) return nil, err } status, err := handleCmdResponse(dc.Command, output) if err != nil { return nil, err } return status, nil }
[ "func", "(", "dc", "*", "DriverCall", ")", "Run", "(", ")", "(", "*", "DriverStatus", ",", "error", ")", "{", "cmd", ":=", "dc", ".", "plugin", ".", "runner", ".", "Command", "(", "dc", ".", "Execpath", ",", "dc", ".", "args", "...", ")", "\n", "timeout", ":=", "false", "\n", "if", "dc", ".", "Timeout", ">", "0", "{", "timer", ":=", "time", ".", "AfterFunc", "(", "dc", ".", "Timeout", ",", "func", "(", ")", "{", "timeout", "=", "true", "\n", "cmd", ".", "Stop", "(", ")", "\n", "}", ")", "\n", "defer", "timer", ".", "Stop", "(", ")", "\n", "}", "\n", "output", ",", "execErr", ":=", "cmd", ".", "CombinedOutput", "(", ")", "\n", "if", "execErr", "!=", "nil", "{", "if", "timeout", "{", "return", "nil", ",", "ErrorTimeout", "\n", "}", "\n", "_", ",", "err", ":=", "handleCmdResponse", "(", "dc", ".", "Command", ",", "output", ")", "\n", "if", "err", "==", "nil", "{", "klog", ".", "Errorf", "(", "\"FlexVolume: driver bug: %s: exec error (%s) but no error in response.\"", ",", "dc", ".", "Execpath", ",", "execErr", ")", "\n", "return", "nil", ",", "execErr", "\n", "}", "\n", "klog", ".", "Warningf", "(", "\"FlexVolume: driver call failed: executable: %s, args: %s, error: %s, output: %q\"", ",", "dc", ".", "Execpath", ",", "dc", ".", "args", ",", "execErr", ".", "Error", "(", ")", ",", "output", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "status", ",", "err", ":=", "handleCmdResponse", "(", "dc", ".", "Command", ",", "output", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "status", ",", "nil", "\n", "}" ]
//Run the command with option parameters
[ "Run", "the", "command", "with", "option", "parameters" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/flex/pkg/volume/driver-call.go#L94-L127
train
kubernetes-incubator/external-storage
flex/pkg/volume/driver-call.go
NewOptionsForDriver
func NewOptionsForDriver(volumeOptions, extraOptions map[string]string) (OptionsForDriver, error) { options := map[string]string{} for key, value := range extraOptions { options[key] = value } for key, value := range volumeOptions { options[key] = value } return OptionsForDriver(options), nil }
go
func NewOptionsForDriver(volumeOptions, extraOptions map[string]string) (OptionsForDriver, error) { options := map[string]string{} for key, value := range extraOptions { options[key] = value } for key, value := range volumeOptions { options[key] = value } return OptionsForDriver(options), nil }
[ "func", "NewOptionsForDriver", "(", "volumeOptions", ",", "extraOptions", "map", "[", "string", "]", "string", ")", "(", "OptionsForDriver", ",", "error", ")", "{", "options", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "for", "key", ",", "value", ":=", "range", "extraOptions", "{", "options", "[", "key", "]", "=", "value", "\n", "}", "\n", "for", "key", ",", "value", ":=", "range", "volumeOptions", "{", "options", "[", "key", "]", "=", "value", "\n", "}", "\n", "return", "OptionsForDriver", "(", "options", ")", ",", "nil", "\n", "}" ]
// NewOptionsForDriver assemble all option parameters
[ "NewOptionsForDriver", "assemble", "all", "option", "parameters" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/flex/pkg/volume/driver-call.go#L133-L145
train
kubernetes-incubator/external-storage
local-volume/provisioner/pkg/deleter/jobcontroller.go
NewJobController
func NewJobController(labelmap map[string]string, config *common.RuntimeConfig) (JobController, error) { namespace := config.Namespace queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()) labelset := labels.Set(labelmap) optionsModifier := func(options *meta_v1.ListOptions) { options.LabelSelector = labels.SelectorFromSet(labelset).String() } informer := config.InformerFactory.InformerFor(&batch_v1.Job{}, func(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { return cache.NewSharedIndexInformer( cache.NewFilteredListWatchFromClient(client.BatchV1().RESTClient(), "jobs", namespace, optionsModifier), &batch_v1.Job{}, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, ) }) informer.AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { key, err := cache.MetaNamespaceKeyFunc(obj) if err == nil { queue.Add(key) } return }, UpdateFunc: func(oldObj, newObj interface{}) { key, err := cache.MetaNamespaceKeyFunc(newObj) if err == nil { glog.Infof("Got update notification for %s", key) queue.Add(key) } return }, DeleteFunc: func(obj interface{}) { key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) if err == nil { glog.Infof("Got delete notification for %s", key) queue.Add(key) } }, }) return &jobController{ RuntimeConfig: config, namespace: namespace, queue: queue, jobLister: batchlisters.NewJobLister(informer.GetIndexer()), }, nil }
go
func NewJobController(labelmap map[string]string, config *common.RuntimeConfig) (JobController, error) { namespace := config.Namespace queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()) labelset := labels.Set(labelmap) optionsModifier := func(options *meta_v1.ListOptions) { options.LabelSelector = labels.SelectorFromSet(labelset).String() } informer := config.InformerFactory.InformerFor(&batch_v1.Job{}, func(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { return cache.NewSharedIndexInformer( cache.NewFilteredListWatchFromClient(client.BatchV1().RESTClient(), "jobs", namespace, optionsModifier), &batch_v1.Job{}, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, ) }) informer.AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { key, err := cache.MetaNamespaceKeyFunc(obj) if err == nil { queue.Add(key) } return }, UpdateFunc: func(oldObj, newObj interface{}) { key, err := cache.MetaNamespaceKeyFunc(newObj) if err == nil { glog.Infof("Got update notification for %s", key) queue.Add(key) } return }, DeleteFunc: func(obj interface{}) { key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) if err == nil { glog.Infof("Got delete notification for %s", key) queue.Add(key) } }, }) return &jobController{ RuntimeConfig: config, namespace: namespace, queue: queue, jobLister: batchlisters.NewJobLister(informer.GetIndexer()), }, nil }
[ "func", "NewJobController", "(", "labelmap", "map", "[", "string", "]", "string", ",", "config", "*", "common", ".", "RuntimeConfig", ")", "(", "JobController", ",", "error", ")", "{", "namespace", ":=", "config", ".", "Namespace", "\n", "queue", ":=", "workqueue", ".", "NewRateLimitingQueue", "(", "workqueue", ".", "DefaultControllerRateLimiter", "(", ")", ")", "\n", "labelset", ":=", "labels", ".", "Set", "(", "labelmap", ")", "\n", "optionsModifier", ":=", "func", "(", "options", "*", "meta_v1", ".", "ListOptions", ")", "{", "options", ".", "LabelSelector", "=", "labels", ".", "SelectorFromSet", "(", "labelset", ")", ".", "String", "(", ")", "\n", "}", "\n", "informer", ":=", "config", ".", "InformerFactory", ".", "InformerFor", "(", "&", "batch_v1", ".", "Job", "{", "}", ",", "func", "(", "client", "kubernetes", ".", "Interface", ",", "resyncPeriod", "time", ".", "Duration", ")", "cache", ".", "SharedIndexInformer", "{", "return", "cache", ".", "NewSharedIndexInformer", "(", "cache", ".", "NewFilteredListWatchFromClient", "(", "client", ".", "BatchV1", "(", ")", ".", "RESTClient", "(", ")", ",", "\"jobs\"", ",", "namespace", ",", "optionsModifier", ")", ",", "&", "batch_v1", ".", "Job", "{", "}", ",", "resyncPeriod", ",", "cache", ".", "Indexers", "{", "cache", ".", "NamespaceIndex", ":", "cache", ".", "MetaNamespaceIndexFunc", "}", ",", ")", "\n", "}", ")", "\n", "informer", ".", "AddEventHandler", "(", "cache", ".", "ResourceEventHandlerFuncs", "{", "AddFunc", ":", "func", "(", "obj", "interface", "{", "}", ")", "{", "key", ",", "err", ":=", "cache", ".", "MetaNamespaceKeyFunc", "(", "obj", ")", "\n", "if", "err", "==", "nil", "{", "queue", ".", "Add", "(", "key", ")", "\n", "}", "\n", "return", "\n", "}", ",", "UpdateFunc", ":", "func", "(", "oldObj", ",", "newObj", "interface", "{", "}", ")", "{", "key", ",", "err", ":=", "cache", ".", "MetaNamespaceKeyFunc", "(", "newObj", ")", "\n", "if", "err", "==", "nil", "{", "glog", ".", "Infof", "(", "\"Got update notification for %s\"", ",", "key", ")", "\n", "queue", ".", "Add", "(", "key", ")", "\n", "}", "\n", "return", "\n", "}", ",", "DeleteFunc", ":", "func", "(", "obj", "interface", "{", "}", ")", "{", "key", ",", "err", ":=", "cache", ".", "DeletionHandlingMetaNamespaceKeyFunc", "(", "obj", ")", "\n", "if", "err", "==", "nil", "{", "glog", ".", "Infof", "(", "\"Got delete notification for %s\"", ",", "key", ")", "\n", "queue", ".", "Add", "(", "key", ")", "\n", "}", "\n", "}", ",", "}", ")", "\n", "return", "&", "jobController", "{", "RuntimeConfig", ":", "config", ",", "namespace", ":", "namespace", ",", "queue", ":", "queue", ",", "jobLister", ":", "batchlisters", ".", "NewJobLister", "(", "informer", ".", "GetIndexer", "(", ")", ")", ",", "}", ",", "nil", "\n", "}" ]
// NewJobController instantiates a new job controller.
[ "NewJobController", "instantiates", "a", "new", "job", "controller", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/deleter/jobcontroller.go#L76-L125
train
kubernetes-incubator/external-storage
local-volume/provisioner/pkg/deleter/jobcontroller.go
processNextItem
func (c *jobController) processNextItem() bool { key, quit := c.queue.Get() if quit { return false } defer c.queue.Done(key) err := c.processItem(key.(string)) if err == nil { // No error, tell the queue to stop tracking history c.queue.Forget(key) } else if c.queue.NumRequeues(key) < maxRetries { glog.Errorf("Error processing %s (will retry): %v", key, err) // requeue the item to work on later c.queue.AddRateLimited(key) } else { // err != nil and too many retries glog.Errorf("Error processing %s (giving up): %v", key, err) c.queue.Forget(key) utilruntime.HandleError(err) } return true }
go
func (c *jobController) processNextItem() bool { key, quit := c.queue.Get() if quit { return false } defer c.queue.Done(key) err := c.processItem(key.(string)) if err == nil { // No error, tell the queue to stop tracking history c.queue.Forget(key) } else if c.queue.NumRequeues(key) < maxRetries { glog.Errorf("Error processing %s (will retry): %v", key, err) // requeue the item to work on later c.queue.AddRateLimited(key) } else { // err != nil and too many retries glog.Errorf("Error processing %s (giving up): %v", key, err) c.queue.Forget(key) utilruntime.HandleError(err) } return true }
[ "func", "(", "c", "*", "jobController", ")", "processNextItem", "(", ")", "bool", "{", "key", ",", "quit", ":=", "c", ".", "queue", ".", "Get", "(", ")", "\n", "if", "quit", "{", "return", "false", "\n", "}", "\n", "defer", "c", ".", "queue", ".", "Done", "(", "key", ")", "\n", "err", ":=", "c", ".", "processItem", "(", "key", ".", "(", "string", ")", ")", "\n", "if", "err", "==", "nil", "{", "c", ".", "queue", ".", "Forget", "(", "key", ")", "\n", "}", "else", "if", "c", ".", "queue", ".", "NumRequeues", "(", "key", ")", "<", "maxRetries", "{", "glog", ".", "Errorf", "(", "\"Error processing %s (will retry): %v\"", ",", "key", ",", "err", ")", "\n", "c", ".", "queue", ".", "AddRateLimited", "(", "key", ")", "\n", "}", "else", "{", "glog", ".", "Errorf", "(", "\"Error processing %s (giving up): %v\"", ",", "key", ",", "err", ")", "\n", "c", ".", "queue", ".", "Forget", "(", "key", ")", "\n", "utilruntime", ".", "HandleError", "(", "err", ")", "\n", "}", "\n", "return", "true", "\n", "}" ]
// processNextItem serially handles the events provided by the informer.
[ "processNextItem", "serially", "handles", "the", "events", "provided", "by", "the", "informer", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/deleter/jobcontroller.go#L146-L170
train
kubernetes-incubator/external-storage
local-volume/provisioner/pkg/deleter/jobcontroller.go
IsCleaningJobRunning
func (c *jobController) IsCleaningJobRunning(pvName string) bool { jobName := generateCleaningJobName(pvName) job, err := c.jobLister.Jobs(c.namespace).Get(jobName) if errors.IsNotFound(err) { return false } if err != nil { glog.Warningf("Failed to check whether job %s is running (%s). Assuming its still running.", jobName, err) return true } return job.Status.Succeeded <= 0 }
go
func (c *jobController) IsCleaningJobRunning(pvName string) bool { jobName := generateCleaningJobName(pvName) job, err := c.jobLister.Jobs(c.namespace).Get(jobName) if errors.IsNotFound(err) { return false } if err != nil { glog.Warningf("Failed to check whether job %s is running (%s). Assuming its still running.", jobName, err) return true } return job.Status.Succeeded <= 0 }
[ "func", "(", "c", "*", "jobController", ")", "IsCleaningJobRunning", "(", "pvName", "string", ")", "bool", "{", "jobName", ":=", "generateCleaningJobName", "(", "pvName", ")", "\n", "job", ",", "err", ":=", "c", ".", "jobLister", ".", "Jobs", "(", "c", ".", "namespace", ")", ".", "Get", "(", "jobName", ")", "\n", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "false", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Warningf", "(", "\"Failed to check whether job %s is running (%s). Assuming its still running.\"", ",", "jobName", ",", "err", ")", "\n", "return", "true", "\n", "}", "\n", "return", "job", ".", "Status", ".", "Succeeded", "<=", "0", "\n", "}" ]
// IsCleaningJobRunning returns true if a cleaning job is running for the specified PV.
[ "IsCleaningJobRunning", "returns", "true", "if", "a", "cleaning", "job", "is", "running", "for", "the", "specified", "PV", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/deleter/jobcontroller.go#L205-L219
train
kubernetes-incubator/external-storage
local-volume/provisioner/pkg/deleter/jobcontroller.go
RemoveJob
func (c *jobController) RemoveJob(pvName string) (CleanupState, *time.Time, error) { jobName := generateCleaningJobName(pvName) job, err := c.jobLister.Jobs(c.namespace).Get(jobName) if err != nil { if errors.IsNotFound(err) { return CSNotFound, nil, nil } return CSUnknown, nil, fmt.Errorf("Failed to check whether job %s has succeeded. Error - %s", jobName, err.Error()) } var startTime *time.Time if startTimeStr, ok := job.Annotations[StartTimeAnnotation]; ok { parsedStartTime, err := time.Parse(time.RFC3339Nano, startTimeStr) if err == nil { startTime = &parsedStartTime } else { glog.Errorf("Failed to parse start time %s: %v", startTimeStr, err) } } if job.Status.Succeeded == 0 { // Jobs has not yet succeeded. We assume failed jobs to be still running, until addressed by admin. return CSUnknown, nil, fmt.Errorf("Error deleting Job %q: Cannot remove job that has not succeeded", job.Name) } if err := c.RuntimeConfig.APIUtil.DeleteJob(job.Name, c.namespace); err != nil { return CSUnknown, nil, fmt.Errorf("Error deleting Job %q: %s", job.Name, err.Error()) } return CSSucceeded, startTime, nil }
go
func (c *jobController) RemoveJob(pvName string) (CleanupState, *time.Time, error) { jobName := generateCleaningJobName(pvName) job, err := c.jobLister.Jobs(c.namespace).Get(jobName) if err != nil { if errors.IsNotFound(err) { return CSNotFound, nil, nil } return CSUnknown, nil, fmt.Errorf("Failed to check whether job %s has succeeded. Error - %s", jobName, err.Error()) } var startTime *time.Time if startTimeStr, ok := job.Annotations[StartTimeAnnotation]; ok { parsedStartTime, err := time.Parse(time.RFC3339Nano, startTimeStr) if err == nil { startTime = &parsedStartTime } else { glog.Errorf("Failed to parse start time %s: %v", startTimeStr, err) } } if job.Status.Succeeded == 0 { // Jobs has not yet succeeded. We assume failed jobs to be still running, until addressed by admin. return CSUnknown, nil, fmt.Errorf("Error deleting Job %q: Cannot remove job that has not succeeded", job.Name) } if err := c.RuntimeConfig.APIUtil.DeleteJob(job.Name, c.namespace); err != nil { return CSUnknown, nil, fmt.Errorf("Error deleting Job %q: %s", job.Name, err.Error()) } return CSSucceeded, startTime, nil }
[ "func", "(", "c", "*", "jobController", ")", "RemoveJob", "(", "pvName", "string", ")", "(", "CleanupState", ",", "*", "time", ".", "Time", ",", "error", ")", "{", "jobName", ":=", "generateCleaningJobName", "(", "pvName", ")", "\n", "job", ",", "err", ":=", "c", ".", "jobLister", ".", "Jobs", "(", "c", ".", "namespace", ")", ".", "Get", "(", "jobName", ")", "\n", "if", "err", "!=", "nil", "{", "if", "errors", ".", "IsNotFound", "(", "err", ")", "{", "return", "CSNotFound", ",", "nil", ",", "nil", "\n", "}", "\n", "return", "CSUnknown", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"Failed to check whether job %s has succeeded. Error - %s\"", ",", "jobName", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "var", "startTime", "*", "time", ".", "Time", "\n", "if", "startTimeStr", ",", "ok", ":=", "job", ".", "Annotations", "[", "StartTimeAnnotation", "]", ";", "ok", "{", "parsedStartTime", ",", "err", ":=", "time", ".", "Parse", "(", "time", ".", "RFC3339Nano", ",", "startTimeStr", ")", "\n", "if", "err", "==", "nil", "{", "startTime", "=", "&", "parsedStartTime", "\n", "}", "else", "{", "glog", ".", "Errorf", "(", "\"Failed to parse start time %s: %v\"", ",", "startTimeStr", ",", "err", ")", "\n", "}", "\n", "}", "\n", "if", "job", ".", "Status", ".", "Succeeded", "==", "0", "{", "return", "CSUnknown", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"Error deleting Job %q: Cannot remove job that has not succeeded\"", ",", "job", ".", "Name", ")", "\n", "}", "\n", "if", "err", ":=", "c", ".", "RuntimeConfig", ".", "APIUtil", ".", "DeleteJob", "(", "job", ".", "Name", ",", "c", ".", "namespace", ")", ";", "err", "!=", "nil", "{", "return", "CSUnknown", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"Error deleting Job %q: %s\"", ",", "job", ".", "Name", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "CSSucceeded", ",", "startTime", ",", "nil", "\n", "}" ]
// RemoveJob returns true and deletes the job if the cleaning job has completed.
[ "RemoveJob", "returns", "true", "and", "deletes", "the", "job", "if", "the", "cleaning", "job", "has", "completed", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/deleter/jobcontroller.go#L222-L253
train
kubernetes-incubator/external-storage
local-volume/provisioner/pkg/deleter/jobcontroller.go
NewCleanupJob
func NewCleanupJob(pv *apiv1.PersistentVolume, volMode apiv1.PersistentVolumeMode, imageName string, nodeName string, namespace string, mountPath string, config common.MountConfig) (*batch_v1.Job, error) { priv := true // Container definition jobContainer := apiv1.Container{ Name: JobContainerName, Image: imageName, SecurityContext: &apiv1.SecurityContext{ Privileged: &priv, }, } if volMode == apiv1.PersistentVolumeBlock { jobContainer.Command = config.BlockCleanerCommand jobContainer.Env = []apiv1.EnvVar{{Name: common.LocalPVEnv, Value: mountPath}} } else if volMode == apiv1.PersistentVolumeFilesystem { // We only have one way to clean filesystem, so no need to customize // filesystem cleaner command. jobContainer.Command = []string{"/scripts/fsclean.sh"} jobContainer.Env = []apiv1.EnvVar{{Name: common.LocalFilesystemEnv, Value: mountPath}} } else { return nil, fmt.Errorf("unknown PersistentVolume mode: %v", volMode) } mountName := common.GenerateMountName(&config) volumes := []apiv1.Volume{ { Name: mountName, VolumeSource: apiv1.VolumeSource{ HostPath: &apiv1.HostPathVolumeSource{ Path: config.HostDir, }, }, }, } jobContainer.VolumeMounts = []apiv1.VolumeMount{{ Name: mountName, MountPath: config.MountDir}, } // Make job query-able by some useful labels for admins. labels := map[string]string{ common.NodeNameLabel: nodeName, PVLabel: pv.Name, PVUuidLabel: string(pv.UID), } // Annotate job with useful information that cannot be set as labels due to label name restrictions. annotations := map[string]string{ DeviceAnnotation: mountPath, StartTimeAnnotation: time.Now().Format(time.RFC3339Nano), } podTemplate := apiv1.Pod{} podTemplate.Spec = apiv1.PodSpec{ Containers: []apiv1.Container{jobContainer}, Volumes: volumes, NodeSelector: map[string]string{common.NodeNameLabel: nodeName}, } podTemplate.ObjectMeta = meta_v1.ObjectMeta{ Name: generateCleaningJobName(pv.Name), Namespace: namespace, Labels: labels, Annotations: annotations, } job := &batch_v1.Job{} job.ObjectMeta = podTemplate.ObjectMeta job.Spec.Template.Spec = podTemplate.Spec job.Spec.Template.Spec.RestartPolicy = apiv1.RestartPolicyOnFailure return job, nil }
go
func NewCleanupJob(pv *apiv1.PersistentVolume, volMode apiv1.PersistentVolumeMode, imageName string, nodeName string, namespace string, mountPath string, config common.MountConfig) (*batch_v1.Job, error) { priv := true // Container definition jobContainer := apiv1.Container{ Name: JobContainerName, Image: imageName, SecurityContext: &apiv1.SecurityContext{ Privileged: &priv, }, } if volMode == apiv1.PersistentVolumeBlock { jobContainer.Command = config.BlockCleanerCommand jobContainer.Env = []apiv1.EnvVar{{Name: common.LocalPVEnv, Value: mountPath}} } else if volMode == apiv1.PersistentVolumeFilesystem { // We only have one way to clean filesystem, so no need to customize // filesystem cleaner command. jobContainer.Command = []string{"/scripts/fsclean.sh"} jobContainer.Env = []apiv1.EnvVar{{Name: common.LocalFilesystemEnv, Value: mountPath}} } else { return nil, fmt.Errorf("unknown PersistentVolume mode: %v", volMode) } mountName := common.GenerateMountName(&config) volumes := []apiv1.Volume{ { Name: mountName, VolumeSource: apiv1.VolumeSource{ HostPath: &apiv1.HostPathVolumeSource{ Path: config.HostDir, }, }, }, } jobContainer.VolumeMounts = []apiv1.VolumeMount{{ Name: mountName, MountPath: config.MountDir}, } // Make job query-able by some useful labels for admins. labels := map[string]string{ common.NodeNameLabel: nodeName, PVLabel: pv.Name, PVUuidLabel: string(pv.UID), } // Annotate job with useful information that cannot be set as labels due to label name restrictions. annotations := map[string]string{ DeviceAnnotation: mountPath, StartTimeAnnotation: time.Now().Format(time.RFC3339Nano), } podTemplate := apiv1.Pod{} podTemplate.Spec = apiv1.PodSpec{ Containers: []apiv1.Container{jobContainer}, Volumes: volumes, NodeSelector: map[string]string{common.NodeNameLabel: nodeName}, } podTemplate.ObjectMeta = meta_v1.ObjectMeta{ Name: generateCleaningJobName(pv.Name), Namespace: namespace, Labels: labels, Annotations: annotations, } job := &batch_v1.Job{} job.ObjectMeta = podTemplate.ObjectMeta job.Spec.Template.Spec = podTemplate.Spec job.Spec.Template.Spec.RestartPolicy = apiv1.RestartPolicyOnFailure return job, nil }
[ "func", "NewCleanupJob", "(", "pv", "*", "apiv1", ".", "PersistentVolume", ",", "volMode", "apiv1", ".", "PersistentVolumeMode", ",", "imageName", "string", ",", "nodeName", "string", ",", "namespace", "string", ",", "mountPath", "string", ",", "config", "common", ".", "MountConfig", ")", "(", "*", "batch_v1", ".", "Job", ",", "error", ")", "{", "priv", ":=", "true", "\n", "jobContainer", ":=", "apiv1", ".", "Container", "{", "Name", ":", "JobContainerName", ",", "Image", ":", "imageName", ",", "SecurityContext", ":", "&", "apiv1", ".", "SecurityContext", "{", "Privileged", ":", "&", "priv", ",", "}", ",", "}", "\n", "if", "volMode", "==", "apiv1", ".", "PersistentVolumeBlock", "{", "jobContainer", ".", "Command", "=", "config", ".", "BlockCleanerCommand", "\n", "jobContainer", ".", "Env", "=", "[", "]", "apiv1", ".", "EnvVar", "{", "{", "Name", ":", "common", ".", "LocalPVEnv", ",", "Value", ":", "mountPath", "}", "}", "\n", "}", "else", "if", "volMode", "==", "apiv1", ".", "PersistentVolumeFilesystem", "{", "jobContainer", ".", "Command", "=", "[", "]", "string", "{", "\"/scripts/fsclean.sh\"", "}", "\n", "jobContainer", ".", "Env", "=", "[", "]", "apiv1", ".", "EnvVar", "{", "{", "Name", ":", "common", ".", "LocalFilesystemEnv", ",", "Value", ":", "mountPath", "}", "}", "\n", "}", "else", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"unknown PersistentVolume mode: %v\"", ",", "volMode", ")", "\n", "}", "\n", "mountName", ":=", "common", ".", "GenerateMountName", "(", "&", "config", ")", "\n", "volumes", ":=", "[", "]", "apiv1", ".", "Volume", "{", "{", "Name", ":", "mountName", ",", "VolumeSource", ":", "apiv1", ".", "VolumeSource", "{", "HostPath", ":", "&", "apiv1", ".", "HostPathVolumeSource", "{", "Path", ":", "config", ".", "HostDir", ",", "}", ",", "}", ",", "}", ",", "}", "\n", "jobContainer", ".", "VolumeMounts", "=", "[", "]", "apiv1", ".", "VolumeMount", "{", "{", "Name", ":", "mountName", ",", "MountPath", ":", "config", ".", "MountDir", "}", ",", "}", "\n", "labels", ":=", "map", "[", "string", "]", "string", "{", "common", ".", "NodeNameLabel", ":", "nodeName", ",", "PVLabel", ":", "pv", ".", "Name", ",", "PVUuidLabel", ":", "string", "(", "pv", ".", "UID", ")", ",", "}", "\n", "annotations", ":=", "map", "[", "string", "]", "string", "{", "DeviceAnnotation", ":", "mountPath", ",", "StartTimeAnnotation", ":", "time", ".", "Now", "(", ")", ".", "Format", "(", "time", ".", "RFC3339Nano", ")", ",", "}", "\n", "podTemplate", ":=", "apiv1", ".", "Pod", "{", "}", "\n", "podTemplate", ".", "Spec", "=", "apiv1", ".", "PodSpec", "{", "Containers", ":", "[", "]", "apiv1", ".", "Container", "{", "jobContainer", "}", ",", "Volumes", ":", "volumes", ",", "NodeSelector", ":", "map", "[", "string", "]", "string", "{", "common", ".", "NodeNameLabel", ":", "nodeName", "}", ",", "}", "\n", "podTemplate", ".", "ObjectMeta", "=", "meta_v1", ".", "ObjectMeta", "{", "Name", ":", "generateCleaningJobName", "(", "pv", ".", "Name", ")", ",", "Namespace", ":", "namespace", ",", "Labels", ":", "labels", ",", "Annotations", ":", "annotations", ",", "}", "\n", "job", ":=", "&", "batch_v1", ".", "Job", "{", "}", "\n", "job", ".", "ObjectMeta", "=", "podTemplate", ".", "ObjectMeta", "\n", "job", ".", "Spec", ".", "Template", ".", "Spec", "=", "podTemplate", ".", "Spec", "\n", "job", ".", "Spec", ".", "Template", ".", "Spec", ".", "RestartPolicy", "=", "apiv1", ".", "RestartPolicyOnFailure", "\n", "return", "job", ",", "nil", "\n", "}" ]
// NewCleanupJob creates manifest for a cleaning job.
[ "NewCleanupJob", "creates", "manifest", "for", "a", "cleaning", "job", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/deleter/jobcontroller.go#L256-L325
train
kubernetes-incubator/external-storage
local-volume/provisioner/pkg/deleter/jobcontroller.go
IsCleaningJobRunning
func (c *FakeJobController) IsCleaningJobRunning(pvName string) bool { c.IsRunningCount++ _, exists := c.pvCleanupRunning[pvName] return exists }
go
func (c *FakeJobController) IsCleaningJobRunning(pvName string) bool { c.IsRunningCount++ _, exists := c.pvCleanupRunning[pvName] return exists }
[ "func", "(", "c", "*", "FakeJobController", ")", "IsCleaningJobRunning", "(", "pvName", "string", ")", "bool", "{", "c", ".", "IsRunningCount", "++", "\n", "_", ",", "exists", ":=", "c", ".", "pvCleanupRunning", "[", "pvName", "]", "\n", "return", "exists", "\n", "}" ]
// IsCleaningJobRunning mocks the interface method.
[ "IsCleaningJobRunning", "mocks", "the", "interface", "method", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/deleter/jobcontroller.go#L361-L365
train
kubernetes-incubator/external-storage
local-volume/provisioner/pkg/deleter/jobcontroller.go
RemoveJob
func (c *FakeJobController) RemoveJob(pvName string) (CleanupState, *time.Time, error) { c.RemoveCompletedCount++ status, exists := c.pvCleanupRunning[pvName] if !exists { return CSNotFound, nil, nil } if status != CSSucceeded { return CSUnknown, nil, fmt.Errorf("cannot remove job that has not yet completed %s status %d", pvName, status) } return CSSucceeded, nil, nil }
go
func (c *FakeJobController) RemoveJob(pvName string) (CleanupState, *time.Time, error) { c.RemoveCompletedCount++ status, exists := c.pvCleanupRunning[pvName] if !exists { return CSNotFound, nil, nil } if status != CSSucceeded { return CSUnknown, nil, fmt.Errorf("cannot remove job that has not yet completed %s status %d", pvName, status) } return CSSucceeded, nil, nil }
[ "func", "(", "c", "*", "FakeJobController", ")", "RemoveJob", "(", "pvName", "string", ")", "(", "CleanupState", ",", "*", "time", ".", "Time", ",", "error", ")", "{", "c", ".", "RemoveCompletedCount", "++", "\n", "status", ",", "exists", ":=", "c", ".", "pvCleanupRunning", "[", "pvName", "]", "\n", "if", "!", "exists", "{", "return", "CSNotFound", ",", "nil", ",", "nil", "\n", "}", "\n", "if", "status", "!=", "CSSucceeded", "{", "return", "CSUnknown", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"cannot remove job that has not yet completed %s status %d\"", ",", "pvName", ",", "status", ")", "\n", "}", "\n", "return", "CSSucceeded", ",", "nil", ",", "nil", "\n", "}" ]
// RemoveJob mocks the interface method.
[ "RemoveJob", "mocks", "the", "interface", "method", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/deleter/jobcontroller.go#L368-L378
train
kubernetes-incubator/external-storage
openebs/openebs-provisioner.go
NewOpenEBSProvisioner
func NewOpenEBSProvisioner(client kubernetes.Interface) controller.Provisioner { nodeName := os.Getenv("NODE_NAME") if nodeName == "" { glog.Errorf("ENV variable 'NODE_NAME' is not set") } var openebsObj mApiv1.OpenEBSVolume //Get maya-apiserver IP address from cluster addr, err := openebsObj.GetMayaClusterIP(client) if err != nil { glog.Errorf("Error getting maya-apiserver IP Address: %v", err) return nil } mayaServiceURI := "http://" + addr + ":5656" //Set maya-apiserver IP address along with default port os.Setenv("MAPI_ADDR", mayaServiceURI) return &openEBSProvisioner{ mapiURI: mayaServiceURI, identity: nodeName, } }
go
func NewOpenEBSProvisioner(client kubernetes.Interface) controller.Provisioner { nodeName := os.Getenv("NODE_NAME") if nodeName == "" { glog.Errorf("ENV variable 'NODE_NAME' is not set") } var openebsObj mApiv1.OpenEBSVolume //Get maya-apiserver IP address from cluster addr, err := openebsObj.GetMayaClusterIP(client) if err != nil { glog.Errorf("Error getting maya-apiserver IP Address: %v", err) return nil } mayaServiceURI := "http://" + addr + ":5656" //Set maya-apiserver IP address along with default port os.Setenv("MAPI_ADDR", mayaServiceURI) return &openEBSProvisioner{ mapiURI: mayaServiceURI, identity: nodeName, } }
[ "func", "NewOpenEBSProvisioner", "(", "client", "kubernetes", ".", "Interface", ")", "controller", ".", "Provisioner", "{", "nodeName", ":=", "os", ".", "Getenv", "(", "\"NODE_NAME\"", ")", "\n", "if", "nodeName", "==", "\"\"", "{", "glog", ".", "Errorf", "(", "\"ENV variable 'NODE_NAME' is not set\"", ")", "\n", "}", "\n", "var", "openebsObj", "mApiv1", ".", "OpenEBSVolume", "\n", "addr", ",", "err", ":=", "openebsObj", ".", "GetMayaClusterIP", "(", "client", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Errorf", "(", "\"Error getting maya-apiserver IP Address: %v\"", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n", "mayaServiceURI", ":=", "\"http://\"", "+", "addr", "+", "\":5656\"", "\n", "os", ".", "Setenv", "(", "\"MAPI_ADDR\"", ",", "mayaServiceURI", ")", "\n", "return", "&", "openEBSProvisioner", "{", "mapiURI", ":", "mayaServiceURI", ",", "identity", ":", "nodeName", ",", "}", "\n", "}" ]
// NewOpenEBSProvisioner creates a new openebs provisioner
[ "NewOpenEBSProvisioner", "creates", "a", "new", "openebs", "provisioner" ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/openebs/openebs-provisioner.go#L53-L77
train
kubernetes-incubator/external-storage
snapshot/pkg/controller/cache/actual_state_of_world.go
AddSnapshot
func (asw *actualStateOfWorld) AddSnapshot(snapshot *crdv1.VolumeSnapshot) error { asw.Lock() defer asw.Unlock() snapshotName := MakeSnapshotName(snapshot) glog.Infof("Adding new snapshot to actual state of world: %s", snapshotName) asw.snapshots[snapshotName] = snapshot return nil }
go
func (asw *actualStateOfWorld) AddSnapshot(snapshot *crdv1.VolumeSnapshot) error { asw.Lock() defer asw.Unlock() snapshotName := MakeSnapshotName(snapshot) glog.Infof("Adding new snapshot to actual state of world: %s", snapshotName) asw.snapshots[snapshotName] = snapshot return nil }
[ "func", "(", "asw", "*", "actualStateOfWorld", ")", "AddSnapshot", "(", "snapshot", "*", "crdv1", ".", "VolumeSnapshot", ")", "error", "{", "asw", ".", "Lock", "(", ")", "\n", "defer", "asw", ".", "Unlock", "(", ")", "\n", "snapshotName", ":=", "MakeSnapshotName", "(", "snapshot", ")", "\n", "glog", ".", "Infof", "(", "\"Adding new snapshot to actual state of world: %s\"", ",", "snapshotName", ")", "\n", "asw", ".", "snapshots", "[", "snapshotName", "]", "=", "snapshot", "\n", "return", "nil", "\n", "}" ]
// Adds a snapshot to the list of snapshots to be created.
[ "Adds", "a", "snapshot", "to", "the", "list", "of", "snapshots", "to", "be", "created", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/controller/cache/actual_state_of_world.go#L69-L77
train
kubernetes-incubator/external-storage
snapshot/pkg/controller/cache/actual_state_of_world.go
DeleteSnapshot
func (asw *actualStateOfWorld) DeleteSnapshot(snapshotName string) error { asw.Lock() defer asw.Unlock() glog.Infof("Deleting snapshot from actual state of world: %s", snapshotName) delete(asw.snapshots, snapshotName) return nil }
go
func (asw *actualStateOfWorld) DeleteSnapshot(snapshotName string) error { asw.Lock() defer asw.Unlock() glog.Infof("Deleting snapshot from actual state of world: %s", snapshotName) delete(asw.snapshots, snapshotName) return nil }
[ "func", "(", "asw", "*", "actualStateOfWorld", ")", "DeleteSnapshot", "(", "snapshotName", "string", ")", "error", "{", "asw", ".", "Lock", "(", ")", "\n", "defer", "asw", ".", "Unlock", "(", ")", "\n", "glog", ".", "Infof", "(", "\"Deleting snapshot from actual state of world: %s\"", ",", "snapshotName", ")", "\n", "delete", "(", "asw", ".", "snapshots", ",", "snapshotName", ")", "\n", "return", "nil", "\n", "}" ]
// Removes the snapshot from the list of existing snapshots.
[ "Removes", "the", "snapshot", "from", "the", "list", "of", "existing", "snapshots", "." ]
fbfedbf60da4e5ee25a3151bfe8504f3e3281319
https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/controller/cache/actual_state_of_world.go#L80-L87
train
asaskevich/govalidator
arrays.go
Each
func Each(array []interface{}, iterator Iterator) { for index, data := range array { iterator(data, index) } }
go
func Each(array []interface{}, iterator Iterator) { for index, data := range array { iterator(data, index) } }
[ "func", "Each", "(", "array", "[", "]", "interface", "{", "}", ",", "iterator", "Iterator", ")", "{", "for", "index", ",", "data", ":=", "range", "array", "{", "iterator", "(", "data", ",", "index", ")", "\n", "}", "\n", "}" ]
// Each iterates over the slice and apply Iterator to every item
[ "Each", "iterates", "over", "the", "slice", "and", "apply", "Iterator", "to", "every", "item" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/arrays.go#L13-L17
train
asaskevich/govalidator
arrays.go
Map
func Map(array []interface{}, iterator ResultIterator) []interface{} { var result = make([]interface{}, len(array)) for index, data := range array { result[index] = iterator(data, index) } return result }
go
func Map(array []interface{}, iterator ResultIterator) []interface{} { var result = make([]interface{}, len(array)) for index, data := range array { result[index] = iterator(data, index) } return result }
[ "func", "Map", "(", "array", "[", "]", "interface", "{", "}", ",", "iterator", "ResultIterator", ")", "[", "]", "interface", "{", "}", "{", "var", "result", "=", "make", "(", "[", "]", "interface", "{", "}", ",", "len", "(", "array", ")", ")", "\n", "for", "index", ",", "data", ":=", "range", "array", "{", "result", "[", "index", "]", "=", "iterator", "(", "data", ",", "index", ")", "\n", "}", "\n", "return", "result", "\n", "}" ]
// Map iterates over the slice and apply ResultIterator to every item. Returns new slice as a result.
[ "Map", "iterates", "over", "the", "slice", "and", "apply", "ResultIterator", "to", "every", "item", ".", "Returns", "new", "slice", "as", "a", "result", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/arrays.go#L20-L26
train
asaskevich/govalidator
arrays.go
Find
func Find(array []interface{}, iterator ConditionIterator) interface{} { for index, data := range array { if iterator(data, index) { return data } } return nil }
go
func Find(array []interface{}, iterator ConditionIterator) interface{} { for index, data := range array { if iterator(data, index) { return data } } return nil }
[ "func", "Find", "(", "array", "[", "]", "interface", "{", "}", ",", "iterator", "ConditionIterator", ")", "interface", "{", "}", "{", "for", "index", ",", "data", ":=", "range", "array", "{", "if", "iterator", "(", "data", ",", "index", ")", "{", "return", "data", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Find iterates over the slice and apply ConditionIterator to every item. Returns first item that meet ConditionIterator or nil otherwise.
[ "Find", "iterates", "over", "the", "slice", "and", "apply", "ConditionIterator", "to", "every", "item", ".", "Returns", "first", "item", "that", "meet", "ConditionIterator", "or", "nil", "otherwise", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/arrays.go#L29-L36
train
asaskevich/govalidator
arrays.go
Filter
func Filter(array []interface{}, iterator ConditionIterator) []interface{} { var result = make([]interface{}, 0) for index, data := range array { if iterator(data, index) { result = append(result, data) } } return result }
go
func Filter(array []interface{}, iterator ConditionIterator) []interface{} { var result = make([]interface{}, 0) for index, data := range array { if iterator(data, index) { result = append(result, data) } } return result }
[ "func", "Filter", "(", "array", "[", "]", "interface", "{", "}", ",", "iterator", "ConditionIterator", ")", "[", "]", "interface", "{", "}", "{", "var", "result", "=", "make", "(", "[", "]", "interface", "{", "}", ",", "0", ")", "\n", "for", "index", ",", "data", ":=", "range", "array", "{", "if", "iterator", "(", "data", ",", "index", ")", "{", "result", "=", "append", "(", "result", ",", "data", ")", "\n", "}", "\n", "}", "\n", "return", "result", "\n", "}" ]
// Filter iterates over the slice and apply ConditionIterator to every item. Returns new slice.
[ "Filter", "iterates", "over", "the", "slice", "and", "apply", "ConditionIterator", "to", "every", "item", ".", "Returns", "new", "slice", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/arrays.go#L39-L47
train
asaskevich/govalidator
arrays.go
Count
func Count(array []interface{}, iterator ConditionIterator) int { count := 0 for index, data := range array { if iterator(data, index) { count = count + 1 } } return count }
go
func Count(array []interface{}, iterator ConditionIterator) int { count := 0 for index, data := range array { if iterator(data, index) { count = count + 1 } } return count }
[ "func", "Count", "(", "array", "[", "]", "interface", "{", "}", ",", "iterator", "ConditionIterator", ")", "int", "{", "count", ":=", "0", "\n", "for", "index", ",", "data", ":=", "range", "array", "{", "if", "iterator", "(", "data", ",", "index", ")", "{", "count", "=", "count", "+", "1", "\n", "}", "\n", "}", "\n", "return", "count", "\n", "}" ]
// Count iterates over the slice and apply ConditionIterator to every item. Returns count of items that meets ConditionIterator.
[ "Count", "iterates", "over", "the", "slice", "and", "apply", "ConditionIterator", "to", "every", "item", ".", "Returns", "count", "of", "items", "that", "meets", "ConditionIterator", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/arrays.go#L50-L58
train
asaskevich/govalidator
utils.go
LeftTrim
func LeftTrim(str, chars string) string { if chars == "" { return strings.TrimLeftFunc(str, unicode.IsSpace) } r, _ := regexp.Compile("^[" + chars + "]+") return r.ReplaceAllString(str, "") }
go
func LeftTrim(str, chars string) string { if chars == "" { return strings.TrimLeftFunc(str, unicode.IsSpace) } r, _ := regexp.Compile("^[" + chars + "]+") return r.ReplaceAllString(str, "") }
[ "func", "LeftTrim", "(", "str", ",", "chars", "string", ")", "string", "{", "if", "chars", "==", "\"\"", "{", "return", "strings", ".", "TrimLeftFunc", "(", "str", ",", "unicode", ".", "IsSpace", ")", "\n", "}", "\n", "r", ",", "_", ":=", "regexp", ".", "Compile", "(", "\"^[\"", "+", "chars", "+", "\"]+\"", ")", "\n", "return", "r", ".", "ReplaceAllString", "(", "str", ",", "\"\"", ")", "\n", "}" ]
// LeftTrim trim characters from the left-side of the input. // If second argument is empty, it's will be remove leading spaces.
[ "LeftTrim", "trim", "characters", "from", "the", "left", "-", "side", "of", "the", "input", ".", "If", "second", "argument", "is", "empty", "it", "s", "will", "be", "remove", "leading", "spaces", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L29-L35
train
asaskevich/govalidator
utils.go
RightTrim
func RightTrim(str, chars string) string { if chars == "" { return strings.TrimRightFunc(str, unicode.IsSpace) } r, _ := regexp.Compile("[" + chars + "]+$") return r.ReplaceAllString(str, "") }
go
func RightTrim(str, chars string) string { if chars == "" { return strings.TrimRightFunc(str, unicode.IsSpace) } r, _ := regexp.Compile("[" + chars + "]+$") return r.ReplaceAllString(str, "") }
[ "func", "RightTrim", "(", "str", ",", "chars", "string", ")", "string", "{", "if", "chars", "==", "\"\"", "{", "return", "strings", ".", "TrimRightFunc", "(", "str", ",", "unicode", ".", "IsSpace", ")", "\n", "}", "\n", "r", ",", "_", ":=", "regexp", ".", "Compile", "(", "\"[\"", "+", "chars", "+", "\"]+$\"", ")", "\n", "return", "r", ".", "ReplaceAllString", "(", "str", ",", "\"\"", ")", "\n", "}" ]
// RightTrim trim characters from the right-side of the input. // If second argument is empty, it's will be remove spaces.
[ "RightTrim", "trim", "characters", "from", "the", "right", "-", "side", "of", "the", "input", ".", "If", "second", "argument", "is", "empty", "it", "s", "will", "be", "remove", "spaces", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L39-L45
train
asaskevich/govalidator
utils.go
Trim
func Trim(str, chars string) string { return LeftTrim(RightTrim(str, chars), chars) }
go
func Trim(str, chars string) string { return LeftTrim(RightTrim(str, chars), chars) }
[ "func", "Trim", "(", "str", ",", "chars", "string", ")", "string", "{", "return", "LeftTrim", "(", "RightTrim", "(", "str", ",", "chars", ")", ",", "chars", ")", "\n", "}" ]
// Trim trim characters from both sides of the input. // If second argument is empty, it's will be remove spaces.
[ "Trim", "trim", "characters", "from", "both", "sides", "of", "the", "input", ".", "If", "second", "argument", "is", "empty", "it", "s", "will", "be", "remove", "spaces", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L49-L51
train
asaskevich/govalidator
utils.go
WhiteList
func WhiteList(str, chars string) string { pattern := "[^" + chars + "]+" r, _ := regexp.Compile(pattern) return r.ReplaceAllString(str, "") }
go
func WhiteList(str, chars string) string { pattern := "[^" + chars + "]+" r, _ := regexp.Compile(pattern) return r.ReplaceAllString(str, "") }
[ "func", "WhiteList", "(", "str", ",", "chars", "string", ")", "string", "{", "pattern", ":=", "\"[^\"", "+", "chars", "+", "\"]+\"", "\n", "r", ",", "_", ":=", "regexp", ".", "Compile", "(", "pattern", ")", "\n", "return", "r", ".", "ReplaceAllString", "(", "str", ",", "\"\"", ")", "\n", "}" ]
// WhiteList remove characters that do not appear in the whitelist.
[ "WhiteList", "remove", "characters", "that", "do", "not", "appear", "in", "the", "whitelist", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L54-L58
train
asaskevich/govalidator
utils.go
ReplacePattern
func ReplacePattern(str, pattern, replace string) string { r, _ := regexp.Compile(pattern) return r.ReplaceAllString(str, replace) }
go
func ReplacePattern(str, pattern, replace string) string { r, _ := regexp.Compile(pattern) return r.ReplaceAllString(str, replace) }
[ "func", "ReplacePattern", "(", "str", ",", "pattern", ",", "replace", "string", ")", "string", "{", "r", ",", "_", ":=", "regexp", ".", "Compile", "(", "pattern", ")", "\n", "return", "r", ".", "ReplaceAllString", "(", "str", ",", "replace", ")", "\n", "}" ]
// ReplacePattern replace regular expression pattern in string
[ "ReplacePattern", "replace", "regular", "expression", "pattern", "in", "string" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L80-L83
train
asaskevich/govalidator
utils.go
Reverse
func Reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) }
go
func Reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) }
[ "func", "Reverse", "(", "s", "string", ")", "string", "{", "r", ":=", "[", "]", "rune", "(", "s", ")", "\n", "for", "i", ",", "j", ":=", "0", ",", "len", "(", "r", ")", "-", "1", ";", "i", "<", "j", ";", "i", ",", "j", "=", "i", "+", "1", ",", "j", "-", "1", "{", "r", "[", "i", "]", ",", "r", "[", "j", "]", "=", "r", "[", "j", "]", ",", "r", "[", "i", "]", "\n", "}", "\n", "return", "string", "(", "r", ")", "\n", "}" ]
// Reverse return reversed string
[ "Reverse", "return", "reversed", "string" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L124-L130
train
asaskevich/govalidator
utils.go
GetLine
func GetLine(s string, index int) (string, error) { lines := GetLines(s) if index < 0 || index >= len(lines) { return "", errors.New("line index out of bounds") } return lines[index], nil }
go
func GetLine(s string, index int) (string, error) { lines := GetLines(s) if index < 0 || index >= len(lines) { return "", errors.New("line index out of bounds") } return lines[index], nil }
[ "func", "GetLine", "(", "s", "string", ",", "index", "int", ")", "(", "string", ",", "error", ")", "{", "lines", ":=", "GetLines", "(", "s", ")", "\n", "if", "index", "<", "0", "||", "index", ">=", "len", "(", "lines", ")", "{", "return", "\"\"", ",", "errors", ".", "New", "(", "\"line index out of bounds\"", ")", "\n", "}", "\n", "return", "lines", "[", "index", "]", ",", "nil", "\n", "}" ]
// GetLine return specified line of multiline string
[ "GetLine", "return", "specified", "line", "of", "multiline", "string" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L138-L144
train