repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
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", "(", "\"", "\"", ")", "\n", "}", "\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", "(", "\"", "\"", ")", "\n", "}", "\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", "(", "\"", "\"", ")", ",", "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", "(", "\"", "\"", ",", "\"", "\"", ")", "}", "\n\n", "instances", ",", "err", ":=", "c", ".", "describeInstances", "(", "filters", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "types", ".", "NodeName", "{", "}", ",", "err", "\n", "}", "\n\n", "if", "len", "(", "instances", ")", "==", "0", "{", "return", "[", "]", "types", ".", "NodeName", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "strings", ".", "HasPrefix", "(", "regex", ",", "\"", "\"", ")", "&&", "strings", ".", "HasSuffix", "(", "regex", ",", "\"", "\"", ")", "{", "glog", ".", "Infof", "(", "\"", "\"", ",", "regex", ")", "\n", "regex", "=", "regex", "[", "1", ":", "len", "(", "regex", ")", "-", "1", "]", "\n", "}", "\n\n", "re", ",", "err", ":=", "regexp", ".", "Compile", "(", "regex", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "types", ".", "NodeName", "{", "}", ",", "err", "\n", "}", "\n\n", "matchingInstances", ":=", "[", "]", "types", ".", "NodeName", "{", "}", "\n", "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", ")", "==", "\"", "\"", "{", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"", "\"", ",", "*", "instance", ".", "InstanceId", ")", "\n", "continue", "\n", "}", "\n\n", "nodeName", ":=", "mapInstanceToNodeName", "(", "instance", ")", "\n", "if", "nodeName", "==", "\"", "\"", "{", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"", "\"", ",", "aws", ".", "StringValue", "(", "instance", ".", "InstanceId", ")", ")", "\n", "continue", "\n", "}", "\n\n", "for", "_", ",", "tag", ":=", "range", "instance", ".", "Tags", "{", "if", "orEmpty", "(", "tag", ".", "Key", ")", "==", "\"", "\"", "&&", "re", ".", "MatchString", "(", "orEmpty", "(", "tag", ".", "Value", ")", ")", "{", "matchingInstances", "=", "append", "(", "matchingInstances", ",", "nodeName", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"", "\"", ",", "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", "(", "\"", "\"", ",", "i", ".", "awsID", ")", "\n", "}", "\n\n", "deviceMappings", ":=", "map", "[", "mountDevice", "]", "awsVolumeID", "{", "}", "\n", "for", "_", ",", "blockDevice", ":=", "range", "info", ".", "BlockDeviceMappings", "{", "name", ":=", "aws", ".", "StringValue", "(", "blockDevice", ".", "DeviceName", ")", "\n", "if", "strings", ".", "HasPrefix", "(", "name", ",", "\"", "\"", ")", "{", "name", "=", "name", "[", "7", ":", "]", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "name", ",", "\"", "\"", ")", "{", "name", "=", "name", "[", "8", ":", "]", "\n", "}", "\n", "if", "len", "(", "name", ")", "<", "1", "||", "len", "(", "name", ")", ">", "2", "{", "glog", ".", "Warningf", "(", "\"", "\"", ",", "aws", ".", "StringValue", "(", "blockDevice", ".", "DeviceName", ")", ")", "\n", "}", "\n", "deviceMappings", "[", "mountDevice", "(", "name", ")", "]", "=", "awsVolumeID", "(", "aws", ".", "StringValue", "(", "blockDevice", ".", "Ebs", ".", "VolumeId", ")", ")", "\n", "}", "\n\n", "// 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", "(", ")", "\n", "defer", "c", ".", "attachingMutex", ".", "Unlock", "(", ")", "\n\n", "for", "mountDevice", ",", "volume", ":=", "range", "c", ".", "attaching", "[", "i", ".", "nodeName", "]", "{", "deviceMappings", "[", "mountDevice", "]", "=", "volume", "\n", "}", "\n\n", "// 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", "(", "\"", "\"", ",", "mountDevice", ",", "mappingVolumeID", ")", "\n", "}", "\n", "return", "mountDevice", ",", "true", ",", "nil", "\n", "}", "\n", "}", "\n\n", "if", "!", "assign", "{", "return", "mountDevice", "(", "\"", "\"", ")", ",", "false", ",", "nil", "\n", "}", "\n\n", "// Find the next unused device name", "deviceAllocator", ":=", "c", ".", "deviceAllocators", "[", "i", ".", "nodeName", "]", "\n", "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", ")", "\n", "c", ".", "deviceAllocators", "[", "i", ".", "nodeName", "]", "=", "deviceAllocator", "\n", "}", "\n", "chosen", ",", "err", ":=", "deviceAllocator", ".", "GetNext", "(", "deviceMappings", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Warningf", "(", "\"", "\"", ",", "deviceMappings", ",", "err", ")", "\n", "return", "\"", "\"", ",", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "i", ".", "nodeName", ")", "\n", "}", "\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", "(", "\"", "\"", ",", "chosen", ",", "volumeID", ")", "\n\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\n", "request", ":=", "&", "ec2", ".", "DescribeVolumesInput", "{", "VolumeIds", ":", "[", "]", "*", "string", "{", "volumeID", ".", "awsString", "(", ")", "}", ",", "}", "\n\n", "volumes", ",", "err", ":=", "d", ".", "ec2", ".", "DescribeVolumes", "(", "request", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "volumeID", ",", "err", ")", "\n", "}", "\n", "if", "len", "(", "volumes", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "volumeID", ")", "\n", "}", "\n", "if", "len", "(", "volumes", ")", ">", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "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\n", "// 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", "\n", "var", "attachment", "*", "ec2", ".", "VolumeAttachment", "\n\n", "err", ":=", "wait", ".", "ExponentialBackoff", "(", "backoff", ",", "func", "(", ")", "(", "bool", ",", "error", ")", "{", "info", ",", "err", ":=", "d", ".", "describeVolume", "(", ")", "\n", "if", "err", "!=", "nil", "{", "describeErrorCount", "++", "\n", "if", "describeErrorCount", ">", "volumeAttachmentStatusConsecutiveErrorLimit", "{", "// report the error", "return", "false", ",", "err", "\n", "}", "\n", "glog", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "false", ",", "nil", "\n", "}", "\n", "describeErrorCount", "=", "0", "\n", "if", "len", "(", "info", ".", "Attachments", ")", ">", "1", "{", "// Shouldn't happen; log so we know if it is", "glog", ".", "Warningf", "(", "\"", "\"", ",", "d", ".", "awsID", ",", "info", ")", "\n", "}", "\n", "attachmentStatus", ":=", "\"", "\"", "\n", "for", "_", ",", "a", ":=", "range", "info", ".", "Attachments", "{", "if", "attachmentStatus", "!=", "\"", "\"", "{", "// Shouldn't happen; log so we know if it is", "glog", ".", "Warningf", "(", "\"", "\"", ",", "d", ".", "awsID", ",", "info", ")", "\n", "}", "\n", "if", "a", ".", "State", "!=", "nil", "{", "attachment", "=", "a", "\n", "attachmentStatus", "=", "*", "a", ".", "State", "\n", "}", "else", "{", "// Shouldn't happen; log so we know if it is", "glog", ".", "Warningf", "(", "\"", "\"", ",", "d", ".", "awsID", ",", "a", ")", "\n", "}", "\n", "}", "\n", "if", "attachmentStatus", "==", "\"", "\"", "{", "attachmentStatus", "=", "\"", "\"", "\n", "}", "\n", "if", "attachmentStatus", "==", "status", "{", "// Attachment is in requested state, finish waiting", "return", "true", ",", "nil", "\n", "}", "\n", "// continue waiting", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"", "\"", ",", "d", ".", "awsID", ",", "attachmentStatus", ",", "status", ")", "\n", "return", "false", ",", "nil", "\n", "}", ")", "\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", "(", ")", "==", "\"", "\"", "{", "return", "false", ",", "nil", "\n", "}", "\n", "if", "awsError", ".", "Code", "(", ")", "==", "\"", "\"", "{", "return", "false", ",", "volume", ".", "NewDeletedVolumeInUseError", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "\n", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "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\n", "awsInstance", "=", "newAWSInstance", "(", "c", ".", "ec2", ",", "instance", ")", "\n", "}", "\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", "(", "\"", "\"", ",", "*", "info", ".", "VolumeId", ")", "\n", "}", "\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\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\n", "if", "len", "(", "nodeDisks", ")", "==", "0", "{", "return", "attached", ",", "nil", "\n", "}", "\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\n", "awsInstances", ",", "err", ":=", "c", ".", "getInstancesByNodeNames", "(", "dnsNameSlice", ")", "\n", "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", "\n", "}", "\n\n", "if", "len", "(", "awsInstances", ")", "==", "0", "{", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"", "\"", ")", "\n", "return", "attached", ",", "nil", "\n", "}", "\n\n", "awsInstanceMap", ":=", "make", "(", "map", "[", "types", ".", "NodeName", "]", "*", "ec2", ".", "Instance", ")", "\n", "for", "_", ",", "awsInstance", ":=", "range", "awsInstances", "{", "awsInstanceMap", "[", "mapInstanceToNodeName", "(", "awsInstance", ")", "]", "=", "awsInstance", "\n", "}", "\n\n", "// 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", "]", "\n", "if", "awsInstance", "==", "nil", "{", "// If instance no longer exists, safe to assume volume is not attached.", "glog", ".", "Warningf", "(", "\"", "\"", ",", "nodeName", ",", "diskNames", ")", "\n", "continue", "\n", "}", "\n\n", "idToDiskName", ":=", "make", "(", "map", "[", "awsVolumeID", "]", "KubernetesVolumeID", ")", "\n", "for", "_", ",", "diskName", ":=", "range", "diskNames", "{", "volumeID", ",", "err", ":=", "diskName", ".", "mapToAWSVolumeID", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "diskName", ",", "err", ")", "\n", "}", "\n", "idToDiskName", "[", "volumeID", "]", "=", "diskName", "\n", "}", "\n\n", "for", "_", ",", "blockDevice", ":=", "range", "awsInstance", ".", "BlockDeviceMappings", "{", "volumeID", ":=", "awsVolumeID", "(", "aws", ".", "StringValue", "(", "blockDevice", ".", "Ebs", ".", "VolumeId", ")", ")", "\n", "diskName", ",", "found", ":=", "idToDiskName", "[", "volumeID", "]", "\n", "if", "found", "{", "// Disk is still attached to node", "setNodeDisk", "(", "attached", ",", "diskName", ",", "nodeName", ",", "true", ")", "\n", "}", "\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", ":=", "\"", "\"", "+", "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", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "snapshotOptions", ".", "Tags", "!=", "nil", "{", "awsID", ":=", "awsVolumeID", "(", "aws", ".", "StringValue", "(", "res", ".", "SnapshotId", ")", ")", "\n", "// apply tags", "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", "(", "\"", "\"", ",", "*", "res", ".", "SnapshotId", ",", "delerr", ")", "\n", "}", "\n", "return", "\"", "\"", ",", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "*", "res", ".", "SnapshotId", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "*", "res", ".", "SnapshotId", ",", "*", "res", ".", "State", ",", "nil", "\n\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\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", "(", "\"", "\"", ",", "result", ")", "\n", "}", "\n", "if", "result", "[", "0", "]", ".", "State", "==", "nil", "{", "return", "\"", "\"", ",", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "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", "(", "\"", "\"", ",", "*", "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", "(", "\"", "\"", ")", "\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\n", "request", ".", "Filters", "=", "append", "(", "request", ".", "Filters", ",", "filter", ")", "\n", "}", "\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", "(", "\"", "\"", ",", "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", "// We don't apply our tag filters because we are retrieving by ID", "groups", ",", "err", ":=", "c", ".", "ec2", ".", "DescribeSecurityGroups", "(", "describeSecurityGroupsRequest", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "len", "(", "groups", ")", "==", "0", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "if", "len", "(", "groups", ")", "!=", "1", "{", "// This should not be possible - ids should be unique", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "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", "(", "\"", "\"", ",", "err", ")", "\n", "return", "false", ",", "err", "\n", "}", "\n\n", "if", "group", "==", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "securityGroupID", ")", "\n", "}", "\n\n", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"", "\"", ",", "securityGroupID", ",", "group", ".", "IpPermissions", ")", "\n\n", "actual", ":=", "NewIPPermissionSet", "(", "group", ".", "IpPermissions", "...", ")", "\n\n", "// 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", "(", ")", "\n", "actual", "=", "actual", ".", "Ungroup", "(", ")", "\n\n", "remove", ":=", "actual", ".", "Difference", "(", "permissions", ")", "\n", "add", ":=", "permissions", ".", "Difference", "(", "actual", ")", "\n\n", "if", "add", ".", "Len", "(", ")", "==", "0", "&&", "remove", ".", "Len", "(", ")", "==", "0", "{", "return", "false", ",", "nil", "\n", "}", "\n\n", "// 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", "(", "\"", "\"", ",", "securityGroupID", ",", "add", ".", "List", "(", ")", ")", "\n\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", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "if", "remove", ".", "Len", "(", ")", "!=", "0", "{", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"", "\"", ",", "securityGroupID", ",", "remove", ".", "List", "(", ")", ")", "\n\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", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\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\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", "(", "\"", "\"", ",", "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\n", "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", "(", "\"", "\"", ",", "instanceID", ")", "\n", "}", "\n", "return", "tagged", "[", "0", "]", ",", "nil", "\n", "}", "\n\n", "if", "len", "(", "untagged", ")", ">", "0", "{", "// For back-compat, we will allow a single untagged SG", "if", "len", "(", "untagged", ")", "!=", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "instanceID", ")", "\n", "}", "\n", "return", "untagged", "[", "0", "]", ",", "nil", "\n", "}", "\n\n", "glog", ".", "Warningf", "(", "\"", "\"", ",", "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\n", "if", "len", "(", "instances", ")", "==", "0", "{", "return", "nil", ",", "cloudprovider", ".", "ErrInstanceNotFound", "\n", "}", "\n", "if", "len", "(", "instances", ")", ">", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "instanceID", ")", "\n", "}", "\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", "(", "\"", "\"", ")", "\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\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\n", "cache", ".", "pvs", "[", "pv", ".", "Name", "]", "=", "pv", "\n", "glog", ".", "Infof", "(", "\"", "\"", ",", "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\n", "delete", "(", "cache", ".", "pvs", ",", "pvName", ")", "\n", "glog", ".", "Infof", "(", "\"", "\"", ",", "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\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", "{", "// Start rpcbind if it is not started yet", "cmd", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", ":=", "cmd", ".", "Run", "(", ")", ";", "err", "!=", "nil", "{", "cmd", "=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "out", ",", "err", ":=", "cmd", ".", "CombinedOutput", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ",", "out", ")", "\n", "}", "\n", "}", "\n\n", "cmd", "=", "exec", ".", "Command", "(", "\"", "\"", ")", "\n", "if", "out", ",", "err", ":=", "cmd", ".", "CombinedOutput", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ",", "out", ")", "\n", "}", "\n\n", "// Start dbus, needed for ganesha dynamic exports", "cmd", "=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "out", ",", "err", ":=", "cmd", ".", "CombinedOutput", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ",", "out", ")", "\n", "}", "\n\n", "err", ":=", "setRlimitNOFILE", "(", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Use defaultGaneshaConfigContents if the ganeshaConfig doesn't exist yet", "if", "_", ",", "err", "=", "os", ".", "Stat", "(", "ganeshaConfig", ")", ";", "os", ".", "IsNotExist", "(", "err", ")", "{", "err", "=", "ioutil", ".", "WriteFile", "(", "ganeshaConfig", ",", "defaultGaneshaConfigContents", ",", "0600", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ganeshaConfig", ",", "err", ")", "\n", "}", "\n", "}", "\n", "err", "=", "setGracePeriod", "(", "ganeshaConfig", ",", "gracePeriod", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "err", "=", "setFsidDevice", "(", "ganeshaConfig", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\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\n", "klog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"", "\"", ",", "volSizeInt", ",", "config", ")", "\n\n", "// Possible opModes are gluster-block and heketi:", "switch", "config", ".", "opMode", "{", "// An experimental/Test Mode:", "case", "glusterBlockOpmode", ":", "gBlockCreateErr", ":=", "p", ".", "glusterBlockExecCreate", "(", "blockRes", ",", "config", ",", "sizeStr", ",", "haCountStr", ",", "blockVol", ")", "\n", "if", "gBlockCreateErr", "!=", "nil", "{", "klog", ".", "Errorf", "(", "\"", "\"", ",", "gBlockCreateErr", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "gBlockCreateErr", ")", "\n", "}", "\n\n", "case", "heketiOpmode", ":", "hBlockCreateErr", ":=", "p", ".", "heketiBlockVolCreate", "(", "blockRes", ",", "config", ",", "volSizeInt", ",", "haCountStr", ",", "blockVol", ")", "\n", "if", "hBlockCreateErr", "!=", "nil", "{", "klog", ".", "Errorf", "(", "\"", "\"", ",", "hBlockCreateErr", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hBlockCreateErr", ")", "\n", "}", "\n\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "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", "(", "\"", "\"", ")", "\n", "}", "\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", "(", "\"", "\"", ")", "\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", ")", "{", "// 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", ")", "\n\n", "if", "!", "strings", ".", "HasPrefix", "(", "s", ",", "\"", "\"", ")", "{", "// Assume a bare aws volume id (vol-1234...)", "// Build a URL with an empty host (AZ)", "s", "=", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", "+", "s", "\n", "}", "\n", "url", ",", "err", ":=", "url", ".", "Parse", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "// TODO: Maybe we should pass a URL into the Volume functions", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n", "if", "url", ".", "Scheme", "!=", "\"", "\"", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n\n", "awsID", ":=", "url", ".", "Path", "\n", "awsID", "=", "strings", ".", "Trim", "(", "awsID", ",", "\"", "\"", ")", "\n\n", "// 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", ",", "\"", "\"", ")", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\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", "(", "\"", "\"", ")", "\n\n", "// TODO: Search for and support Rackspace loadbalancer API, and others.", "network", ",", "err", ":=", "os", ".", "NewNetworkV2", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "false", "\n", "}", "\n\n", "compute", ",", "err", ":=", "os", ".", "NewComputeV2", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "false", "\n", "}", "\n\n", "lbVersion", ":=", "os", ".", "lbOpts", ".", "LBVersion", "\n", "if", "lbVersion", "==", "\"", "\"", "{", "// No version specified, try newest supported by server", "netExts", ",", "err", ":=", "networkExtensions", "(", "network", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "false", "\n", "}", "\n\n", "if", "netExts", "[", "\"", "\"", "]", "{", "lbVersion", "=", "\"", "\"", "\n", "}", "else", "if", "netExts", "[", "\"", "\"", "]", "{", "lbVersion", "=", "\"", "\"", "\n", "}", "else", "{", "glog", ".", "Warningf", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "false", "\n", "}", "\n", "glog", ".", "V", "(", "3", ")", ".", "Infof", "(", "\"", "\"", ",", "lbVersion", ")", "\n", "}", "\n\n", "glog", ".", "V", "(", "1", ")", ".", "Info", "(", "\"", "\"", ")", "\n\n", "if", "lbVersion", "==", "\"", "\"", "{", "return", "&", "LbaasV2", "{", "LoadBalancer", "{", "network", ",", "compute", ",", "os", ".", "lbOpts", "}", "}", ",", "true", "\n", "}", "else", "if", "lbVersion", "==", "\"", "\"", "{", "return", "&", "LbaasV1", "{", "LoadBalancer", "{", "network", ",", "compute", ",", "os", ".", "lbOpts", "}", "}", ",", "true", "\n", "}", "else", "{", "glog", ".", "Warningf", "(", "\"", "\\\"", "\\\"", "\"", ",", "lbVersion", ")", "\n", "return", "nil", ",", "false", "\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", "(", "\"", "\"", ")", "\n\n", "network", ",", "err", ":=", "os", ".", "NewNetworkV2", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "false", "\n", "}", "\n\n", "netExts", ",", "err", ":=", "networkExtensions", "(", "network", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "false", "\n", "}", "\n\n", "if", "!", "netExts", "[", "\"", "\"", "]", "{", "glog", ".", "V", "(", "3", ")", ".", "Infof", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "false", "\n", "}", "\n\n", "compute", ",", "err", ":=", "os", ".", "NewComputeV2", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "false", "\n", "}", "\n\n", "r", ",", "err", ":=", "NewRoutes", "(", "compute", ",", "network", ",", "os", ".", "routeOpts", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "false", "\n", "}", "\n\n", "glog", ".", "V", "(", "1", ")", ".", "Info", "(", "\"", "\"", ")", "\n\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", "(", "\"", "\"", ")", "\n\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\n", "zone", ":=", "cloudprovider", ".", "Zone", "{", "FailureDomain", ":", "md", ".", "AvailabilityZone", ",", "Region", ":", "os", ".", "region", ",", "}", "\n", "glog", ".", "V", "(", "1", ")", ".", "Infof", "(", "\"", "\"", ",", "zone", ")", "\n\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", "(", "\"", "\"", ",", "uniqueSnapshotName", ")", "\n", "}", "\n\n", "pvc", ",", "err", ":=", "vs", ".", "coreClient", ".", "CoreV1", "(", ")", ".", "PersistentVolumeClaims", "(", "snapshot", ".", "Metadata", ".", "Namespace", ")", ".", "Get", "(", "pvcName", ",", "metav1", ".", "GetOptions", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "pvcName", ",", "err", ")", "\n", "}", "\n", "if", "pvc", ".", "Status", ".", "Phase", "!=", "v1", ".", "ClaimBound", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "pvcName", ")", "\n", "}", "\n\n", "pvName", ":=", "pvc", ".", "Spec", ".", "VolumeName", "\n", "pv", ",", "err", ":=", "vs", ".", "getPVFromName", "(", "pvName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "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", "(", "\"", "\"", ")", "\n", "}", "\n", "err", ":=", "vs", ".", "restClient", ".", "Get", "(", ")", ".", "Name", "(", "snapshotDataName", ")", ".", "Resource", "(", "crdv1", ".", "VolumeSnapshotDataResourcePlural", ")", ".", "Do", "(", ")", ".", "Into", "(", "&", "snapshotDataObj", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "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\n", "tags", ":=", "vs", ".", "findVolumeSnapshotMetadata", "(", "snapshot", ")", "\n", "// If there is no tag returned, snapshotting is not triggered yet, return new state", "if", "tags", "==", "nil", "{", "glog", ".", "Infof", "(", "\"", "\"", ",", "uniqueSnapshotName", ")", "\n", "return", "statusNew", ",", "snapshot", ",", "nil", "\n", "}", "\n", "// 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", "(", "\"", "\"", ",", "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", "// Find snapshot through cloud provider by existing tags, and create VolumeSnapshotData if such snapshot is found", "snapshotDataSource", ",", "conditions", ",", "err", "=", "vs", ".", "findSnapshotByTags", "(", "snapshotName", ",", "snapshot", ")", "\n", "if", "err", "!=", "nil", "{", "return", "statusNew", ",", "snapshot", ",", "nil", "\n", "}", "\n", "// Snapshot is found. Create VolumeSnapshotData, bind VolumeSnapshotData to VolumeSnapshot, and update VolumeSnapshot status", "glog", ".", "Infof", "(", "\"", "\"", ",", "uniqueSnapshotName", ")", "\n", "pvName", ",", "ok", ":=", "snapshot", ".", "Metadata", ".", "Labels", "[", "pvNameLabel", "]", "\n", "if", "!", "ok", "{", "return", "statusError", ",", "snapshot", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "snapshotDataObj", ",", "err", "=", "vs", ".", "createVolumeSnapshotData", "(", "snapshotName", ",", "pvName", ",", "snapshotDataSource", ",", "conditions", ")", "\n", "if", "err", "!=", "nil", "{", "return", "statusError", ",", "snapshot", ",", "err", "\n", "}", "\n", "glog", ".", "Infof", "(", "\"", "\"", ",", "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", "// 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", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "switch", "status", "{", "case", "statusReady", ":", "glog", ".", "Infof", "(", "\"", "\"", ",", "uniqueSnapshotName", ")", "\n", "vs", ".", "actualStateOfWorld", ".", "AddSnapshot", "(", "snapshot", ")", "\n", "return", "nil", "\n", "case", "statusError", ":", "glog", ".", "Infof", "(", "\"", "\"", ",", "uniqueSnapshotName", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "uniqueSnapshotName", ")", "\n", "case", "statusPending", ":", "glog", ".", "V", "(", "4", ")", ".", "Infof", "(", "\"", "\"", ",", "uniqueSnapshotName", ")", "\n", "// Query the volume plugin for the status of the snapshot with snapshot id", "// from VolumeSnapshotData object.", "snapshotDataObj", ",", "err", ":=", "vs", ".", "getSnapshotDataFromSnapshot", "(", "snapshotObj", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "err", "=", "vs", ".", "waitForSnapshot", "(", "uniqueSnapshotName", ",", "snapshotObj", ",", "snapshotDataObj", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "uniqueSnapshotName", ",", "err", ")", "\n", "}", "\n", "glog", ".", "Infof", "(", "\"", "\"", ",", "uniqueSnapshotName", ")", "\n", "return", "nil", "\n", "case", "statusNew", ":", "glog", ".", "Infof", "(", "\"", "\"", ",", "uniqueSnapshotName", ")", "\n", "err", "=", "vs", ".", "createSnapshot", "(", "uniqueSnapshotName", ",", "snapshotObj", ")", "\n", "return", "err", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "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", "(", "\"", "\"", ",", "uniqueSnapshotName", ")", "\n", "pv", ",", "err", ":=", "vs", ".", "getPVFromVolumeSnapshot", "(", "uniqueSnapshotName", ",", "snapshot", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "glog", ".", "Infof", "(", "\"", "\"", ",", "uniqueSnapshotName", ")", "\n", "tags", ",", "err", "=", "vs", ".", "updateVolumeSnapshotMetadata", "(", "snapshot", ",", "pv", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "uniqueSnapshotName", ",", "err", ")", "\n", "}", "\n\n", "snapshotDataSource", ",", "snapStatus", ",", "err", "=", "vs", ".", "takeSnapshot", "(", "snapshot", ",", "pv", ",", "tags", ")", "\n", "if", "err", "!=", "nil", "||", "snapshotDataSource", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "pv", ".", "Name", ",", "err", ")", "\n", "}", "\n\n", "glog", ".", "Infof", "(", "\"", "\"", ",", "uniqueSnapshotName", ")", "\n", "snapshotDataObj", ",", "err", ":=", "vs", ".", "createVolumeSnapshotData", "(", "uniqueSnapshotName", ",", "pv", ".", "Name", ",", "snapshotDataSource", ",", "snapStatus", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "glog", ".", "Infof", "(", "\"", "\"", ",", "uniqueSnapshotName", ")", "\n", "snapshotObj", ",", "err", ":=", "vs", ".", "bindandUpdateVolumeSnapshot", "(", "snapshot", ",", "snapshotDataObj", ".", "Metadata", ".", "Name", ",", "snapStatus", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Errorf", "(", "\"", "\"", ",", "uniqueSnapshotName", ",", "err", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "uniqueSnapshotName", ")", "\n", "}", "\n\n", "// Waiting for snapshot to be ready", "err", "=", "vs", ".", "waitForSnapshot", "(", "uniqueSnapshotName", ",", "snapshotObj", ",", "snapshotDataObj", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "uniqueSnapshotName", ",", "err", ")", "\n", "}", "\n", "glog", ".", "Infof", "(", "\"", "\"", ",", "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", "(", "\"", "\"", ")", "\n", "var", "snapshotObj", "crdv1", ".", "VolumeSnapshot", "\n", "// 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", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "snapshot", ".", "Metadata", ".", "Name", ",", "err", ")", "\n", "}", "\n\n", "// Copy the snapshot object before updating it", "snapshotCopy", ":=", "snapshotObj", ".", "DeepCopy", "(", ")", "\n\n", "if", "snapshotCopy", ".", "Metadata", ".", "Labels", "==", "nil", "{", "snapshotCopy", ".", "Metadata", ".", "Labels", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "}", "\n", "snapshotCopy", ".", "Metadata", ".", "Labels", "[", "snapshotMetadataTimeStamp", "]", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", "\n", "snapshotCopy", ".", "Metadata", ".", "Labels", "[", "snapshotMetadataPVName", "]", "=", "pvName", "\n", "glog", ".", "Infof", "(", "\"", "\"", ",", "snapshotCopy", ".", "Metadata", ".", "UID", ",", "snapshotCopy", ".", "Metadata", ".", "Name", ",", "snapshotCopy", ".", "Metadata", ".", "Namespace", ",", "snapshotCopy", ".", "Metadata", ".", "Labels", ")", "\n\n", "// TODO: Use Patch instead of Put to update the object?", "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", "(", "\"", "\"", ",", "snapshot", ".", "Metadata", ".", "Namespace", ",", "snapshot", ".", "Metadata", ".", "Name", ",", "err", ")", "\n", "}", "\n\n", "cloudTags", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "cloudTags", "[", "CloudSnapshotCreatedForVolumeSnapshotNamespaceTag", "]", "=", "result", ".", "Metadata", ".", "Namespace", "\n", "cloudTags", "[", "CloudSnapshotCreatedForVolumeSnapshotNameTag", "]", "=", "result", ".", "Metadata", ".", "Name", "\n", "cloudTags", "[", "CloudSnapshotCreatedForVolumeSnapshotUIDTag", "]", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "result", ".", "Metadata", ".", "UID", ")", "\n", "cloudTags", "[", "CloudSnapshotCreatedForVolumeSnapshotTimestampTag", "]", "=", "result", ".", "Metadata", ".", "Labels", "[", "snapshotMetadataTimeStamp", "]", "\n\n", "glog", ".", "Infof", "(", "\"", "\"", ",", "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\n", "newCondition", ":=", "&", "crdv1", ".", "VolumeSnapshotDataCondition", "{", "Type", ":", "(", "crdv1", ".", "VolumeSnapshotDataConditionType", ")", "(", "condition", ".", "Type", ")", ",", "Status", ":", "condition", ".", "Status", ",", "Message", ":", "condition", ".", "Message", ",", "LastTransitionTime", ":", "condition", ".", "LastTransitionTime", ",", "}", "\n", "oldStatus", ":=", "snapshotDataObj", ".", "Status", ".", "DeepCopy", "(", ")", "\n\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", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\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\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\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\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", "(", "\"", "\"", ",", "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\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\n", "glog", ".", "Infof", "(", "\"", "\"", ")", "\n", "// Get a fresh copy of the VolumeSnapshot from the API server", "glog", ".", "Infof", "(", "\"", "\"", ",", "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\n", "uniqueSnapshotName", ":=", "cache", ".", "MakeSnapshotName", "(", "snapshot", ")", "\n", "// TODO: Is copy needed here?", "snapshotCopy", ":=", "snapshotObj", ".", "DeepCopy", "(", ")", "\n\n", "snapshotCopy", ".", "Spec", ".", "SnapshotDataName", "=", "snapshotDataName", "\n", "if", "status", "!=", "nil", "{", "snapshotCopy", ".", "Status", ".", "Conditions", "=", "*", "status", "\n", "}", "\n", "glog", ".", "Infof", "(", "\"", "\"", ",", "snapshotCopy", ")", "\n", "// TODO: Make diff of the two objects and then use restClient.Patch to update it", "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", "(", "\"", "\"", ",", "uniqueSnapshotName", ",", "err", ")", "\n", "}", "\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", "(", "\"", "\"", ")", "\n", "}", "\n", "className", ":=", "helper", ".", "GetPersistentVolumeClass", "(", "pv", ")", "\n", "if", "className", "==", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\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\n", "jsonBytes", ",", "err", ":=", "json", ".", "Marshal", "(", "optionsForDriver", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\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\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\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", "(", "\"", "\"", ",", "dc", ".", "Execpath", ",", "execErr", ")", "\n", "return", "nil", ",", "execErr", "\n", "}", "\n\n", "klog", ".", "Warningf", "(", "\"", "\"", ",", "dc", ".", "Execpath", ",", "dc", ".", "args", ",", "execErr", ".", "Error", "(", ")", ",", "output", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "status", ",", "err", ":=", "handleCmdResponse", "(", "dc", ".", "Command", ",", "output", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\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\n", "for", "key", ",", "value", ":=", "range", "extraOptions", "{", "options", "[", "key", "]", "=", "value", "\n", "}", "\n\n", "for", "key", ",", "value", ":=", "range", "volumeOptions", "{", "options", "[", "key", "]", "=", "value", "\n", "}", "\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\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", "(", ")", ",", "\"", "\"", ",", "namespace", ",", "optionsModifier", ")", ",", "&", "batch_v1", ".", "Job", "{", "}", ",", "resyncPeriod", ",", "cache", ".", "Indexers", "{", "cache", ".", "NamespaceIndex", ":", "cache", ".", "MetaNamespaceIndexFunc", "}", ",", ")", "\n", "}", ")", "\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", "(", "\"", "\"", ",", "key", ")", "\n", "queue", ".", "Add", "(", "key", ")", "\n", "}", "\n", "return", "\n", "}", ",", "DeleteFunc", ":", "func", "(", "obj", "interface", "{", "}", ")", "{", "key", ",", "err", ":=", "cache", ".", "DeletionHandlingMetaNamespaceKeyFunc", "(", "obj", ")", "\n", "if", "err", "==", "nil", "{", "glog", ".", "Infof", "(", "\"", "\"", ",", "key", ")", "\n", "queue", ".", "Add", "(", "key", ")", "\n", "}", "\n", "}", ",", "}", ")", "\n\n", "return", "&", "jobController", "{", "RuntimeConfig", ":", "config", ",", "namespace", ":", "namespace", ",", "queue", ":", "queue", ",", "jobLister", ":", "batchlisters", ".", "NewJobLister", "(", "informer", ".", "GetIndexer", "(", ")", ")", ",", "}", ",", "nil", "\n\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\n", "defer", "c", ".", "queue", ".", "Done", "(", "key", ")", "\n\n", "err", ":=", "c", ".", "processItem", "(", "key", ".", "(", "string", ")", ")", "\n", "if", "err", "==", "nil", "{", "// No error, tell the queue to stop tracking history", "c", ".", "queue", ".", "Forget", "(", "key", ")", "\n", "}", "else", "if", "c", ".", "queue", ".", "NumRequeues", "(", "key", ")", "<", "maxRetries", "{", "glog", ".", "Errorf", "(", "\"", "\"", ",", "key", ",", "err", ")", "\n", "// requeue the item to work on later", "c", ".", "queue", ".", "AddRateLimited", "(", "key", ")", "\n", "}", "else", "{", "// err != nil and too many retries", "glog", ".", "Errorf", "(", "\"", "\"", ",", "key", ",", "err", ")", "\n", "c", ".", "queue", ".", "Forget", "(", "key", ")", "\n", "utilruntime", ".", "HandleError", "(", "err", ")", "\n", "}", "\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\n", "if", "err", "!=", "nil", "{", "glog", ".", "Warningf", "(", "\"", "\"", ",", "jobName", ",", "err", ")", "\n", "return", "true", "\n", "}", "\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", "(", "\"", "\"", ",", "jobName", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\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", "(", "\"", "\"", ",", "startTimeStr", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "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", "(", "\"", "\"", ",", "job", ".", "Name", ")", "\n", "}", "\n\n", "if", "err", ":=", "c", ".", "RuntimeConfig", ".", "APIUtil", ".", "DeleteJob", "(", "job", ".", "Name", ",", "c", ".", "namespace", ")", ";", "err", "!=", "nil", "{", "return", "CSUnknown", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "job", ".", "Name", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\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", "// Container definition", "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", "{", "// We only have one way to clean filesystem, so no need to customize", "// filesystem cleaner command.", "jobContainer", ".", "Command", "=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "jobContainer", ".", "Env", "=", "[", "]", "apiv1", ".", "EnvVar", "{", "{", "Name", ":", "common", ".", "LocalFilesystemEnv", ",", "Value", ":", "mountPath", "}", "}", "\n", "}", "else", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "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\n", "// Make job query-able by some useful labels for admins.", "labels", ":=", "map", "[", "string", "]", "string", "{", "common", ".", "NodeNameLabel", ":", "nodeName", ",", "PVLabel", ":", "pv", ".", "Name", ",", "PVUuidLabel", ":", "string", "(", "pv", ".", "UID", ")", ",", "}", "\n\n", "// 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", ")", ",", "}", "\n\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\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", "(", "\"", "\"", ",", "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", "(", "\"", "\"", ")", "\n", "if", "nodeName", "==", "\"", "\"", "{", "glog", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "openebsObj", "mApiv1", ".", "OpenEBSVolume", "\n\n", "//Get maya-apiserver IP address from cluster", "addr", ",", "err", ":=", "openebsObj", ".", "GetMayaClusterIP", "(", "client", ")", "\n\n", "if", "err", "!=", "nil", "{", "glog", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n", "mayaServiceURI", ":=", "\"", "\"", "+", "addr", "+", "\"", "\"", "\n\n", "//Set maya-apiserver IP address along with default port", "os", ".", "Setenv", "(", "\"", "\"", ",", "mayaServiceURI", ")", "\n\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\n", "snapshotName", ":=", "MakeSnapshotName", "(", "snapshot", ")", "\n", "glog", ".", "Infof", "(", "\"", "\"", ",", "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\n", "glog", ".", "Infof", "(", "\"", "\"", ",", "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", "(", "\"", "\"", ")", "\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
asaskevich/govalidator
utils.go
SafeFileName
func SafeFileName(str string) string { name := strings.ToLower(str) name = path.Clean(path.Base(name)) name = strings.Trim(name, " ") separators, err := regexp.Compile(`[ &_=+:]`) if err == nil { name = separators.ReplaceAllString(name, "-") } legal, err := regexp.Compile(`[^[:alnum:]-.]`) if err == nil { name = legal.ReplaceAllString(name, "") } for strings.Contains(name, "--") { name = strings.Replace(name, "--", "-", -1) } return name }
go
func SafeFileName(str string) string { name := strings.ToLower(str) name = path.Clean(path.Base(name)) name = strings.Trim(name, " ") separators, err := regexp.Compile(`[ &_=+:]`) if err == nil { name = separators.ReplaceAllString(name, "-") } legal, err := regexp.Compile(`[^[:alnum:]-.]`) if err == nil { name = legal.ReplaceAllString(name, "") } for strings.Contains(name, "--") { name = strings.Replace(name, "--", "-", -1) } return name }
[ "func", "SafeFileName", "(", "str", "string", ")", "string", "{", "name", ":=", "strings", ".", "ToLower", "(", "str", ")", "\n", "name", "=", "path", ".", "Clean", "(", "path", ".", "Base", "(", "name", ")", ")", "\n", "name", "=", "strings", ".", "Trim", "(", "name", ",", "\"", "\"", ")", "\n", "separators", ",", "err", ":=", "regexp", ".", "Compile", "(", "`[ &_=+:]`", ")", "\n", "if", "err", "==", "nil", "{", "name", "=", "separators", ".", "ReplaceAllString", "(", "name", ",", "\"", "\"", ")", "\n", "}", "\n", "legal", ",", "err", ":=", "regexp", ".", "Compile", "(", "`[^[:alnum:]-.]`", ")", "\n", "if", "err", "==", "nil", "{", "name", "=", "legal", ".", "ReplaceAllString", "(", "name", ",", "\"", "\"", ")", "\n", "}", "\n", "for", "strings", ".", "Contains", "(", "name", ",", "\"", "\"", ")", "{", "name", "=", "strings", ".", "Replace", "(", "name", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "}", "\n", "return", "name", "\n", "}" ]
// SafeFileName return safe string that can be used in file names
[ "SafeFileName", "return", "safe", "string", "that", "can", "be", "used", "in", "file", "names" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L152-L168
train
asaskevich/govalidator
utils.go
Truncate
func Truncate(str string, length int, ending string) string { var aftstr, befstr string if len(str) > length { words := strings.Fields(str) before, present := 0, 0 for i := range words { befstr = aftstr before = present aftstr = aftstr + words[i] + " " present = len(aftstr) if present > length && i != 0 { if (length - before) < (present - length) { return Trim(befstr, " /\\.,\"'#!?&@+-") + ending } return Trim(aftstr, " /\\.,\"'#!?&@+-") + ending } } } return str }
go
func Truncate(str string, length int, ending string) string { var aftstr, befstr string if len(str) > length { words := strings.Fields(str) before, present := 0, 0 for i := range words { befstr = aftstr before = present aftstr = aftstr + words[i] + " " present = len(aftstr) if present > length && i != 0 { if (length - before) < (present - length) { return Trim(befstr, " /\\.,\"'#!?&@+-") + ending } return Trim(aftstr, " /\\.,\"'#!?&@+-") + ending } } } return str }
[ "func", "Truncate", "(", "str", "string", ",", "length", "int", ",", "ending", "string", ")", "string", "{", "var", "aftstr", ",", "befstr", "string", "\n", "if", "len", "(", "str", ")", ">", "length", "{", "words", ":=", "strings", ".", "Fields", "(", "str", ")", "\n", "before", ",", "present", ":=", "0", ",", "0", "\n", "for", "i", ":=", "range", "words", "{", "befstr", "=", "aftstr", "\n", "before", "=", "present", "\n", "aftstr", "=", "aftstr", "+", "words", "[", "i", "]", "+", "\"", "\"", "\n", "present", "=", "len", "(", "aftstr", ")", "\n", "if", "present", ">", "length", "&&", "i", "!=", "0", "{", "if", "(", "length", "-", "before", ")", "<", "(", "present", "-", "length", ")", "{", "return", "Trim", "(", "befstr", ",", "\"", "\\\\", "\\\"", "\"", ")", "+", "ending", "\n", "}", "\n", "return", "Trim", "(", "aftstr", ",", "\"", "\\\\", "\\\"", "\"", ")", "+", "ending", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "str", "\n", "}" ]
// Truncate a string to the closest length without breaking words.
[ "Truncate", "a", "string", "to", "the", "closest", "length", "without", "breaking", "words", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L191-L211
train
asaskevich/govalidator
utils.go
PadLeft
func PadLeft(str string, padStr string, padLen int) string { return buildPadStr(str, padStr, padLen, true, false) }
go
func PadLeft(str string, padStr string, padLen int) string { return buildPadStr(str, padStr, padLen, true, false) }
[ "func", "PadLeft", "(", "str", "string", ",", "padStr", "string", ",", "padLen", "int", ")", "string", "{", "return", "buildPadStr", "(", "str", ",", "padStr", ",", "padLen", ",", "true", ",", "false", ")", "\n", "}" ]
// PadLeft pad left side of string if size of string is less then indicated pad length
[ "PadLeft", "pad", "left", "side", "of", "string", "if", "size", "of", "string", "is", "less", "then", "indicated", "pad", "length" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L214-L216
train
asaskevich/govalidator
utils.go
PadBoth
func PadBoth(str string, padStr string, padLen int) string { return buildPadStr(str, padStr, padLen, true, true) }
go
func PadBoth(str string, padStr string, padLen int) string { return buildPadStr(str, padStr, padLen, true, true) }
[ "func", "PadBoth", "(", "str", "string", ",", "padStr", "string", ",", "padLen", "int", ")", "string", "{", "return", "buildPadStr", "(", "str", ",", "padStr", ",", "padLen", ",", "true", ",", "true", ")", "\n", "}" ]
// PadBoth pad sides of string if size of string is less then indicated pad length
[ "PadBoth", "pad", "sides", "of", "string", "if", "size", "of", "string", "is", "less", "then", "indicated", "pad", "length" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L224-L226
train
asaskevich/govalidator
utils.go
buildPadStr
func buildPadStr(str string, padStr string, padLen int, padLeft bool, padRight bool) string { // When padded length is less then the current string size if padLen < utf8.RuneCountInString(str) { return str } padLen -= utf8.RuneCountInString(str) targetLen := padLen targetLenLeft := targetLen targetLenRight := targetLen if padLeft && padRight { targetLenLeft = padLen / 2 targetLenRight = padLen - targetLenLeft } strToRepeatLen := utf8.RuneCountInString(padStr) repeatTimes := int(math.Ceil(float64(targetLen) / float64(strToRepeatLen))) repeatedString := strings.Repeat(padStr, repeatTimes) leftSide := "" if padLeft { leftSide = repeatedString[0:targetLenLeft] } rightSide := "" if padRight { rightSide = repeatedString[0:targetLenRight] } return leftSide + str + rightSide }
go
func buildPadStr(str string, padStr string, padLen int, padLeft bool, padRight bool) string { // When padded length is less then the current string size if padLen < utf8.RuneCountInString(str) { return str } padLen -= utf8.RuneCountInString(str) targetLen := padLen targetLenLeft := targetLen targetLenRight := targetLen if padLeft && padRight { targetLenLeft = padLen / 2 targetLenRight = padLen - targetLenLeft } strToRepeatLen := utf8.RuneCountInString(padStr) repeatTimes := int(math.Ceil(float64(targetLen) / float64(strToRepeatLen))) repeatedString := strings.Repeat(padStr, repeatTimes) leftSide := "" if padLeft { leftSide = repeatedString[0:targetLenLeft] } rightSide := "" if padRight { rightSide = repeatedString[0:targetLenRight] } return leftSide + str + rightSide }
[ "func", "buildPadStr", "(", "str", "string", ",", "padStr", "string", ",", "padLen", "int", ",", "padLeft", "bool", ",", "padRight", "bool", ")", "string", "{", "// When padded length is less then the current string size", "if", "padLen", "<", "utf8", ".", "RuneCountInString", "(", "str", ")", "{", "return", "str", "\n", "}", "\n\n", "padLen", "-=", "utf8", ".", "RuneCountInString", "(", "str", ")", "\n\n", "targetLen", ":=", "padLen", "\n\n", "targetLenLeft", ":=", "targetLen", "\n", "targetLenRight", ":=", "targetLen", "\n", "if", "padLeft", "&&", "padRight", "{", "targetLenLeft", "=", "padLen", "/", "2", "\n", "targetLenRight", "=", "padLen", "-", "targetLenLeft", "\n", "}", "\n\n", "strToRepeatLen", ":=", "utf8", ".", "RuneCountInString", "(", "padStr", ")", "\n\n", "repeatTimes", ":=", "int", "(", "math", ".", "Ceil", "(", "float64", "(", "targetLen", ")", "/", "float64", "(", "strToRepeatLen", ")", ")", ")", "\n", "repeatedString", ":=", "strings", ".", "Repeat", "(", "padStr", ",", "repeatTimes", ")", "\n\n", "leftSide", ":=", "\"", "\"", "\n", "if", "padLeft", "{", "leftSide", "=", "repeatedString", "[", "0", ":", "targetLenLeft", "]", "\n", "}", "\n\n", "rightSide", ":=", "\"", "\"", "\n", "if", "padRight", "{", "rightSide", "=", "repeatedString", "[", "0", ":", "targetLenRight", "]", "\n", "}", "\n\n", "return", "leftSide", "+", "str", "+", "rightSide", "\n", "}" ]
// PadString either left, right or both sides, not the padding string can be unicode and more then one // character
[ "PadString", "either", "left", "right", "or", "both", "sides", "not", "the", "padding", "string", "can", "be", "unicode", "and", "more", "then", "one", "character" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L230-L264
train
asaskevich/govalidator
utils.go
TruncatingErrorf
func TruncatingErrorf(str string, args ...interface{}) error { n := strings.Count(str, "%s") return fmt.Errorf(str, args[:n]...) }
go
func TruncatingErrorf(str string, args ...interface{}) error { n := strings.Count(str, "%s") return fmt.Errorf(str, args[:n]...) }
[ "func", "TruncatingErrorf", "(", "str", "string", ",", "args", "...", "interface", "{", "}", ")", "error", "{", "n", ":=", "strings", ".", "Count", "(", "str", ",", "\"", "\"", ")", "\n", "return", "fmt", ".", "Errorf", "(", "str", ",", "args", "[", ":", "n", "]", "...", ")", "\n", "}" ]
// TruncatingErrorf removes extra args from fmt.Errorf if not formatted in the str object
[ "TruncatingErrorf", "removes", "extra", "args", "from", "fmt", ".", "Errorf", "if", "not", "formatted", "in", "the", "str", "object" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/utils.go#L267-L270
train
asaskevich/govalidator
converter.go
ToJSON
func ToJSON(obj interface{}) (string, error) { res, err := json.Marshal(obj) if err != nil { res = []byte("") } return string(res), err }
go
func ToJSON(obj interface{}) (string, error) { res, err := json.Marshal(obj) if err != nil { res = []byte("") } return string(res), err }
[ "func", "ToJSON", "(", "obj", "interface", "{", "}", ")", "(", "string", ",", "error", ")", "{", "res", ",", "err", ":=", "json", ".", "Marshal", "(", "obj", ")", "\n", "if", "err", "!=", "nil", "{", "res", "=", "[", "]", "byte", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "string", "(", "res", ")", ",", "err", "\n", "}" ]
// ToJSON convert the input to a valid JSON string
[ "ToJSON", "convert", "the", "input", "to", "a", "valid", "JSON", "string" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/converter.go#L17-L23
train
asaskevich/govalidator
converter.go
ToFloat
func ToFloat(str string) (float64, error) { res, err := strconv.ParseFloat(str, 64) if err != nil { res = 0.0 } return res, err }
go
func ToFloat(str string) (float64, error) { res, err := strconv.ParseFloat(str, 64) if err != nil { res = 0.0 } return res, err }
[ "func", "ToFloat", "(", "str", "string", ")", "(", "float64", ",", "error", ")", "{", "res", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "str", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "res", "=", "0.0", "\n", "}", "\n", "return", "res", ",", "err", "\n", "}" ]
// ToFloat convert the input string to a float, or 0.0 if the input is not a float.
[ "ToFloat", "convert", "the", "input", "string", "to", "a", "float", "or", "0", ".", "0", "if", "the", "input", "is", "not", "a", "float", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/converter.go#L26-L32
train
asaskevich/govalidator
converter.go
ToInt
func ToInt(value interface{}) (res int64, err error) { val := reflect.ValueOf(value) switch value.(type) { case int, int8, int16, int32, int64: res = val.Int() case uint, uint8, uint16, uint32, uint64: res = int64(val.Uint()) case string: if IsInt(val.String()) { res, err = strconv.ParseInt(val.String(), 0, 64) if err != nil { res = 0 } } else { err = fmt.Errorf("math: square root of negative number %g", value) res = 0 } default: err = fmt.Errorf("math: square root of negative number %g", value) res = 0 } return }
go
func ToInt(value interface{}) (res int64, err error) { val := reflect.ValueOf(value) switch value.(type) { case int, int8, int16, int32, int64: res = val.Int() case uint, uint8, uint16, uint32, uint64: res = int64(val.Uint()) case string: if IsInt(val.String()) { res, err = strconv.ParseInt(val.String(), 0, 64) if err != nil { res = 0 } } else { err = fmt.Errorf("math: square root of negative number %g", value) res = 0 } default: err = fmt.Errorf("math: square root of negative number %g", value) res = 0 } return }
[ "func", "ToInt", "(", "value", "interface", "{", "}", ")", "(", "res", "int64", ",", "err", "error", ")", "{", "val", ":=", "reflect", ".", "ValueOf", "(", "value", ")", "\n\n", "switch", "value", ".", "(", "type", ")", "{", "case", "int", ",", "int8", ",", "int16", ",", "int32", ",", "int64", ":", "res", "=", "val", ".", "Int", "(", ")", "\n", "case", "uint", ",", "uint8", ",", "uint16", ",", "uint32", ",", "uint64", ":", "res", "=", "int64", "(", "val", ".", "Uint", "(", ")", ")", "\n", "case", "string", ":", "if", "IsInt", "(", "val", ".", "String", "(", ")", ")", "{", "res", ",", "err", "=", "strconv", ".", "ParseInt", "(", "val", ".", "String", "(", ")", ",", "0", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "res", "=", "0", "\n", "}", "\n", "}", "else", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "value", ")", "\n", "res", "=", "0", "\n", "}", "\n", "default", ":", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "value", ")", "\n", "res", "=", "0", "\n", "}", "\n\n", "return", "\n", "}" ]
// ToInt convert the input string or any int type to an integer type 64, or 0 if the input is not an integer.
[ "ToInt", "convert", "the", "input", "string", "or", "any", "int", "type", "to", "an", "integer", "type", "64", "or", "0", "if", "the", "input", "is", "not", "an", "integer", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/converter.go#L35-L59
train
asaskevich/govalidator
numerics.go
InRange
func InRange(value interface{}, left interface{}, right interface{}) bool { reflectValue := reflect.TypeOf(value).Kind() reflectLeft := reflect.TypeOf(left).Kind() reflectRight := reflect.TypeOf(right).Kind() if reflectValue == reflect.Int && reflectLeft == reflect.Int && reflectRight == reflect.Int { return InRangeInt(value.(int), left.(int), right.(int)) } else if reflectValue == reflect.Float32 && reflectLeft == reflect.Float32 && reflectRight == reflect.Float32 { return InRangeFloat32(value.(float32), left.(float32), right.(float32)) } else if reflectValue == reflect.Float64 && reflectLeft == reflect.Float64 && reflectRight == reflect.Float64 { return InRangeFloat64(value.(float64), left.(float64), right.(float64)) } else { return false } }
go
func InRange(value interface{}, left interface{}, right interface{}) bool { reflectValue := reflect.TypeOf(value).Kind() reflectLeft := reflect.TypeOf(left).Kind() reflectRight := reflect.TypeOf(right).Kind() if reflectValue == reflect.Int && reflectLeft == reflect.Int && reflectRight == reflect.Int { return InRangeInt(value.(int), left.(int), right.(int)) } else if reflectValue == reflect.Float32 && reflectLeft == reflect.Float32 && reflectRight == reflect.Float32 { return InRangeFloat32(value.(float32), left.(float32), right.(float32)) } else if reflectValue == reflect.Float64 && reflectLeft == reflect.Float64 && reflectRight == reflect.Float64 { return InRangeFloat64(value.(float64), left.(float64), right.(float64)) } else { return false } }
[ "func", "InRange", "(", "value", "interface", "{", "}", ",", "left", "interface", "{", "}", ",", "right", "interface", "{", "}", ")", "bool", "{", "reflectValue", ":=", "reflect", ".", "TypeOf", "(", "value", ")", ".", "Kind", "(", ")", "\n", "reflectLeft", ":=", "reflect", ".", "TypeOf", "(", "left", ")", ".", "Kind", "(", ")", "\n", "reflectRight", ":=", "reflect", ".", "TypeOf", "(", "right", ")", ".", "Kind", "(", ")", "\n\n", "if", "reflectValue", "==", "reflect", ".", "Int", "&&", "reflectLeft", "==", "reflect", ".", "Int", "&&", "reflectRight", "==", "reflect", ".", "Int", "{", "return", "InRangeInt", "(", "value", ".", "(", "int", ")", ",", "left", ".", "(", "int", ")", ",", "right", ".", "(", "int", ")", ")", "\n", "}", "else", "if", "reflectValue", "==", "reflect", ".", "Float32", "&&", "reflectLeft", "==", "reflect", ".", "Float32", "&&", "reflectRight", "==", "reflect", ".", "Float32", "{", "return", "InRangeFloat32", "(", "value", ".", "(", "float32", ")", ",", "left", ".", "(", "float32", ")", ",", "right", ".", "(", "float32", ")", ")", "\n", "}", "else", "if", "reflectValue", "==", "reflect", ".", "Float64", "&&", "reflectLeft", "==", "reflect", ".", "Float64", "&&", "reflectRight", "==", "reflect", ".", "Float64", "{", "return", "InRangeFloat64", "(", "value", ".", "(", "float64", ")", ",", "left", ".", "(", "float64", ")", ",", "right", ".", "(", "float64", ")", ")", "\n", "}", "else", "{", "return", "false", "\n", "}", "\n", "}" ]
// InRange returns true if value lies between left and right border, generic type to handle int, float32 or float64, all types must the same type
[ "InRange", "returns", "true", "if", "value", "lies", "between", "left", "and", "right", "border", "generic", "type", "to", "handle", "int", "float32", "or", "float64", "all", "types", "must", "the", "same", "type" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/numerics.go#L72-L87
train
asaskevich/govalidator
validator.go
IsExistingEmail
func IsExistingEmail(email string) bool { if len(email) < 6 || len(email) > 254 { return false } at := strings.LastIndex(email, "@") if at <= 0 || at > len(email)-3 { return false } user := email[:at] host := email[at+1:] if len(user) > 64 { return false } if userDotRegexp.MatchString(user) || !userRegexp.MatchString(user) || !hostRegexp.MatchString(host) { return false } switch host { case "localhost", "example.com": return true } if _, err := net.LookupMX(host); err != nil { if _, err := net.LookupIP(host); err != nil { return false } } return true }
go
func IsExistingEmail(email string) bool { if len(email) < 6 || len(email) > 254 { return false } at := strings.LastIndex(email, "@") if at <= 0 || at > len(email)-3 { return false } user := email[:at] host := email[at+1:] if len(user) > 64 { return false } if userDotRegexp.MatchString(user) || !userRegexp.MatchString(user) || !hostRegexp.MatchString(host) { return false } switch host { case "localhost", "example.com": return true } if _, err := net.LookupMX(host); err != nil { if _, err := net.LookupIP(host); err != nil { return false } } return true }
[ "func", "IsExistingEmail", "(", "email", "string", ")", "bool", "{", "if", "len", "(", "email", ")", "<", "6", "||", "len", "(", "email", ")", ">", "254", "{", "return", "false", "\n", "}", "\n", "at", ":=", "strings", ".", "LastIndex", "(", "email", ",", "\"", "\"", ")", "\n", "if", "at", "<=", "0", "||", "at", ">", "len", "(", "email", ")", "-", "3", "{", "return", "false", "\n", "}", "\n", "user", ":=", "email", "[", ":", "at", "]", "\n", "host", ":=", "email", "[", "at", "+", "1", ":", "]", "\n", "if", "len", "(", "user", ")", ">", "64", "{", "return", "false", "\n", "}", "\n", "if", "userDotRegexp", ".", "MatchString", "(", "user", ")", "||", "!", "userRegexp", ".", "MatchString", "(", "user", ")", "||", "!", "hostRegexp", ".", "MatchString", "(", "host", ")", "{", "return", "false", "\n", "}", "\n", "switch", "host", "{", "case", "\"", "\"", ",", "\"", "\"", ":", "return", "true", "\n", "}", "\n", "if", "_", ",", "err", ":=", "net", ".", "LookupMX", "(", "host", ")", ";", "err", "!=", "nil", "{", "if", "_", ",", "err", ":=", "net", ".", "LookupIP", "(", "host", ")", ";", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// IsExistingEmail check if the string is an email of existing domain
[ "IsExistingEmail", "check", "if", "the", "string", "is", "an", "email", "of", "existing", "domain" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L73-L101
train
asaskevich/govalidator
validator.go
IsRequestURL
func IsRequestURL(rawurl string) bool { url, err := url.ParseRequestURI(rawurl) if err != nil { return false //Couldn't even parse the rawurl } if len(url.Scheme) == 0 { return false //No Scheme found } return true }
go
func IsRequestURL(rawurl string) bool { url, err := url.ParseRequestURI(rawurl) if err != nil { return false //Couldn't even parse the rawurl } if len(url.Scheme) == 0 { return false //No Scheme found } return true }
[ "func", "IsRequestURL", "(", "rawurl", "string", ")", "bool", "{", "url", ",", "err", ":=", "url", ".", "ParseRequestURI", "(", "rawurl", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "//Couldn't even parse the rawurl", "\n", "}", "\n", "if", "len", "(", "url", ".", "Scheme", ")", "==", "0", "{", "return", "false", "//No Scheme found", "\n", "}", "\n", "return", "true", "\n", "}" ]
// IsRequestURL check if the string rawurl, assuming // it was received in an HTTP request, is a valid // URL confirm to RFC 3986
[ "IsRequestURL", "check", "if", "the", "string", "rawurl", "assuming", "it", "was", "received", "in", "an", "HTTP", "request", "is", "a", "valid", "URL", "confirm", "to", "RFC", "3986" ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L130-L139
train
asaskevich/govalidator
validator.go
IsRequestURI
func IsRequestURI(rawurl string) bool { _, err := url.ParseRequestURI(rawurl) return err == nil }
go
func IsRequestURI(rawurl string) bool { _, err := url.ParseRequestURI(rawurl) return err == nil }
[ "func", "IsRequestURI", "(", "rawurl", "string", ")", "bool", "{", "_", ",", "err", ":=", "url", ".", "ParseRequestURI", "(", "rawurl", ")", "\n", "return", "err", "==", "nil", "\n", "}" ]
// IsRequestURI check if the string rawurl, assuming // it was received in an HTTP request, is an // absolute URI or an absolute path.
[ "IsRequestURI", "check", "if", "the", "string", "rawurl", "assuming", "it", "was", "received", "in", "an", "HTTP", "request", "is", "an", "absolute", "URI", "or", "an", "absolute", "path", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L144-L147
train
asaskevich/govalidator
validator.go
IsLowerCase
func IsLowerCase(str string) bool { if IsNull(str) { return true } return str == strings.ToLower(str) }
go
func IsLowerCase(str string) bool { if IsNull(str) { return true } return str == strings.ToLower(str) }
[ "func", "IsLowerCase", "(", "str", "string", ")", "bool", "{", "if", "IsNull", "(", "str", ")", "{", "return", "true", "\n", "}", "\n", "return", "str", "==", "strings", ".", "ToLower", "(", "str", ")", "\n", "}" ]
// IsLowerCase check if the string is lowercase. Empty string is valid.
[ "IsLowerCase", "check", "if", "the", "string", "is", "lowercase", ".", "Empty", "string", "is", "valid", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L262-L267
train
asaskevich/govalidator
validator.go
IsUpperCase
func IsUpperCase(str string) bool { if IsNull(str) { return true } return str == strings.ToUpper(str) }
go
func IsUpperCase(str string) bool { if IsNull(str) { return true } return str == strings.ToUpper(str) }
[ "func", "IsUpperCase", "(", "str", "string", ")", "bool", "{", "if", "IsNull", "(", "str", ")", "{", "return", "true", "\n", "}", "\n", "return", "str", "==", "strings", ".", "ToUpper", "(", "str", ")", "\n", "}" ]
// IsUpperCase check if the string is uppercase. Empty string is valid.
[ "IsUpperCase", "check", "if", "the", "string", "is", "uppercase", ".", "Empty", "string", "is", "valid", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L270-L275
train
asaskevich/govalidator
validator.go
HasLowerCase
func HasLowerCase(str string) bool { if IsNull(str) { return true } return rxHasLowerCase.MatchString(str) }
go
func HasLowerCase(str string) bool { if IsNull(str) { return true } return rxHasLowerCase.MatchString(str) }
[ "func", "HasLowerCase", "(", "str", "string", ")", "bool", "{", "if", "IsNull", "(", "str", ")", "{", "return", "true", "\n", "}", "\n", "return", "rxHasLowerCase", ".", "MatchString", "(", "str", ")", "\n", "}" ]
// HasLowerCase check if the string contains at least 1 lowercase. Empty string is valid.
[ "HasLowerCase", "check", "if", "the", "string", "contains", "at", "least", "1", "lowercase", ".", "Empty", "string", "is", "valid", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L278-L283
train
asaskevich/govalidator
validator.go
HasUpperCase
func HasUpperCase(str string) bool { if IsNull(str) { return true } return rxHasUpperCase.MatchString(str) }
go
func HasUpperCase(str string) bool { if IsNull(str) { return true } return rxHasUpperCase.MatchString(str) }
[ "func", "HasUpperCase", "(", "str", "string", ")", "bool", "{", "if", "IsNull", "(", "str", ")", "{", "return", "true", "\n", "}", "\n", "return", "rxHasUpperCase", ".", "MatchString", "(", "str", ")", "\n", "}" ]
// HasUpperCase check if the string contians as least 1 uppercase. Empty string is valid.
[ "HasUpperCase", "check", "if", "the", "string", "contians", "as", "least", "1", "uppercase", ".", "Empty", "string", "is", "valid", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L286-L291
train
asaskevich/govalidator
validator.go
IsInt
func IsInt(str string) bool { if IsNull(str) { return true } return rxInt.MatchString(str) }
go
func IsInt(str string) bool { if IsNull(str) { return true } return rxInt.MatchString(str) }
[ "func", "IsInt", "(", "str", "string", ")", "bool", "{", "if", "IsNull", "(", "str", ")", "{", "return", "true", "\n", "}", "\n", "return", "rxInt", ".", "MatchString", "(", "str", ")", "\n", "}" ]
// IsInt check if the string is an integer. Empty string is valid.
[ "IsInt", "check", "if", "the", "string", "is", "an", "integer", ".", "Empty", "string", "is", "valid", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L294-L299
train
asaskevich/govalidator
validator.go
IsFullWidth
func IsFullWidth(str string) bool { if IsNull(str) { return true } return rxFullWidth.MatchString(str) }
go
func IsFullWidth(str string) bool { if IsNull(str) { return true } return rxFullWidth.MatchString(str) }
[ "func", "IsFullWidth", "(", "str", "string", ")", "bool", "{", "if", "IsNull", "(", "str", ")", "{", "return", "true", "\n", "}", "\n", "return", "rxFullWidth", ".", "MatchString", "(", "str", ")", "\n", "}" ]
// IsFullWidth check if the string contains any full-width chars. Empty string is valid.
[ "IsFullWidth", "check", "if", "the", "string", "contains", "any", "full", "-", "width", "chars", ".", "Empty", "string", "is", "valid", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L464-L469
train
asaskevich/govalidator
validator.go
IsHalfWidth
func IsHalfWidth(str string) bool { if IsNull(str) { return true } return rxHalfWidth.MatchString(str) }
go
func IsHalfWidth(str string) bool { if IsNull(str) { return true } return rxHalfWidth.MatchString(str) }
[ "func", "IsHalfWidth", "(", "str", "string", ")", "bool", "{", "if", "IsNull", "(", "str", ")", "{", "return", "true", "\n", "}", "\n", "return", "rxHalfWidth", ".", "MatchString", "(", "str", ")", "\n", "}" ]
// IsHalfWidth check if the string contains any half-width chars. Empty string is valid.
[ "IsHalfWidth", "check", "if", "the", "string", "contains", "any", "half", "-", "width", "chars", ".", "Empty", "string", "is", "valid", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L472-L477
train
asaskevich/govalidator
validator.go
IsVariableWidth
func IsVariableWidth(str string) bool { if IsNull(str) { return true } return rxHalfWidth.MatchString(str) && rxFullWidth.MatchString(str) }
go
func IsVariableWidth(str string) bool { if IsNull(str) { return true } return rxHalfWidth.MatchString(str) && rxFullWidth.MatchString(str) }
[ "func", "IsVariableWidth", "(", "str", "string", ")", "bool", "{", "if", "IsNull", "(", "str", ")", "{", "return", "true", "\n", "}", "\n", "return", "rxHalfWidth", ".", "MatchString", "(", "str", ")", "&&", "rxFullWidth", ".", "MatchString", "(", "str", ")", "\n", "}" ]
// IsVariableWidth check if the string contains a mixture of full and half-width chars. Empty string is valid.
[ "IsVariableWidth", "check", "if", "the", "string", "contains", "a", "mixture", "of", "full", "and", "half", "-", "width", "chars", ".", "Empty", "string", "is", "valid", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L480-L485
train
asaskevich/govalidator
validator.go
IsFilePath
func IsFilePath(str string) (bool, int) { if rxWinPath.MatchString(str) { //check windows path limit see: // http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath if len(str[3:]) > 32767 { return false, Win } return true, Win } else if rxUnixPath.MatchString(str) { return true, Unix } return false, Unknown }
go
func IsFilePath(str string) (bool, int) { if rxWinPath.MatchString(str) { //check windows path limit see: // http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath if len(str[3:]) > 32767 { return false, Win } return true, Win } else if rxUnixPath.MatchString(str) { return true, Unix } return false, Unknown }
[ "func", "IsFilePath", "(", "str", "string", ")", "(", "bool", ",", "int", ")", "{", "if", "rxWinPath", ".", "MatchString", "(", "str", ")", "{", "//check windows path limit see:", "// http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath", "if", "len", "(", "str", "[", "3", ":", "]", ")", ">", "32767", "{", "return", "false", ",", "Win", "\n", "}", "\n", "return", "true", ",", "Win", "\n", "}", "else", "if", "rxUnixPath", ".", "MatchString", "(", "str", ")", "{", "return", "true", ",", "Unix", "\n", "}", "\n", "return", "false", ",", "Unknown", "\n", "}" ]
// IsFilePath check is a string is Win or Unix file path and returns it's type.
[ "IsFilePath", "check", "is", "a", "string", "is", "Win", "or", "Unix", "file", "path", "and", "returns", "it", "s", "type", "." ]
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/validator.go#L493-L505
train