repo stringlengths 5 67 | sha stringlengths 40 40 | path stringlengths 4 234 | url stringlengths 85 339 | language stringclasses 6 values | split stringclasses 3 values | doc stringlengths 3 51.2k | sign stringlengths 5 8.01k | problem stringlengths 13 51.2k | output stringlengths 0 3.87M |
|---|---|---|---|---|---|---|---|---|---|
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L1927-L1929 | go | train | // BackendService Management
// GetBackendService retrieves a backend by name. | func (gce *Cloud) GetBackendService(name string) (*compute.BackendService, error) | // BackendService Management
// GetBackendService retrieves a backend by name.
func (gce *Cloud) GetBackendService(name string) (*compute.BackendService, error) | {
return gce.service.BackendServices.Get(gce.projectID, name).Do()
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L1932-L1938 | go | train | // UpdateBackendService applies the given BackendService as an update to an existing service. | func (gce *Cloud) UpdateBackendService(bg *compute.BackendService) error | // UpdateBackendService applies the given BackendService as an update to an existing service.
func (gce *Cloud) UpdateBackendService(bg *compute.BackendService) error | {
op, err := gce.service.BackendServices.Update(gce.projectID, bg.Name, bg).Do()
if err != nil {
return err
}
return gce.waitForGlobalOp(op)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L1953-L1959 | go | train | // CreateBackendService creates the given BackendService. | func (gce *Cloud) CreateBackendService(bg *compute.BackendService) error | // CreateBackendService creates the given BackendService.
func (gce *Cloud) CreateBackendService(bg *compute.BackendService) error | {
op, err := gce.service.BackendServices.Insert(gce.projectID, bg).Do()
if err != nil {
return err
}
return gce.waitForGlobalOp(op)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L1962-L1965 | go | train | // ListBackendServices lists all backend services in the project. | func (gce *Cloud) ListBackendServices() (*compute.BackendServiceList, error) | // ListBackendServices lists all backend services in the project.
func (gce *Cloud) ListBackendServices() (*compute.BackendServiceList, error) | {
// TODO: use PageToken to list all not just the first 500
return gce.service.BackendServices.List(gce.projectID).Do()
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L1970-L1973 | go | train | // GetHealth returns the health of the BackendService identified by the given
// name, in the given instanceGroup. The instanceGroupLink is the fully
// qualified self link of an instance group. | func (gce *Cloud) GetHealth(name string, instanceGroupLink string) (*compute.BackendServiceGroupHealth, error) | // GetHealth returns the health of the BackendService identified by the given
// name, in the given instanceGroup. The instanceGroupLink is the fully
// qualified self link of an instance group.
func (gce *Cloud) GetHealth(name string, instanceGroupLink string) (*compute.BackendServiceGroupHealth, error) | {
groupRef := &compute.ResourceGroupReference{Group: instanceGroupLink}
return gce.service.BackendServices.GetHealth(gce.projectID, name, groupRef).Do()
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L1978-L1980 | go | train | // Health Checks
// GetHTTPHealthCheck returns the given HTTPHealthCheck by name. | func (gce *Cloud) GetHTTPHealthCheck(name string) (*compute.HttpHealthCheck, error) | // Health Checks
// GetHTTPHealthCheck returns the given HTTPHealthCheck by name.
func (gce *Cloud) GetHTTPHealthCheck(name string) (*compute.HttpHealthCheck, error) | {
return gce.service.HttpHealthChecks.Get(gce.projectID, name).Do()
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L1983-L1989 | go | train | // UpdateHTTPHealthCheck applies the given HTTPHealthCheck as an update. | func (gce *Cloud) UpdateHTTPHealthCheck(hc *compute.HttpHealthCheck) error | // UpdateHTTPHealthCheck applies the given HTTPHealthCheck as an update.
func (gce *Cloud) UpdateHTTPHealthCheck(hc *compute.HttpHealthCheck) error | {
op, err := gce.service.HttpHealthChecks.Update(gce.projectID, hc.Name, hc).Do()
if err != nil {
return err
}
return gce.waitForGlobalOp(op)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2004-L2010 | go | train | // CreateHTTPHealthCheck creates the given HTTPHealthCheck. | func (gce *Cloud) CreateHTTPHealthCheck(hc *compute.HttpHealthCheck) error | // CreateHTTPHealthCheck creates the given HTTPHealthCheck.
func (gce *Cloud) CreateHTTPHealthCheck(hc *compute.HttpHealthCheck) error | {
op, err := gce.service.HttpHealthChecks.Insert(gce.projectID, hc).Do()
if err != nil {
return err
}
return gce.waitForGlobalOp(op)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2013-L2016 | go | train | // ListHTTPHealthChecks lists all HTTPHealthChecks in the project. | func (gce *Cloud) ListHTTPHealthChecks() (*compute.HttpHealthCheckList, error) | // ListHTTPHealthChecks lists all HTTPHealthChecks in the project.
func (gce *Cloud) ListHTTPHealthChecks() (*compute.HttpHealthCheckList, error) | {
// TODO: use PageToken to list all not just the first 500
return gce.service.HttpHealthChecks.List(gce.projectID).Do()
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2021-L2031 | go | train | // InstanceGroup Management
// CreateInstanceGroup creates an instance group with the given instances. It is the callers responsibility to add named ports. | func (gce *Cloud) CreateInstanceGroup(name string, zone string) (*compute.InstanceGroup, error) | // InstanceGroup Management
// CreateInstanceGroup creates an instance group with the given instances. It is the callers responsibility to add named ports.
func (gce *Cloud) CreateInstanceGroup(name string, zone string) (*compute.InstanceGroup, error) | {
op, err := gce.service.InstanceGroups.Insert(
gce.projectID, zone, &compute.InstanceGroup{Name: name}).Do()
if err != nil {
return nil, err
}
if err = gce.waitForZoneOp(op, zone); err != nil {
return nil, err
}
return gce.GetInstanceGroup(name, zone)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2034-L2041 | go | train | // DeleteInstanceGroup deletes an instance group. | func (gce *Cloud) DeleteInstanceGroup(name string, zone string) error | // DeleteInstanceGroup deletes an instance group.
func (gce *Cloud) DeleteInstanceGroup(name string, zone string) error | {
op, err := gce.service.InstanceGroups.Delete(
gce.projectID, zone, name).Do()
if err != nil {
return err
}
return gce.waitForZoneOp(op, zone)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2044-L2047 | go | train | // ListInstanceGroups lists all InstanceGroups in the project and zone. | func (gce *Cloud) ListInstanceGroups(zone string) (*compute.InstanceGroupList, error) | // ListInstanceGroups lists all InstanceGroups in the project and zone.
func (gce *Cloud) ListInstanceGroups(zone string) (*compute.InstanceGroupList, error) | {
// TODO: use PageToken to list all not just the first 500
return gce.service.InstanceGroups.List(gce.projectID, zone).Do()
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2050-L2055 | go | train | // ListInstancesInInstanceGroup lists all the instances in a given instance group and state. | func (gce *Cloud) ListInstancesInInstanceGroup(name string, zone string, state string) (*compute.InstanceGroupsListInstances, error) | // ListInstancesInInstanceGroup lists all the instances in a given instance group and state.
func (gce *Cloud) ListInstancesInInstanceGroup(name string, zone string, state string) (*compute.InstanceGroupsListInstances, error) | {
// TODO: use PageToken to list all not just the first 500
return gce.service.InstanceGroups.ListInstances(
gce.projectID, zone, name,
&compute.InstanceGroupsListInstancesRequest{InstanceState: state}).Do()
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2058-L2077 | go | train | // AddInstancesToInstanceGroup adds the given instances to the given instance group. | func (gce *Cloud) AddInstancesToInstanceGroup(name string, zone string, instanceNames []string) error | // AddInstancesToInstanceGroup adds the given instances to the given instance group.
func (gce *Cloud) AddInstancesToInstanceGroup(name string, zone string, instanceNames []string) error | {
if len(instanceNames) == 0 {
return nil
}
// Adding the same instance twice will result in a 4xx error
instances := []*compute.InstanceReference{}
for _, ins := range instanceNames {
instances = append(instances, &compute.InstanceReference{Instance: makeHostURL(gce.projectID, zone, ins)})
}
op, err := gce.service.InstanceGroups.AddInstances(
gce.projectID, zone, name,
&compute.InstanceGroupsAddInstancesRequest{
Instances: instances,
}).Do()
if err != nil {
return err
}
return gce.waitForZoneOp(op, zone)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2080-L2102 | go | train | // RemoveInstancesFromInstanceGroup removes the given instances from the instance group. | func (gce *Cloud) RemoveInstancesFromInstanceGroup(name string, zone string, instanceNames []string) error | // RemoveInstancesFromInstanceGroup removes the given instances from the instance group.
func (gce *Cloud) RemoveInstancesFromInstanceGroup(name string, zone string, instanceNames []string) error | {
if len(instanceNames) == 0 {
return nil
}
instances := []*compute.InstanceReference{}
for _, ins := range instanceNames {
instanceLink := makeHostURL(gce.projectID, zone, ins)
instances = append(instances, &compute.InstanceReference{Instance: instanceLink})
}
op, err := gce.service.InstanceGroups.RemoveInstances(
gce.projectID, zone, name,
&compute.InstanceGroupsRemoveInstancesRequest{
Instances: instances,
}).Do()
if err != nil {
if isHTTPErrorCode(err, http.StatusNotFound) {
return nil
}
return err
}
return gce.waitForZoneOp(op, zone)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2105-L2133 | go | train | // AddPortToInstanceGroup adds a port to the given instance group. | func (gce *Cloud) AddPortToInstanceGroup(ig *compute.InstanceGroup, port int64) (*compute.NamedPort, error) | // AddPortToInstanceGroup adds a port to the given instance group.
func (gce *Cloud) AddPortToInstanceGroup(ig *compute.InstanceGroup, port int64) (*compute.NamedPort, error) | {
for _, np := range ig.NamedPorts {
if np.Port == port {
glog.V(3).Infof("Instance group %v already has named port %+v", ig.Name, np)
return np, nil
}
}
glog.Infof("Adding port %v to instance group %v with %d ports", port, ig.Name, len(ig.NamedPorts))
namedPort := compute.NamedPort{Name: fmt.Sprintf("port%v", port), Port: port}
ig.NamedPorts = append(ig.NamedPorts, &namedPort)
// setNamedPorts is a zonal endpoint, meaning we invoke it by re-creating a URL like:
// {project}/zones/{zone}/instanceGroups/{instanceGroup}/setNamedPorts, so the "zone"
// parameter given to SetNamedPorts must not be the entire zone URL.
zoneURLParts := strings.Split(ig.Zone, "/")
zone := zoneURLParts[len(zoneURLParts)-1]
op, err := gce.service.InstanceGroups.SetNamedPorts(
gce.projectID, zone, ig.Name,
&compute.InstanceGroupsSetNamedPortsRequest{
NamedPorts: ig.NamedPorts}).Do()
if err != nil {
return nil, err
}
if err = gce.waitForZoneOp(op, zone); err != nil {
return nil, err
}
return &namedPort, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2136-L2138 | go | train | // GetInstanceGroup returns an instance group by name. | func (gce *Cloud) GetInstanceGroup(name string, zone string) (*compute.InstanceGroup, error) | // GetInstanceGroup returns an instance group by name.
func (gce *Cloud) GetInstanceGroup(name string, zone string) (*compute.InstanceGroup, error) | {
return gce.service.InstanceGroups.Get(gce.projectID, zone, name).Do()
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2152-L2154 | go | train | // CurrentNodeName is an implementation of Instances.CurrentNodeName | func (gce *Cloud) CurrentNodeName(hostname string) (types.NodeName, error) | // CurrentNodeName is an implementation of Instances.CurrentNodeName
func (gce *Cloud) CurrentNodeName(hostname string) (types.NodeName, error) | {
return types.NodeName(hostname), nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2157-L2200 | go | train | // AddSSHKeyToAllInstances adds SSH key to all instances | func (gce *Cloud) AddSSHKeyToAllInstances(user string, keyData []byte) error | // AddSSHKeyToAllInstances adds SSH key to all instances
func (gce *Cloud) AddSSHKeyToAllInstances(user string, keyData []byte) error | {
return wait.Poll(2*time.Second, 30*time.Second, func() (bool, error) {
project, err := gce.service.Projects.Get(gce.projectID).Do()
if err != nil {
glog.Errorf("Could not get project: %v", err)
return false, nil
}
keyString := fmt.Sprintf("%s:%s %s@%s", user, strings.TrimSpace(string(keyData)), user, user)
found := false
for _, item := range project.CommonInstanceMetadata.Items {
if item.Key == "sshKeys" {
if strings.Contains(*item.Value, keyString) {
// We've already added the key
glog.Info("SSHKey already in project metadata")
return true, nil
}
value := *item.Value + "\n" + keyString
item.Value = &value
found = true
break
}
}
if !found {
// This is super unlikely, so log.
glog.Infof("Failed to find sshKeys metadata, creating a new item")
project.CommonInstanceMetadata.Items = append(project.CommonInstanceMetadata.Items,
&compute.MetadataItems{
Key: "sshKeys",
Value: &keyString,
})
}
op, err := gce.service.Projects.SetCommonInstanceMetadata(gce.projectID, project.CommonInstanceMetadata).Do()
if err != nil {
glog.Errorf("Could not Set Metadata: %v", err)
return false, nil
}
if err := gce.waitForGlobalOp(op); err != nil {
glog.Errorf("Could not Set Metadata: %v", err)
return false, nil
}
glog.Infof("Successfully added sshKey to project metadata")
return true, nil
})
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2203-L2216 | go | train | // NodeAddresses is an implementation of Instances.NodeAddresses. | func (gce *Cloud) NodeAddresses(_ types.NodeName) ([]v1.NodeAddress, error) | // NodeAddresses is an implementation of Instances.NodeAddresses.
func (gce *Cloud) NodeAddresses(_ types.NodeName) ([]v1.NodeAddress, error) | {
internalIP, err := metadata.Get("instance/network-interfaces/0/ip")
if err != nil {
return nil, fmt.Errorf("couldn't get internal IP: %v", err)
}
externalIP, err := metadata.Get("instance/network-interfaces/0/access-configs/0/external-ip")
if err != nil {
return nil, fmt.Errorf("couldn't get external IP: %v", err)
}
return []v1.NodeAddress{
{Type: v1.NodeInternalIP, Address: internalIP},
{Type: v1.NodeExternalIP, Address: externalIP},
}, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2219-L2228 | go | train | // isCurrentInstance uses metadata server to check if specified instanceID matches current machine's instanceID | func (gce *Cloud) isCurrentInstance(instanceID string) bool | // isCurrentInstance uses metadata server to check if specified instanceID matches current machine's instanceID
func (gce *Cloud) isCurrentInstance(instanceID string) bool | {
currentInstanceID, err := getInstanceIDViaMetadata()
if err != nil {
// Log and swallow error
glog.Errorf("Failed to fetch instanceID via Metadata: %v", err)
return false
}
return currentInstanceID == canonicalizeInstanceName(instanceID)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2237-L2255 | go | train | // ExternalID returns the cloud provider ID of the node with the specified NodeName (deprecated). | func (gce *Cloud) ExternalID(nodeName types.NodeName) (string, error) | // ExternalID returns the cloud provider ID of the node with the specified NodeName (deprecated).
func (gce *Cloud) ExternalID(nodeName types.NodeName) (string, error) | {
instanceName := mapNodeNameToInstanceName(nodeName)
if gce.useMetadataServer {
// Use metadata, if possible, to fetch ID. See issue #12000
if gce.isCurrentInstance(instanceName) {
externalInstanceID, err := getCurrentExternalIDViaMetadata()
if err == nil {
return externalInstanceID, nil
}
}
}
// Fallback to GCE API call if metadata server fails to retrieve ID
inst, err := gce.getInstanceByName(instanceName)
if err != nil {
return "", err
}
return strconv.FormatUint(inst.ID, 10), nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2277-L2293 | go | train | // InstanceType returns the type of the specified node with the specified NodeName. | func (gce *Cloud) InstanceType(nodeName types.NodeName) (string, error) | // InstanceType returns the type of the specified node with the specified NodeName.
func (gce *Cloud) InstanceType(nodeName types.NodeName) (string, error) | {
instanceName := mapNodeNameToInstanceName(nodeName)
if gce.useMetadataServer {
// Use metadata, if possible, to fetch ID. See issue #12000
if gce.isCurrentInstance(instanceName) {
mType, err := getCurrentMachineTypeViaMetadata()
if err == nil {
return mType, nil
}
}
}
instance, err := gce.getInstanceByName(instanceName)
if err != nil {
return "", err
}
return instance.Type, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2296-L2335 | go | train | // GetAllZones returns all the zones in which nodes are running | func (gce *Cloud) GetAllZones() (sets.String, error) | // GetAllZones returns all the zones in which nodes are running
func (gce *Cloud) GetAllZones() (sets.String, error) | {
// Fast-path for non-multizone
if len(gce.managedZones) == 1 {
return sets.NewString(gce.managedZones...), nil
}
// TODO: Caching, but this is currently only called when we are creating a volume,
// which is a relatively infrequent operation, and this is only # zones API calls
zones := sets.NewString()
// TODO: Parallelize, although O(zones) so not too bad (N <= 3 typically)
for _, zone := range gce.managedZones {
// We only retrieve one page in each zone - we only care about existence
listCall := gce.service.Instances.List(gce.projectID, zone)
// No filter: We assume that a zone is either used or unused
// We could only consider running nodes (like we do in List above),
// but probably if instances are starting we still want to consider them.
// I think we should wait until we have a reason to make the
// call one way or the other; we generally can't guarantee correct
// volume spreading if the set of zones is changing
// (and volume spreading is currently only a heuristic).
// Long term we want to replace GetAllZones (which primarily supports volume
// spreading) with a scheduler policy that is able to see the global state of
// volumes and the health of zones.
// Just a minimal set of fields - we only care about existence
listCall = listCall.Fields("items(name)")
res, err := listCall.Do()
if err != nil {
return nil, err
}
if len(res.Items) != 0 {
zones.Insert(zone)
}
}
return zones, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2345-L2386 | go | train | // ListRoutes lists routes | func (gce *Cloud) ListRoutes(clusterName string) ([]*cloudprovider.Route, error) | // ListRoutes lists routes
func (gce *Cloud) ListRoutes(clusterName string) ([]*cloudprovider.Route, error) | {
var routes []*cloudprovider.Route
pageToken := ""
page := 0
for ; page == 0 || (pageToken != "" && page < maxPages); page++ {
listCall := gce.service.Routes.List(gce.projectID)
prefix := truncateClusterName(clusterName)
listCall = listCall.Filter("name eq " + prefix + "-.*")
if pageToken != "" {
listCall = listCall.PageToken(pageToken)
}
res, err := listCall.Do()
if err != nil {
glog.Errorf("Error getting routes from GCE: %v", err)
return nil, err
}
pageToken = res.NextPageToken
for _, r := range res.Items {
if r.Network != gce.networkURL {
continue
}
// Not managed if route description != "k8s-node-route"
if r.Description != k8sNodeRouteTag {
continue
}
// Not managed if route name doesn't start with <clusterName>
if !strings.HasPrefix(r.Name, prefix) {
continue
}
target := path.Base(r.NextHopInstance)
// TODO: Should we lastComponent(target) this?
targetNodeName := types.NodeName(target) // NodeName == Instance Name on GCE
routes = append(routes, &cloudprovider.Route{Name: r.Name, TargetNode: targetNodeName, DestinationCIDR: r.DestRange})
}
}
if page >= maxPages {
glog.Errorf("ListRoutes exceeded maxPages=%d for Routes.List; truncating.", maxPages)
}
return routes, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2393-L2417 | go | train | // CreateRoute creates a route | func (gce *Cloud) CreateRoute(clusterName string, nameHint string, route *cloudprovider.Route) error | // CreateRoute creates a route
func (gce *Cloud) CreateRoute(clusterName string, nameHint string, route *cloudprovider.Route) error | {
routeName := truncateClusterName(clusterName) + "-" + nameHint
instanceName := mapNodeNameToInstanceName(route.TargetNode)
targetInstance, err := gce.getInstanceByName(instanceName)
if err != nil {
return err
}
insertOp, err := gce.service.Routes.Insert(gce.projectID, &compute.Route{
Name: routeName,
DestRange: route.DestinationCIDR,
NextHopInstance: fmt.Sprintf("zones/%s/instances/%s", targetInstance.Zone, targetInstance.Name),
Network: gce.networkURL,
Priority: 1000,
Description: k8sNodeRouteTag,
}).Do()
if err != nil {
if isHTTPErrorCode(err, http.StatusConflict) {
glog.Infof("Route %v already exists.", routeName)
return nil
}
return err
}
return gce.waitForGlobalOp(insertOp)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2420-L2426 | go | train | // DeleteRoute deletes a route | func (gce *Cloud) DeleteRoute(clusterName string, route *cloudprovider.Route) error | // DeleteRoute deletes a route
func (gce *Cloud) DeleteRoute(clusterName string, route *cloudprovider.Route) error | {
deleteOp, err := gce.service.Routes.Delete(gce.projectID, route.Name).Do()
if err != nil {
return err
}
return gce.waitForGlobalOp(deleteOp)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2429-L2434 | go | train | // GetZone gets a zone | func (gce *Cloud) GetZone() (cloudprovider.Zone, error) | // GetZone gets a zone
func (gce *Cloud) GetZone() (cloudprovider.Zone, error) | {
return cloudprovider.Zone{
FailureDomain: gce.localZone,
Region: gce.region,
}, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2518-L2528 | go | train | // DeleteDisk deletes a disk | func (gce *Cloud) DeleteDisk(diskToDelete string) error | // DeleteDisk deletes a disk
func (gce *Cloud) DeleteDisk(diskToDelete string) error | {
err := gce.doDeleteDisk(diskToDelete)
if isGCEError(err, "resourceInUseByAnotherResource") {
return volume.NewDeletedVolumeInUseError(err.Error())
}
if err == cloudprovider.ErrDiskNotFound {
return nil
}
return err
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2551-L2591 | go | train | // GetAutoLabelsForPD builds the labels that should be automatically added to a PersistentVolume backed by a GCE PD
// Specifically, this builds FailureDomain (zone) and Region labels.
// The PersistentVolumeLabel admission controller calls this and adds the labels when a PV is created.
// If zone is specified, the volume will only be found in the specified zone,
// otherwise all managed zones will be searched. | func (gce *Cloud) GetAutoLabelsForPD(name string, zone string) (map[string]string, error) | // GetAutoLabelsForPD builds the labels that should be automatically added to a PersistentVolume backed by a GCE PD
// Specifically, this builds FailureDomain (zone) and Region labels.
// The PersistentVolumeLabel admission controller calls this and adds the labels when a PV is created.
// If zone is specified, the volume will only be found in the specified zone,
// otherwise all managed zones will be searched.
func (gce *Cloud) GetAutoLabelsForPD(name string, zone string) (map[string]string, error) | {
var disk *gceDisk
var err error
if zone == "" {
// We would like as far as possible to avoid this case,
// because GCE doesn't guarantee that volumes are uniquely named per region,
// just per zone. However, creation of GCE PDs was originally done only
// by name, so we have to continue to support that.
// However, wherever possible the zone should be passed (and it is passed
// for most cases that we can control, e.g. dynamic volume provisioning)
disk, err = gce.getDiskByNameUnknownZone(name)
if err != nil {
return nil, err
}
zone = disk.Zone
} else {
// We could assume the disks exists; we have all the information we need
// However it is more consistent to ensure the disk exists,
// and in future we may gather addition information (e.g. disk type, IOPS etc)
disk, err = gce.getDiskByName(name, zone)
if err != nil {
return nil, err
}
}
region, err := GetGCERegion(zone)
if err != nil {
return nil, err
}
if zone == "" || region == "" {
// Unexpected, but sanity-check
return nil, fmt.Errorf("PD did not have zone/region information: %q", disk.Name)
}
labels := make(map[string]string)
labels[apis.LabelZoneFailureDomain] = zone
labels[apis.LabelZoneRegion] = region
return labels, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2594-L2616 | go | train | // AttachDisk attaches a disk | func (gce *Cloud) AttachDisk(diskName string, nodeName types.NodeName, readOnly bool) error | // AttachDisk attaches a disk
func (gce *Cloud) AttachDisk(diskName string, nodeName types.NodeName, readOnly bool) error | {
instanceName := mapNodeNameToInstanceName(nodeName)
instance, err := gce.getInstanceByName(instanceName)
if err != nil {
return fmt.Errorf("error getting instance %q", instanceName)
}
disk, err := gce.getDiskByName(diskName, instance.Zone)
if err != nil {
return err
}
readWrite := "READ_WRITE"
if readOnly {
readWrite = "READ_ONLY"
}
attachedDisk := gce.convertDiskToAttachedDisk(disk, readWrite)
attachOp, err := gce.service.Instances.AttachDisk(gce.projectID, disk.Zone, instance.Name, attachedDisk).Do()
if err != nil {
return err
}
return gce.waitForZoneOp(attachOp, disk.Zone)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2619-L2641 | go | train | // DetachDisk detaches a disk | func (gce *Cloud) DetachDisk(devicePath string, nodeName types.NodeName) error | // DetachDisk detaches a disk
func (gce *Cloud) DetachDisk(devicePath string, nodeName types.NodeName) error | {
instanceName := mapNodeNameToInstanceName(nodeName)
inst, err := gce.getInstanceByName(instanceName)
if err != nil {
if err == cloudprovider.ErrInstanceNotFound {
// If instance no longer exists, safe to assume volume is not attached.
glog.Warningf(
"Instance %q does not exist. DetachDisk will assume PD %q is not attached to it.",
instanceName,
devicePath)
return nil
}
return fmt.Errorf("error getting instance %q", instanceName)
}
detachOp, err := gce.service.Instances.DetachDisk(gce.projectID, inst.Zone, inst.Name, devicePath).Do()
if err != nil {
return err
}
return gce.waitForZoneOp(detachOp, inst.Zone)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2644-L2668 | go | train | // DiskIsAttached checks if disk is attached | func (gce *Cloud) DiskIsAttached(diskName string, nodeName types.NodeName) (bool, error) | // DiskIsAttached checks if disk is attached
func (gce *Cloud) DiskIsAttached(diskName string, nodeName types.NodeName) (bool, error) | {
instanceName := mapNodeNameToInstanceName(nodeName)
instance, err := gce.getInstanceByName(instanceName)
if err != nil {
if err == cloudprovider.ErrInstanceNotFound {
// If instance no longer exists, safe to assume volume is not attached.
glog.Warningf(
"Instance %q does not exist. DiskIsAttached will assume PD %q is not attached to it.",
instanceName,
diskName)
return false, nil
}
return false, err
}
for _, disk := range instance.Disks {
if disk.DeviceName == diskName {
// Disk is still attached to node
return true, nil
}
}
return false, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2705-L2719 | go | train | // Returns a gceDisk for the disk, if it is found in the specified zone.
// If not found, returns (nil, nil) | func (gce *Cloud) findDiskByName(diskName string, zone string) (*gceDisk, error) | // Returns a gceDisk for the disk, if it is found in the specified zone.
// If not found, returns (nil, nil)
func (gce *Cloud) findDiskByName(diskName string, zone string) (*gceDisk, error) | {
disk, err := gce.service.Disks.Get(gce.projectID, zone, diskName).Do()
if err == nil {
d := &gceDisk{
Zone: lastComponent(disk.Zone),
Name: disk.Name,
Kind: disk.Kind,
}
return d, nil
}
if !isHTTPErrorCode(err, http.StatusNotFound) {
return nil, err
}
return nil, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2722-L2728 | go | train | // Like findDiskByName, but returns an error if the disk is not found | func (gce *Cloud) getDiskByName(diskName string, zone string) (*gceDisk, error) | // Like findDiskByName, but returns an error if the disk is not found
func (gce *Cloud) getDiskByName(diskName string, zone string) (*gceDisk, error) | {
disk, err := gce.findDiskByName(diskName, zone)
if disk == nil && err == nil {
return nil, fmt.Errorf("GCE persistent disk not found: diskName=%q zone=%q", diskName, zone)
}
return disk, err
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2733-L2765 | go | train | // Scans all managed zones to return the GCE PD
// Prefer getDiskByName, if the zone can be established
// Return cloudprovider.ErrDiskNotFound if the given disk cannot be found in any zone | func (gce *Cloud) getDiskByNameUnknownZone(diskName string) (*gceDisk, error) | // Scans all managed zones to return the GCE PD
// Prefer getDiskByName, if the zone can be established
// Return cloudprovider.ErrDiskNotFound if the given disk cannot be found in any zone
func (gce *Cloud) getDiskByNameUnknownZone(diskName string) (*gceDisk, error) | {
// Note: this is the gotcha right now with GCE PD support:
// disk names are not unique per-region.
// (I can create two volumes with name "myvol" in e.g. us-central1-b & us-central1-f)
// For now, this is simply undefined behaviour.
//
// In future, we will have to require users to qualify their disk
// "us-central1-a/mydisk". We could do this for them as part of
// admission control, but that might be a little weird (values changing
// on create)
var found *gceDisk
for _, zone := range gce.managedZones {
disk, err := gce.findDiskByName(diskName, zone)
if err != nil {
return nil, err
}
// findDiskByName returns (nil,nil) if the disk doesn't exist, so we can't
// assume that a disk was found unless disk is non-nil.
if disk == nil {
continue
}
if found != nil {
return nil, fmt.Errorf("GCE persistent disk name was found in multiple zones: %q", diskName)
}
found = disk
}
if found != nil {
return found, nil
}
glog.Warningf("GCE persistent disk %q not found in managed zones (%s)", diskName, strings.Join(gce.managedZones, ","))
return nil, cloudprovider.ErrDiskNotFound
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2780-L2788 | go | train | // Converts a Disk resource to an AttachedDisk resource. | func (gce *Cloud) convertDiskToAttachedDisk(disk *gceDisk, readWrite string) *compute.AttachedDisk | // Converts a Disk resource to an AttachedDisk resource.
func (gce *Cloud) convertDiskToAttachedDisk(disk *gceDisk, readWrite string) *compute.AttachedDisk | {
return &compute.AttachedDisk{
DeviceName: disk.Name,
Kind: disk.Kind,
Mode: readWrite,
Source: "https://" + path.Join("www.googleapis.com/compute/v1/projects/", gce.projectID, "zones", disk.Zone, "disks", disk.Name),
Type: "PERSISTENT",
}
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2797-L2853 | go | train | // CreateDiskFromSnapshot create a disk from snapshot | func (gce *Cloud) CreateDiskFromSnapshot(snapshot string,
name string, diskType string, zone string, sizeGb int64, tags map[string]string) error | // CreateDiskFromSnapshot create a disk from snapshot
func (gce *Cloud) CreateDiskFromSnapshot(snapshot string,
name string, diskType string, zone string, sizeGb int64, tags map[string]string) error | {
// Do not allow creation of PDs in zones that are not managed. Such PDs
// then cannot be deleted by DeleteDisk.
isManaged := false
for _, managedZone := range gce.managedZones {
if zone == managedZone {
isManaged = true
break
}
}
if !isManaged {
return fmt.Errorf("kubernetes does not manage zone %q", zone)
}
tagsStr, err := gce.encodeDiskTags(tags)
if err != nil {
return fmt.Errorf("encode disk tag error %v", err)
}
switch diskType {
case DiskTypeSSD, DiskTypeStandard:
// noop
case "":
diskType = diskTypeDefault
default:
return fmt.Errorf("invalid GCE disk type %q", diskType)
}
diskTypeURI := fmt.Sprintf(diskTypeURITemplate, gce.projectID, zone, diskType)
snapshotName := "global/snapshots/" + snapshot
diskToCreate := &compute.Disk{
Name: name,
SizeGb: sizeGb,
Description: tagsStr,
Type: diskTypeURI,
SourceSnapshot: snapshotName,
}
glog.Infof("Create disk from snapshot diskToCreate %+v", diskToCreate)
createOp, err := gce.service.Disks.Insert(gce.projectID, zone, diskToCreate).Do()
glog.Infof("Create disk from snapshot operation %v, err %v", createOp, err)
if err != nil {
if isGCEError(err, "alreadyExists") {
glog.Warningf("GCE PD %q already exists, reusing", name)
return nil
}
return err
}
err = gce.waitForZoneOp(createOp, zone)
if isGCEError(err, "alreadyExists") {
glog.Warningf("GCE PD %q already exists, reusing", name)
return nil
}
return err
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2856-L2869 | go | train | // DescribeSnapshot checks the status of a snapshot | func (gce *Cloud) DescribeSnapshot(snapshotToGet string) (status string, isCompleted bool, err error) | // DescribeSnapshot checks the status of a snapshot
func (gce *Cloud) DescribeSnapshot(snapshotToGet string) (status string, isCompleted bool, err error) | {
snapshot, err := gce.getSnapshotByName(snapshotToGet)
if err != nil {
return "", false, err
}
//no snapshot is found
if snapshot == nil {
return "", false, fmt.Errorf("snapshot %s is not found", snapshotToGet)
}
if snapshot.Status == "READY" {
return snapshot.Status, true, nil
}
return snapshot.Status, false, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2872-L2875 | go | train | // FindSnapshot returns the found snapshots | func (gce *Cloud) FindSnapshot(tags map[string]string) ([]string, []string, error) | // FindSnapshot returns the found snapshots
func (gce *Cloud) FindSnapshot(tags map[string]string) ([]string, []string, error) | {
var snapshotIDs, statuses []string
return snapshotIDs, statuses, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2878-L2894 | go | train | // DeleteSnapshot deletes a snapshot | func (gce *Cloud) DeleteSnapshot(snapshotToDelete string) error | // DeleteSnapshot deletes a snapshot
func (gce *Cloud) DeleteSnapshot(snapshotToDelete string) error | {
snapshot, err := gce.getSnapshotByName(snapshotToDelete)
if err != nil {
return err
}
//no snapshot is found
if snapshot == nil {
return nil
}
deleteOp, err := gce.service.Snapshots.Delete(gce.projectID, snapshotToDelete).Do()
if err != nil {
return err
}
return gce.waitForGlobalOp(deleteOp)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2913-L2938 | go | train | // CreateSnapshot creates a snapshot | func (gce *Cloud) CreateSnapshot(diskName string, zone string, snapshotName string, tags map[string]string) error | // CreateSnapshot creates a snapshot
func (gce *Cloud) CreateSnapshot(diskName string, zone string, snapshotName string, tags map[string]string) error | {
isManaged := false
for _, managedZone := range gce.managedZones {
if zone == managedZone {
isManaged = true
break
}
}
if !isManaged {
return fmt.Errorf("kubernetes does not manage zone %q", zone)
}
tagsStr, err := gce.encodeDiskTags(tags)
if err != nil {
glog.Infof("CreateSnapshot err %v", err)
return err
}
snapshotToCreate := &compute.Snapshot{
Name: snapshotName,
Description: tagsStr,
}
glog.V(4).Infof("Create snapshot project %s, zone %s, diskName %s, snapshotToCreate %+v", gce.projectID, zone, diskName, snapshotToCreate)
createOp, err := gce.service.Disks.CreateSnapshot(gce.projectID, zone, diskName, snapshotToCreate).Do()
glog.V(4).Infof("Create snapshot operation %v", createOp)
return err
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2954-L2967 | go | train | // ListClusters lists clusters | func (gce *Cloud) ListClusters() ([]string, error) | // ListClusters lists clusters
func (gce *Cloud) ListClusters() ([]string, error) | {
allClusters := []string{}
for _, zone := range gce.managedZones {
clusters, err := gce.listClustersInZone(zone)
if err != nil {
return nil, err
}
// TODO: Scoping? Do we need to qualify the cluster name?
allClusters = append(allClusters, clusters...)
}
return allClusters, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L2989-L3063 | go | train | // Gets the named instances, returning cloudprovider.ErrInstanceNotFound if any instance is not found | func (gce *Cloud) getInstancesByNames(names []string) ([]*gceInstance, error) | // Gets the named instances, returning cloudprovider.ErrInstanceNotFound if any instance is not found
func (gce *Cloud) getInstancesByNames(names []string) ([]*gceInstance, error) | {
instances := make(map[string]*gceInstance)
remaining := len(names)
nodeInstancePrefix := gce.nodeInstancePrefix
for _, name := range names {
name = canonicalizeInstanceName(name)
if !strings.HasPrefix(name, gce.nodeInstancePrefix) {
glog.Warningf("instance '%s' does not conform to prefix '%s', removing filter", name, gce.nodeInstancePrefix)
nodeInstancePrefix = ""
}
instances[name] = nil
}
for _, zone := range gce.managedZones {
if remaining == 0 {
break
}
pageToken := ""
page := 0
for ; page == 0 || (pageToken != "" && page < maxPages); page++ {
listCall := gce.service.Instances.List(gce.projectID, zone)
if nodeInstancePrefix != "" {
// Add the filter for hosts
listCall = listCall.Filter("name eq " + nodeInstancePrefix + ".*")
}
// TODO(zmerlynn): Internal bug 29524655
// listCall = listCall.Fields("items(name,id,disks,machineType)")
if pageToken != "" {
listCall.PageToken(pageToken)
}
res, err := listCall.Do()
if err != nil {
return nil, err
}
pageToken = res.NextPageToken
for _, i := range res.Items {
name := i.Name
if _, ok := instances[name]; !ok {
continue
}
instance := &gceInstance{
Zone: zone,
Name: name,
ID: i.Id,
Disks: i.Disks,
Type: lastComponent(i.MachineType),
}
instances[name] = instance
remaining--
}
}
if page >= maxPages {
glog.Errorf("getInstancesByNames exceeded maxPages=%d for Instances.List: truncating.", maxPages)
}
}
instanceArray := make([]*gceInstance, len(names))
for i, name := range names {
name = canonicalizeInstanceName(name)
instance := instances[name]
if instance == nil {
glog.Errorf("Failed to retrieve instance: %q", name)
return nil, cloudprovider.ErrInstanceNotFound
}
instanceArray[i] = instances[name]
}
return instanceArray, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/gce/gce.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/gce/gce.go#L3066-L3088 | go | train | // Gets the named instance, returning cloudprovider.ErrInstanceNotFound if the instance is not found | func (gce *Cloud) getInstanceByName(name string) (*gceInstance, error) | // Gets the named instance, returning cloudprovider.ErrInstanceNotFound if the instance is not found
func (gce *Cloud) getInstanceByName(name string) (*gceInstance, error) | {
// Avoid changing behaviour when not managing multiple zones
for _, zone := range gce.managedZones {
name = canonicalizeInstanceName(name)
res, err := gce.service.Instances.Get(gce.projectID, zone, name).Do()
if err != nil {
glog.Errorf("getInstanceByName: failed to get instance %s; err: %v", name, err)
if isHTTPErrorCode(err, http.StatusNotFound) {
continue
}
return nil, err
}
return &gceInstance{
Zone: lastComponent(res.Zone),
Name: res.Name,
ID: res.Id,
Disks: res.Disks,
Type: lastComponent(res.MachineType),
}, nil
}
return nil, cloudprovider.ErrInstanceNotFound
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | repo-infra/kazel/kazel.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/repo-infra/kazel/kazel.go#L289-L307 | go | train | // RuleKind converts a value of the RuleType* enum into the BUILD string. | func (rt ruleType) RuleKind() string | // RuleKind converts a value of the RuleType* enum into the BUILD string.
func (rt ruleType) RuleKind() string | {
switch rt {
case RuleTypeGoBinary:
return "go_binary"
case RuleTypeGoLibrary:
return "go_library"
case RuleTypeGoTest:
return "go_test"
case RuleTypeGoXTest:
return "go_test"
case RuleTypeCGoGenrule:
return "cgo_genrule"
case RuleTypeFileGroup:
return "filegroup"
case RuleTypeOpenAPILibrary:
return "openapi_library"
}
panic("unreachable")
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | repo-infra/kazel/kazel.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/repo-infra/kazel/kazel.go#L510-L512 | go | train | // Set sets the named attribute to the provided bazel expression. | func (a Attrs) Set(name string, expr bzl.Expr) | // Set sets the named attribute to the provided bazel expression.
func (a Attrs) Set(name string, expr bzl.Expr) | {
a[name] = expr
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | repo-infra/kazel/kazel.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/repo-infra/kazel/kazel.go#L515-L520 | go | train | // SetList sets the named attribute to the provided bazel expression list. | func (a Attrs) SetList(name string, expr *bzl.ListExpr) | // SetList sets the named attribute to the provided bazel expression list.
func (a Attrs) SetList(name string, expr *bzl.ListExpr) | {
if len(expr.List) == 0 {
return
}
a[name] = expr
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | repo-infra/kazel/kazel.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/repo-infra/kazel/kazel.go#L616-L626 | go | train | // findBuildFile determines the name of a preexisting BUILD file, returning
// a default if no such file exists. | func findBuildFile(pkgPath string) (bool, string) | // findBuildFile determines the name of a preexisting BUILD file, returning
// a default if no such file exists.
func findBuildFile(pkgPath string) (bool, string) | {
options := []string{"BUILD.bazel", "BUILD"}
for _, b := range options {
path := filepath.Join(pkgPath, b)
info, err := os.Stat(path)
if err == nil && !info.IsDir() {
return true, path
}
}
return false, filepath.Join(pkgPath, "BUILD")
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | repo-infra/kazel/kazel.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/repo-infra/kazel/kazel.go#L630-L688 | go | train | // ReconcileRules reconciles, simplifies, and writes the rules for the specified package, adding
// additional dependency rules as needed. | func ReconcileRules(pkgPath string, rules []*bzl.Rule, managedAttrs []string, dryRun bool) (bool, error) | // ReconcileRules reconciles, simplifies, and writes the rules for the specified package, adding
// additional dependency rules as needed.
func ReconcileRules(pkgPath string, rules []*bzl.Rule, managedAttrs []string, dryRun bool) (bool, error) | {
_, path := findBuildFile(pkgPath)
info, err := os.Stat(path)
if err != nil && os.IsNotExist(err) {
f := &bzl.File{}
writeHeaders(f)
reconcileLoad(f, rules)
writeRules(f, rules)
return writeFile(path, f, false, dryRun)
} else if err != nil {
return false, err
}
if info.IsDir() {
return false, fmt.Errorf("%q cannot be a directory", path)
}
b, err := ioutil.ReadFile(path)
if err != nil {
return false, err
}
f, err := bzl.Parse(path, b)
if err != nil {
return false, err
}
oldRules := make(map[string]*bzl.Rule)
for _, r := range f.Rules("") {
oldRules[r.Name()] = r
}
for _, r := range rules {
o, ok := oldRules[r.Name()]
if !ok {
f.Stmt = append(f.Stmt, r.Call)
continue
}
if !RuleIsManaged(o) {
continue
}
reconcileAttr := func(o, n *bzl.Rule, name string) {
if e := n.Attr(name); e != nil {
o.SetAttr(name, e)
} else {
o.DelAttr(name)
}
}
for _, attr := range managedAttrs {
reconcileAttr(o, r, attr)
}
delete(oldRules, r.Name())
}
for _, r := range oldRules {
if !RuleIsManaged(r) {
continue
}
f.DelRules(r.Kind(), r.Name())
}
reconcileLoad(f, f.Rules(""))
return writeFile(path, f, true, dryRun)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | repo-infra/kazel/kazel.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/repo-infra/kazel/kazel.go#L729-L738 | go | train | // RuleIsManaged returns whether the provided rule is managed by this tool,
// based on the tags set on the rule. | func RuleIsManaged(r *bzl.Rule) bool | // RuleIsManaged returns whether the provided rule is managed by this tool,
// based on the tags set on the rule.
func RuleIsManaged(r *bzl.Rule) bool | {
var automanaged bool
for _, tag := range r.AttrStrings("tags") {
if tag == automanagedTag {
automanaged = true
break
}
}
return automanaged
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/aws/tags.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/tags.go#L88-L99 | go | train | // Extracts a clusterID from the given tags, if one is present
// If no clusterID is found, returns "", nil
// If multiple (different) clusterIDs are found, returns an error | func (t *awsTagging) initFromTags(tags []*ec2.Tag) error | // Extracts a clusterID from the given tags, if one is present
// If no clusterID is found, returns "", nil
// If multiple (different) clusterIDs are found, returns an error
func (t *awsTagging) initFromTags(tags []*ec2.Tag) error | {
legacyClusterID, newClusterID, err := findClusterIDs(tags)
if err != nil {
return err
}
if legacyClusterID == "" && newClusterID == "" {
glog.Errorf("Tag %q nor %q not found; Kubernetes may behave unexpectedly.", TagNameKubernetesClusterLegacy, TagNameKubernetesClusterPrefix+"...")
}
return t.init(legacyClusterID, newClusterID)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/plugins.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/plugins.go#L65-L73 | go | train | // CloudProviders returns the name of all registered cloud providers in a
// string slice | func CloudProviders() []string | // CloudProviders returns the name of all registered cloud providers in a
// string slice
func CloudProviders() []string | {
names := []string{}
providersMutex.Lock()
defer providersMutex.Unlock()
for name := range providers {
names = append(names, name)
}
return names
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/plugins.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/plugins.go#L96-L134 | go | train | // InitCloudProvider creates an instance of the named cloud provider. | func InitCloudProvider(name string, configFilePath string) (Interface, error) | // InitCloudProvider creates an instance of the named cloud provider.
func InitCloudProvider(name string, configFilePath string) (Interface, error) | {
var cloud Interface
var err error
if name == "" {
glog.Info("No cloud provider specified.")
return nil, nil
}
if IsExternal(name) {
glog.Info("External cloud provider specified")
return nil, nil
}
if configFilePath != "" {
var config *os.File
config, err = os.Open(configFilePath)
if err != nil {
glog.Fatalf("Couldn't open cloud provider configuration %s: %#v",
configFilePath, err)
}
defer config.Close()
cloud, err = GetCloudProvider(name, config)
} else {
// Pass explicit nil so plugins can actually check for nil. See
// "Why is my nil error value not equal to nil?" in golang.org/doc/faq.
cloud, err = GetCloudProvider(name, nil)
}
if err != nil {
return nil, fmt.Errorf("could not init cloud provider %q: %v", name, err)
}
if cloud == nil {
return nil, fmt.Errorf("unknown cloud provider %q", name)
}
return cloud, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | local-volume/provisioner/pkg/util/volume_util_linux.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/volume_util_linux.go#L30-L45 | go | train | // GetBlockCapacityByte returns capacity in bytes of a block device.
// fullPath is the pathname of block device. | func (u *volumeUtil) GetBlockCapacityByte(fullPath string) (int64, error) | // GetBlockCapacityByte returns capacity in bytes of a block device.
// fullPath is the pathname of block device.
func (u *volumeUtil) GetBlockCapacityByte(fullPath string) (int64, error) | {
file, err := os.OpenFile(fullPath, os.O_RDONLY, 0)
if err != nil {
return 0, err
}
defer file.Close()
var size int64
// Get size of block device into 64 bit int.
// Ref: http://www.microhowto.info/howto/get_the_size_of_a_linux_block_special_device_in_c.html
if _, _, err := unix.Syscall(unix.SYS_IOCTL, file.Fd(), unix.BLKGETSIZE64, uintptr(unsafe.Pointer(&size))); err != 0 {
return 0, err
}
return size, err
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | local-volume/provisioner/pkg/util/volume_util_linux.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/volume_util_linux.go#L48-L56 | go | train | // IsBlock checks if the given path is a block device | func (u *volumeUtil) IsBlock(fullPath string) (bool, error) | // IsBlock checks if the given path is a block device
func (u *volumeUtil) IsBlock(fullPath string) (bool, error) | {
var st unix.Stat_t
err := unix.Stat(fullPath, &st)
if err != nil {
return false, err
}
return (st.Mode & unix.S_IFMT) == unix.S_IFBLK, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | local-volume/provisioner/pkg/common/common.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/common/common.go#L201-L235 | go | train | // CreateLocalPVSpec returns a PV spec that can be used for PV creation | func CreateLocalPVSpec(config *LocalPVConfig) *v1.PersistentVolume | // CreateLocalPVSpec returns a PV spec that can be used for PV creation
func CreateLocalPVSpec(config *LocalPVConfig) *v1.PersistentVolume | {
pv := &v1.PersistentVolume{
ObjectMeta: metav1.ObjectMeta{
Name: config.Name,
Labels: config.Labels,
Annotations: map[string]string{
AnnProvisionedBy: config.ProvisionerName,
},
},
Spec: v1.PersistentVolumeSpec{
PersistentVolumeReclaimPolicy: config.ReclaimPolicy,
Capacity: v1.ResourceList{
v1.ResourceName(v1.ResourceStorage): *resource.NewQuantity(int64(config.Capacity), resource.BinarySI),
},
PersistentVolumeSource: v1.PersistentVolumeSource{
Local: &v1.LocalVolumeSource{
Path: config.HostPath,
FSType: config.FsType,
},
},
AccessModes: []v1.PersistentVolumeAccessMode{
v1.ReadWriteOnce,
},
StorageClassName: config.StorageClass,
VolumeMode: &config.VolumeMode,
MountOptions: config.MountOptions,
},
}
if config.UseAlphaAPI {
pv.ObjectMeta.Annotations[AlphaStorageNodeAffinityAnnotation] = config.AffinityAnn
} else {
pv.Spec.NodeAffinity = config.NodeAffinity
}
return pv
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | local-volume/provisioner/pkg/common/common.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/common/common.go#L238-L245 | go | train | // GetContainerPath gets the local path (within provisioner container) of the PV | func GetContainerPath(pv *v1.PersistentVolume, config MountConfig) (string, error) | // GetContainerPath gets the local path (within provisioner container) of the PV
func GetContainerPath(pv *v1.PersistentVolume, config MountConfig) (string, error) | {
relativePath, err := filepath.Rel(config.HostDir, pv.Spec.Local.Path)
if err != nil {
return "", fmt.Errorf("Could not get relative path for pv %q: %v", pv.Name, err)
}
return filepath.Join(config.MountDir, relativePath), nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | local-volume/provisioner/pkg/common/common.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/common/common.go#L248-L255 | go | train | // GetVolumeConfigFromConfigMap gets volume configuration from given configmap. | func GetVolumeConfigFromConfigMap(client *kubernetes.Clientset, namespace, name string, provisionerConfig *ProvisionerConfiguration) error | // GetVolumeConfigFromConfigMap gets volume configuration from given configmap.
func GetVolumeConfigFromConfigMap(client *kubernetes.Clientset, namespace, name string, provisionerConfig *ProvisionerConfiguration) error | {
configMap, err := client.CoreV1().ConfigMaps(namespace).Get(name, metav1.GetOptions{})
if err != nil {
return err
}
err = ConfigMapDataToVolumeConfig(configMap.Data, provisionerConfig)
return err
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | local-volume/provisioner/pkg/common/common.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/common/common.go#L258-L279 | go | train | // VolumeConfigToConfigMapData converts volume config to configmap data. | func VolumeConfigToConfigMapData(config *ProvisionerConfiguration) (map[string]string, error) | // VolumeConfigToConfigMapData converts volume config to configmap data.
func VolumeConfigToConfigMapData(config *ProvisionerConfiguration) (map[string]string, error) | {
configMapData := make(map[string]string)
val, err := yaml.Marshal(config.StorageClassConfig)
if err != nil {
return nil, fmt.Errorf("unable to Marshal volume config: %v", err)
}
configMapData[ProvisonerStorageClassConfig] = string(val)
if len(config.NodeLabelsForPV) > 0 {
nodeLabels, nlErr := yaml.Marshal(config.NodeLabelsForPV)
if nlErr != nil {
return nil, fmt.Errorf("unable to Marshal node label: %v", nlErr)
}
configMapData[ProvisionerNodeLabelsForPV] = string(nodeLabels)
}
ver, err := yaml.Marshal(config.UseAlphaAPI)
if err != nil {
return nil, fmt.Errorf("unable to Marshal API version config: %v", err)
}
configMapData[ProvisionerUseAlphaAPI] = string(ver)
return configMapData, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | local-volume/provisioner/pkg/common/common.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/common/common.go#L282-L325 | go | train | // ConfigMapDataToVolumeConfig converts configmap data to volume config. | func ConfigMapDataToVolumeConfig(data map[string]string, provisionerConfig *ProvisionerConfiguration) error | // ConfigMapDataToVolumeConfig converts configmap data to volume config.
func ConfigMapDataToVolumeConfig(data map[string]string, provisionerConfig *ProvisionerConfiguration) error | {
rawYaml := ""
for key, val := range data {
rawYaml += key
rawYaml += ": \n"
rawYaml += insertSpaces(string(val))
}
if err := yaml.Unmarshal([]byte(rawYaml), provisionerConfig); err != nil {
return fmt.Errorf("fail to Unmarshal yaml due to: %#v", err)
}
for class, config := range provisionerConfig.StorageClassConfig {
if config.BlockCleanerCommand == nil {
// Supply a default block cleaner command.
config.BlockCleanerCommand = []string{DefaultBlockCleanerCommand}
} else {
// Validate that array is non empty.
if len(config.BlockCleanerCommand) < 1 {
return fmt.Errorf("Invalid empty block cleaner command for class %v", class)
}
}
if config.MountDir == "" || config.HostDir == "" {
return fmt.Errorf("Storage Class %v is misconfigured, missing HostDir or MountDir parameter", class)
}
if config.VolumeMode == "" {
config.VolumeMode = DefaultVolumeMode
}
volumeMode := v1.PersistentVolumeMode(config.VolumeMode)
if volumeMode != v1.PersistentVolumeBlock && volumeMode != v1.PersistentVolumeFilesystem {
return fmt.Errorf("unsupported volume mode %s", config.VolumeMode)
}
provisionerConfig.StorageClassConfig[class] = config
glog.Infof("StorageClass %q configured with MountDir %q, HostDir %q, VolumeMode %q, FsType %q, BlockCleanerCommand %q",
class,
config.MountDir,
config.HostDir,
config.VolumeMode,
config.FsType,
config.BlockCleanerCommand)
}
return nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | local-volume/provisioner/pkg/common/common.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/common/common.go#L339-L358 | go | train | // LoadProvisionerConfigs loads all configuration into a string and unmarshal it into ProvisionerConfiguration struct.
// The configuration is stored in the configmap which is mounted as a volume. | func LoadProvisionerConfigs(configPath string, provisionerConfig *ProvisionerConfiguration) error | // LoadProvisionerConfigs loads all configuration into a string and unmarshal it into ProvisionerConfiguration struct.
// The configuration is stored in the configmap which is mounted as a volume.
func LoadProvisionerConfigs(configPath string, provisionerConfig *ProvisionerConfiguration) error | {
files, err := ioutil.ReadDir(configPath)
if err != nil {
return err
}
data := make(map[string]string)
for _, file := range files {
if !file.IsDir() {
if strings.Compare(file.Name(), "..data") != 0 {
fileContents, err := ioutil.ReadFile(path.Join(configPath, file.Name()))
if err != nil {
glog.Infof("Could not read file: %s due to: %v", path.Join(configPath, file.Name()), err)
return err
}
data[file.Name()] = string(fileContents)
}
}
}
return ConfigMapDataToVolumeConfig(data, provisionerConfig)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | local-volume/provisioner/pkg/common/common.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/common/common.go#L361-L386 | go | train | // SetupClient created client using either in-cluster configuration or if KUBECONFIG environment variable is specified then using that config. | func SetupClient() *kubernetes.Clientset | // SetupClient created client using either in-cluster configuration or if KUBECONFIG environment variable is specified then using that config.
func SetupClient() *kubernetes.Clientset | {
var config *rest.Config
var err error
kubeconfigFile := os.Getenv(KubeConfigEnv)
if kubeconfigFile != "" {
config, err = BuildConfigFromFlags("", kubeconfigFile)
if err != nil {
glog.Fatalf("Error creating config from %s specified file: %s %v\n", KubeConfigEnv,
kubeconfigFile, err)
}
glog.Infof("Creating client using kubeconfig file %s", kubeconfigFile)
} else {
config, err = InClusterConfig()
if err != nil {
glog.Fatalf("Error creating InCluster config: %v\n", err)
}
glog.Infof("Creating client using in-cluster config")
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
glog.Fatalf("Error creating clientset: %v\n", err)
}
return clientset
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | local-volume/provisioner/pkg/common/common.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/common/common.go#L389-L394 | go | train | // GenerateMountName generates a volumeMount.name for pod spec, based on volume configuration. | func GenerateMountName(mount *MountConfig) string | // GenerateMountName generates a volumeMount.name for pod spec, based on volume configuration.
func GenerateMountName(mount *MountConfig) string | {
h := fnv.New32a()
h.Write([]byte(mount.HostDir))
h.Write([]byte(mount.MountDir))
return fmt.Sprintf("mount-%x", h.Sum32())
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | local-volume/provisioner/pkg/common/common.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/common/common.go#L397-L417 | go | train | // GetVolumeMode check volume mode of given path. | func GetVolumeMode(volUtil util.VolumeUtil, fullPath string) (v1.PersistentVolumeMode, error) | // GetVolumeMode check volume mode of given path.
func GetVolumeMode(volUtil util.VolumeUtil, fullPath string) (v1.PersistentVolumeMode, error) | {
isdir, errdir := volUtil.IsDir(fullPath)
if isdir {
return v1.PersistentVolumeFilesystem, nil
}
// check for Block before returning errdir
isblk, errblk := volUtil.IsBlock(fullPath)
if isblk {
return v1.PersistentVolumeBlock, nil
}
if errdir == nil && errblk == nil {
return "", fmt.Errorf("Skipping file %q: not a directory nor block device", fullPath)
}
// report the first error found
if errdir != nil {
return "", fmt.Errorf("Directory check for %q failed: %s", fullPath, errdir)
}
return "", fmt.Errorf("Block device check for %q failed: %s", fullPath, errblk)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | nfs/pkg/volume/delete.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/nfs/pkg/volume/delete.go#L31-L60 | go | train | // Delete removes the directory that was created by Provision backing the given
// PV and removes its export from the NFS server. | func (p *nfsProvisioner) Delete(volume *v1.PersistentVolume) error | // Delete removes the directory that was created by Provision backing the given
// PV and removes its export from the NFS server.
func (p *nfsProvisioner) Delete(volume *v1.PersistentVolume) error | {
// Ignore the call if this provisioner was not the one to provision the
// volume. It doesn't even attempt to delete it, so it's neither a success
// (nil error) nor failure (any other error)
provisioned, err := p.provisioned(volume)
if err != nil {
return fmt.Errorf("error determining if this provisioner was the one to provision volume %q: %v", volume.Name, err)
}
if !provisioned {
strerr := fmt.Sprintf("this provisioner id %s didn't provision volume %q and so can't delete it; id %s did & can", p.identity, volume.Name, volume.Annotations[annProvisionerID])
return &controller.IgnoredError{Reason: strerr}
}
err = p.deleteDirectory(volume)
if err != nil {
return fmt.Errorf("error deleting volume's backing path: %v", err)
}
err = p.deleteExport(volume)
if err != nil {
return fmt.Errorf("deleted the volume's backing path but error deleting export: %v", err)
}
err = p.deleteQuota(volume)
if err != nil {
return fmt.Errorf("deleted the volume's backing path & export but error deleting quota: %v", err)
}
return nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | digitalocean/pkg/volume/provision.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/digitalocean/pkg/volume/provision.go#L50-L61 | go | train | // NewDigitalOceanProvisioner creates a new DigitalOcean provisioner | func NewDigitalOceanProvisioner(ctx context.Context, client kubernetes.Interface, doClient *godo.Client) controller.Provisioner | // NewDigitalOceanProvisioner creates a new DigitalOcean provisioner
func NewDigitalOceanProvisioner(ctx context.Context, client kubernetes.Interface, doClient *godo.Client) controller.Provisioner | {
var identity types.UID
provisioner := &digitaloceanProvisioner{
client: client,
doClient: doClient,
ctx: ctx,
identity: identity,
}
return provisioner
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | digitalocean/pkg/volume/provision.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/digitalocean/pkg/volume/provision.go#L82-L124 | go | train | // Provision creates a volume i.e. the storage asset and returns a PV object for
// the volume. | func (p *digitaloceanProvisioner) Provision(options controller.VolumeOptions) (*v1.PersistentVolume, error) | // Provision creates a volume i.e. the storage asset and returns a PV object for
// the volume.
func (p *digitaloceanProvisioner) Provision(options controller.VolumeOptions) (*v1.PersistentVolume, error) | {
if !util.AccessModesContainedInAll(p.getAccessModes(), options.PVC.Spec.AccessModes) {
return nil, fmt.Errorf("Invalid Access Modes: %v, Supported Access Modes: %v", options.PVC.Spec.AccessModes, p.getAccessModes())
}
vol, err := p.createVolume(options)
if err != nil {
return nil, err
}
annotations := make(map[string]string)
annotations[annCreatedBy] = createdBy
annotations[annProvisionerID] = string(p.identity)
annotations[annVolumeID] = vol.ID
labels := make(map[string]string)
labels[apis.LabelZoneFailureDomain] = vol.Region.Slug
pv := &v1.PersistentVolume{
ObjectMeta: metav1.ObjectMeta{
Name: options.PVName,
Labels: labels,
Annotations: annotations,
},
Spec: v1.PersistentVolumeSpec{
PersistentVolumeReclaimPolicy: options.PersistentVolumeReclaimPolicy,
AccessModes: options.PVC.Spec.AccessModes,
Capacity: v1.ResourceList{
v1.ResourceName(v1.ResourceStorage): resource.MustParse(fmt.Sprintf("%dGi", vol.SizeGigaBytes)),
},
PersistentVolumeSource: v1.PersistentVolumeSource{
FlexVolume: &v1.FlexPersistentVolumeSource{
Driver: fmt.Sprintf("%s/%s", flexvolumeVendor, flexvolumeDriver),
Options: map[string]string{},
ReadOnly: false,
},
},
},
}
return pv, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | iscsi/targetd/provisioner/iscsi-provisioner.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/iscsi/targetd/provisioner/iscsi-provisioner.go#L104-L109 | go | train | // getAccessModes returns access modes iscsi volume supported. | func (p *iscsiProvisioner) getAccessModes() []v1.PersistentVolumeAccessMode | // getAccessModes returns access modes iscsi volume supported.
func (p *iscsiProvisioner) getAccessModes() []v1.PersistentVolumeAccessMode | {
return []v1.PersistentVolumeAccessMode{
v1.ReadWriteOnce,
v1.ReadOnlyMany,
}
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | iscsi/targetd/provisioner/iscsi-provisioner.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/iscsi/targetd/provisioner/iscsi-provisioner.go#L112-L165 | go | train | // Provision creates a storage asset and returns a PV object representing it. | func (p *iscsiProvisioner) Provision(options controller.VolumeOptions) (*v1.PersistentVolume, error) | // Provision creates a storage asset and returns a PV object representing it.
func (p *iscsiProvisioner) Provision(options controller.VolumeOptions) (*v1.PersistentVolume, error) | {
if !util.AccessModesContainedInAll(p.getAccessModes(), options.PVC.Spec.AccessModes) {
return nil, fmt.Errorf("invalid AccessModes %v: only AccessModes %v are supported", options.PVC.Spec.AccessModes, p.getAccessModes())
}
log.Debugln("new provision request received for pvc: ", options.PVName)
vol, lun, pool, err := p.createVolume(options)
if err != nil {
log.Warnln(err)
return nil, err
}
log.Debugln("volume created with vol and lun: ", vol, lun)
annotations := make(map[string]string)
annotations["volume_name"] = vol
annotations["pool"] = pool
annotations["initiators"] = options.Parameters["initiators"]
var portals []string
if len(options.Parameters["portals"]) > 0 {
portals = strings.Split(options.Parameters["portals"], ",")
}
pv := &v1.PersistentVolume{
ObjectMeta: metav1.ObjectMeta{
Name: options.PVName,
Labels: map[string]string{},
Annotations: annotations,
},
Spec: v1.PersistentVolumeSpec{
PersistentVolumeReclaimPolicy: options.PersistentVolumeReclaimPolicy,
AccessModes: options.PVC.Spec.AccessModes,
Capacity: v1.ResourceList{
v1.ResourceName(v1.ResourceStorage): options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)],
},
// set volumeMode from PVC Spec
VolumeMode: options.PVC.Spec.VolumeMode,
PersistentVolumeSource: v1.PersistentVolumeSource{
ISCSI: &v1.ISCSIPersistentVolumeSource{
TargetPortal: options.Parameters["targetPortal"],
Portals: portals,
IQN: options.Parameters["iqn"],
ISCSIInterface: options.Parameters["iscsiInterface"],
Lun: lun,
ReadOnly: getReadOnly(options.Parameters["readonly"]),
FSType: getFsType(options.Parameters["fsType"]),
DiscoveryCHAPAuth: getBool(options.Parameters["chapAuthDiscovery"]),
SessionCHAPAuth: getBool(options.Parameters["chapAuthSession"]),
SecretRef: getSecretRef(getBool(options.Parameters["chapAuthDiscovery"]), getBool(options.Parameters["chapAuthSession"]), &v1.SecretReference{Name: viper.GetString("provisioner-name") + "-chap-secret"}),
},
},
},
}
return pv, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | iscsi/targetd/provisioner/iscsi-provisioner.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/iscsi/targetd/provisioner/iscsi-provisioner.go#L200-L221 | go | train | // Delete removes the storage asset that was created by Provision represented
// by the given PV. | func (p *iscsiProvisioner) Delete(volume *v1.PersistentVolume) error | // Delete removes the storage asset that was created by Provision represented
// by the given PV.
func (p *iscsiProvisioner) Delete(volume *v1.PersistentVolume) error | {
//vol from the annotation
log.Debugln("volume deletion request received: ", volume.GetName())
for _, initiator := range strings.Split(volume.Annotations["initiators"], ",") {
log.Debugln("removing iscsi export: ", volume.Annotations["volume_name"], volume.Annotations["pool"], initiator)
err := p.exportDestroy(volume.Annotations["volume_name"], volume.Annotations["pool"], initiator)
if err != nil {
log.Warnln(err)
return err
}
log.Debugln("iscsi export removed: ", volume.Annotations["volume_name"], volume.Annotations["pool"], initiator)
}
log.Debugln("removing logical volume : ", volume.Annotations["volume_name"], volume.Annotations["pool"])
err := p.volDestroy(volume.Annotations["volume_name"], volume.Annotations["pool"])
if err != nil {
log.Warnln(err)
return err
}
log.Debugln("logical volume removed: ", volume.Annotations["volume_name"], volume.Annotations["pool"])
log.Debugln("volume deletion request completed: ", volume.GetName())
return nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | iscsi/targetd/provisioner/iscsi-provisioner.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/iscsi/targetd/provisioner/iscsi-provisioner.go#L312-L348 | go | train | // getFirstAvailableLun gets first available Lun. | func getFirstAvailableLun(exportList exportList) (int32, error) | // getFirstAvailableLun gets first available Lun.
func getFirstAvailableLun(exportList exportList) (int32, error) | {
sort.Sort(exportList)
log.Debug("sorted export List: ", exportList)
//this is sloppy way to remove duplicates
uniqueExport := make(map[int32]export)
for _, export := range exportList {
uniqueExport[export.Lun] = export
}
log.Debug("unique luns sorted export List: ", uniqueExport)
//this is a sloppy way to get the list of luns
luns := make([]int, len(uniqueExport), len(uniqueExport))
i := 0
for _, export := range uniqueExport {
luns[i] = int(export.Lun)
i++
}
log.Debug("lun list: ", luns)
if len(luns) >= 255 {
return -1, errors.New("255 luns allocated no more luns available")
}
var sluns sort.IntSlice
sluns = luns[0:]
sort.Sort(sluns)
log.Debug("sorted lun list: ", sluns)
lun := int32(len(sluns))
for i, clun := range sluns {
if i < int(clun) {
lun = int32(i)
break
}
}
return lun, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | iscsi/targetd/provisioner/iscsi-provisioner.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/iscsi/targetd/provisioner/iscsi-provisioner.go#L351-L364 | go | train | // volDestroy removes calls vol_destroy targetd API to remove volume. | func (p *iscsiProvisioner) volDestroy(vol string, pool string) error | // volDestroy removes calls vol_destroy targetd API to remove volume.
func (p *iscsiProvisioner) volDestroy(vol string, pool string) error | {
client, err := p.getConnection()
defer client.Close()
if err != nil {
log.Warnln(err)
return err
}
args := volDestroyArgs{
Pool: pool,
Name: vol,
}
err = client.Call("vol_destroy", args, nil)
return err
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | iscsi/targetd/provisioner/iscsi-provisioner.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/iscsi/targetd/provisioner/iscsi-provisioner.go#L367-L381 | go | train | // exportDestroy calls export_destroy targetd API to remove export of volume. | func (p *iscsiProvisioner) exportDestroy(vol string, pool string, initiator string) error | // exportDestroy calls export_destroy targetd API to remove export of volume.
func (p *iscsiProvisioner) exportDestroy(vol string, pool string, initiator string) error | {
client, err := p.getConnection()
defer client.Close()
if err != nil {
log.Warnln(err)
return err
}
args := exportDestroyArgs{
Pool: pool,
Vol: vol,
InitiatorWwn: initiator,
}
err = client.Call("export_destroy", args, nil)
return err
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | iscsi/targetd/provisioner/iscsi-provisioner.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/iscsi/targetd/provisioner/iscsi-provisioner.go#L384-L398 | go | train | // volCreate calls vol_create targetd API to create a volume. | func (p *iscsiProvisioner) volCreate(name string, size int64, pool string) error | // volCreate calls vol_create targetd API to create a volume.
func (p *iscsiProvisioner) volCreate(name string, size int64, pool string) error | {
client, err := p.getConnection()
defer client.Close()
if err != nil {
log.Warnln(err)
return err
}
args := volCreateArgs{
Pool: pool,
Name: name,
Size: size,
}
err = client.Call("vol_create", args, nil)
return err
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | iscsi/targetd/provisioner/iscsi-provisioner.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/iscsi/targetd/provisioner/iscsi-provisioner.go#L401-L416 | go | train | // exportCreate calls export_create targetd API to create an export of volume. | func (p *iscsiProvisioner) exportCreate(vol string, lun int32, pool string, initiator string) error | // exportCreate calls export_create targetd API to create an export of volume.
func (p *iscsiProvisioner) exportCreate(vol string, lun int32, pool string, initiator string) error | {
client, err := p.getConnection()
defer client.Close()
if err != nil {
log.Warnln(err)
return err
}
args := exportCreateArgs{
Pool: pool,
Vol: vol,
InitiatorWwn: initiator,
Lun: lun,
}
err = client.Call("export_create", args, nil)
return err
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | iscsi/targetd/provisioner/iscsi-provisioner.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/iscsi/targetd/provisioner/iscsi-provisioner.go#L419-L429 | go | train | // exportList lists calls export_list targetd API to get export objects. | func (p *iscsiProvisioner) exportList() (exportList, error) | // exportList lists calls export_list targetd API to get export objects.
func (p *iscsiProvisioner) exportList() (exportList, error) | {
client, err := p.getConnection()
defer client.Close()
if err != nil {
log.Warnln(err)
return nil, err
}
var result1 exportList
err = client.Call("export_list", nil, &result1)
return result1, err
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | iscsi/targetd/provisioner/iscsi-provisioner.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/iscsi/targetd/provisioner/iscsi-provisioner.go#L433-L453 | go | train | //initiator_set_auth(initiator_wwn, in_user, in_pass, out_user, out_pass) | func (p *iscsiProvisioner) setInitiatorAuth(initiator string, inUser string, inPassword string, outUser string, outPassword string) error | //initiator_set_auth(initiator_wwn, in_user, in_pass, out_user, out_pass)
func (p *iscsiProvisioner) setInitiatorAuth(initiator string, inUser string, inPassword string, outUser string, outPassword string) error | {
client, err := p.getConnection()
defer client.Close()
if err != nil {
log.Warnln(err)
return err
}
//make arguments object
args := initiatorSetAuthArgs{
InitiatorWwn: initiator,
InUser: inUser,
InPassword: inPassword,
OutUser: outUser,
OutPassword: outPassword,
}
//call remote procedure with args
err = client.Call("initiator_set_auth", args, nil)
return err
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | repo-infra/kazel/sourcerer.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/repo-infra/kazel/sourcerer.go#L40-L107 | go | train | // walkSource walks the source tree recursively from pkgPath, adding
// any BUILD files to v.newRules to be formatted.
//
// If AddSourcesRules is enabled in the kazel config, then we additionally add
// package-sources and recursive all-srcs filegroups rules to every BUILD file.
//
// Returns the list of children all-srcs targets that should be added to the
// all-srcs rule of the enclosing package. | func (v *Vendorer) walkSource(pkgPath string) ([]string, error) | // walkSource walks the source tree recursively from pkgPath, adding
// any BUILD files to v.newRules to be formatted.
//
// If AddSourcesRules is enabled in the kazel config, then we additionally add
// package-sources and recursive all-srcs filegroups rules to every BUILD file.
//
// Returns the list of children all-srcs targets that should be added to the
// all-srcs rule of the enclosing package.
func (v *Vendorer) walkSource(pkgPath string) ([]string, error) | {
// clean pkgPath since we access v.newRules directly
pkgPath = filepath.Clean(pkgPath)
for _, r := range v.skippedPaths {
if r.Match([]byte(pkgPath)) {
return nil, nil
}
}
files, err := ioutil.ReadDir(pkgPath)
if err != nil {
return nil, err
}
// Find any children packages we need to include in an all-srcs rule.
var children []string
for _, f := range files {
if f.IsDir() {
c, err := v.walkSource(filepath.Join(pkgPath, f.Name()))
if err != nil {
return nil, err
}
children = append(children, c...)
}
}
// This path is a package either if we've added rules or if a BUILD file already exists.
_, hasRules := v.newRules[pkgPath]
isPkg := hasRules
if !isPkg {
isPkg, _ = findBuildFile(pkgPath)
}
if !isPkg {
// This directory isn't a package (doesn't contain a BUILD file),
// but there might be subdirectories that are packages,
// so pass that up to our parent.
return children, nil
}
// Enforce formatting the BUILD file, even if we're not adding srcs rules
if !hasRules {
v.addRules(pkgPath, nil)
}
if !v.cfg.AddSourcesRules {
return nil, nil
}
pkgSrcsExpr := &bzl.LiteralExpr{Token: `glob(["**"])`}
if pkgPath == "." {
pkgSrcsExpr = &bzl.LiteralExpr{Token: `glob(["**"], exclude=["bazel-*/**", ".git/**"])`}
}
v.addRules(pkgPath, []*bzl.Rule{
newRule(RuleTypeFileGroup,
func(_ ruleType) string { return pkgSrcsTarget },
map[string]bzl.Expr{
"srcs": pkgSrcsExpr,
"visibility": asExpr([]string{"//visibility:private"}),
}),
newRule(RuleTypeFileGroup,
func(_ ruleType) string { return allSrcsTarget },
map[string]bzl.Expr{
"srcs": asExpr(append(children, fmt.Sprintf(":%s", pkgSrcsTarget))),
}),
})
return []string{fmt.Sprintf("//%s:%s", pkgPath, allSrcsTarget)}, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/openstack/openstack_client.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_client.go#L27-L36 | go | train | // NewNetworkV2 creates a new Network V2 endpoint | func (os *OpenStack) NewNetworkV2() (*gophercloud.ServiceClient, error) | // NewNetworkV2 creates a new Network V2 endpoint
func (os *OpenStack) NewNetworkV2() (*gophercloud.ServiceClient, error) | {
network, err := openstack.NewNetworkV2(os.provider, gophercloud.EndpointOpts{
Region: os.region,
})
if err != nil {
glog.Warningf("Failed to find network v2 endpoint: %v", err)
return nil, err
}
return network, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/openstack/openstack_client.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_client.go#L39-L48 | go | train | // NewComputeV2 creates a new Compute V2 endpoint | func (os *OpenStack) NewComputeV2() (*gophercloud.ServiceClient, error) | // NewComputeV2 creates a new Compute V2 endpoint
func (os *OpenStack) NewComputeV2() (*gophercloud.ServiceClient, error) | {
compute, err := openstack.NewComputeV2(os.provider, gophercloud.EndpointOpts{
Region: os.region,
})
if err != nil {
glog.Warningf("Failed to find compute v2 endpoint: %v", err)
return nil, err
}
return compute, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/openstack/openstack_client.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_client.go#L53-L62 | go | train | // NewBlockStorageV1 creates a new BlockStorage V1 endpoint
// TODO(xyang): This should be removed at some point after the OpenStack Queens release
// because V1 API has been deprecated for many releases and was finally removed from Cinder in Queens. | func (os *OpenStack) NewBlockStorageV1() (*gophercloud.ServiceClient, error) | // NewBlockStorageV1 creates a new BlockStorage V1 endpoint
// TODO(xyang): This should be removed at some point after the OpenStack Queens release
// because V1 API has been deprecated for many releases and was finally removed from Cinder in Queens.
func (os *OpenStack) NewBlockStorageV1() (*gophercloud.ServiceClient, error) | {
storage, err := openstack.NewBlockStorageV1(os.provider, gophercloud.EndpointOpts{
Region: os.region,
})
if err != nil {
glog.Errorf("Unable to initialize cinder v1 client for region: %s", os.region)
return nil, err
}
return storage, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/aws/log_handler.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/log_handler.go#L25-L34 | go | train | // Handler for aws-sdk-go that logs all requests | func awsHandlerLogger(req *request.Request) | // Handler for aws-sdk-go that logs all requests
func awsHandlerLogger(req *request.Request) | {
service := req.ClientInfo.ServiceName
name := "?"
if req.Operation != nil {
name = req.Operation.Name
}
glog.V(4).Infof("AWS request: %s %s", service, name)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/openstack/openstack_volumes.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_volumes.go#L135-L149 | go | train | // OperationPending checks status, makes sure we're not in error state | func (os *OpenStack) OperationPending(diskName string) (bool, string, error) | // OperationPending checks status, makes sure we're not in error state
func (os *OpenStack) OperationPending(diskName string) (bool, string, error) | {
volume, err := os.getVolume(diskName)
if err != nil {
return false, "", err
}
volumeStatus := volume.Status
if volumeStatus == VolumeErrorStatus {
glog.Errorf("status of volume %s is %s", diskName, volumeStatus)
return false, volumeStatus, nil
}
if volumeStatus == VolumeAvailableStatus || volumeStatus == VolumeInUseStatus || volumeStatus == VolumeDeletedStatus {
return false, volume.Status, nil
}
return true, volumeStatus, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/openstack/openstack_volumes.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_volumes.go#L152-L189 | go | train | // AttachDisk attaches specified cinder volume to the compute running kubelet | func (os *OpenStack) AttachDisk(instanceID, volumeID string) (string, error) | // AttachDisk attaches specified cinder volume to the compute running kubelet
func (os *OpenStack) AttachDisk(instanceID, volumeID string) (string, error) | {
volume, err := os.getVolume(volumeID)
if err != nil {
return "", err
}
if volume.Status != VolumeAvailableStatus {
errmsg := fmt.Sprintf("volume %s status is %s, not %s, can not be attached to instance %s.", volume.Name, volume.Status, VolumeAvailableStatus, instanceID)
glog.Error(errmsg)
return "", errors.New(errmsg)
}
cClient, err := os.NewComputeV2()
if err != nil {
return "", err
}
if volume.AttachedServerID != "" {
if instanceID == volume.AttachedServerID {
glog.V(4).Infof("Disk %s is already attached to instance %s", volumeID, instanceID)
return volume.ID, nil
}
glog.V(2).Infof("Disk %s is attached to a different instance (%s), detaching", volumeID, volume.AttachedServerID)
err = os.DetachDisk(volume.AttachedServerID, volumeID)
if err != nil {
return "", err
}
}
// add read only flag here if possible spothanis
_, err = volumeattach.Create(cClient, instanceID, &volumeattach.CreateOpts{
VolumeID: volume.ID,
}).Extract()
if err != nil {
glog.Errorf("Failed to attach %s volume to %s compute: %v", volumeID, instanceID, err)
return "", err
}
glog.V(2).Infof("Successfully attached %s volume to %s compute", volumeID, instanceID)
return volume.ID, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/openstack/openstack_volumes.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_volumes.go#L192-L221 | go | train | // DetachDisk detaches given cinder volume from the compute running kubelet | func (os *OpenStack) DetachDisk(instanceID, volumeID string) error | // DetachDisk detaches given cinder volume from the compute running kubelet
func (os *OpenStack) DetachDisk(instanceID, volumeID string) error | {
volume, err := os.getVolume(volumeID)
if err != nil {
return err
}
if volume.Status != VolumeInUseStatus {
errmsg := fmt.Sprintf("can not detach volume %s, its status is %s.", volume.Name, volume.Status)
glog.Error(errmsg)
return errors.New(errmsg)
}
cClient, err := os.NewComputeV2()
if err != nil {
return err
}
if volume.AttachedServerID != instanceID {
errMsg := fmt.Sprintf("Disk: %s has no attachments or is not attached to compute: %s", volume.Name, instanceID)
glog.Error(errMsg)
return errors.New(errMsg)
}
// This is a blocking call and effects kubelet's performance directly.
// We should consider kicking it out into a separate routine, if it is bad.
err = volumeattach.Delete(cClient, instanceID, volume.ID).ExtractErr()
if err != nil {
glog.Errorf("Failed to delete volume %s from compute %s attached %v", volume.ID, instanceID, err)
return err
}
glog.V(2).Infof("Successfully detached volume: %s from compute: %s", volume.ID, instanceID)
return nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/openstack/openstack_volumes.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_volumes.go#L234-L261 | go | train | // CreateVolume of given size (in GiB) | func (os *OpenStack) CreateVolume(name string, size int, vtype, availability, snapshotID string, tags *map[string]string) (string, string, error) | // CreateVolume of given size (in GiB)
func (os *OpenStack) CreateVolume(name string, size int, vtype, availability, snapshotID string, tags *map[string]string) (string, string, error) | {
volumes, err := os.volumeService("")
if err != nil || volumes == nil {
glog.Errorf("Unable to initialize cinder client for region: %s", os.region)
return "", "", err
}
opts := VolumeCreateOpts{
Name: name,
Size: size,
VolumeType: vtype,
Availability: availability,
SourceSnapshotID: snapshotID,
}
if tags != nil {
opts.Metadata = *tags
}
volumeID, volumeAZ, err := volumes.createVolume(opts)
if err != nil {
glog.Errorf("Failed to create a %d GB volume: %v", size, err)
return "", "", err
}
glog.Infof("Created volume %v in Availability Zone: %v", volumeID, volumeAZ)
return volumeID, volumeAZ, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/openstack/openstack_volumes.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_volumes.go#L264-L288 | go | train | // GetDevicePath returns the path of an attached block storage volume, specified by its id. | func (os *OpenStack) GetDevicePath(volumeID string) string | // GetDevicePath returns the path of an attached block storage volume, specified by its id.
func (os *OpenStack) GetDevicePath(volumeID string) string | {
// Build a list of candidate device paths
candidateDeviceNodes := []string{
// KVM
fmt.Sprintf("virtio-%s", volumeID[:20]),
// KVM virtio-scsi
fmt.Sprintf("scsi-0QEMU_QEMU_HARDDISK_%s", volumeID[:20]),
// ESXi
fmt.Sprintf("wwn-0x%s", strings.Replace(volumeID, "-", "", -1)),
}
files, _ := ioutil.ReadDir("/dev/disk/by-id/")
for _, f := range files {
for _, c := range candidateDeviceNodes {
if c == f.Name() {
glog.V(4).Infof("Found disk attached as %q; full devicepath: %s\n", f.Name(), path.Join("/dev/disk/by-id/", f.Name()))
return path.Join("/dev/disk/by-id/", f.Name())
}
}
}
glog.Warningf("Failed to find device for the volumeID: %q\n", volumeID)
return ""
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/openstack/openstack_volumes.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_volumes.go#L291-L313 | go | train | // DeleteVolume deletes the specified volume | func (os *OpenStack) DeleteVolume(volumeID string) error | // DeleteVolume deletes the specified volume
func (os *OpenStack) DeleteVolume(volumeID string) error | {
used, err := os.diskIsUsed(volumeID)
if err != nil {
return err
}
if used {
msg := fmt.Sprintf("Cannot delete the volume %q, it's still attached to a node", volumeID)
return k8sVolume.NewDeletedVolumeInUseError(msg)
}
volumes, err := os.volumeService("")
if err != nil || volumes == nil {
glog.Errorf("Unable to initialize cinder client for region: %s", os.region)
return err
}
err = volumes.deleteVolume(volumeID)
if err != nil {
glog.Errorf("Cannot delete volume %s: %v", volumeID, err)
}
return nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/openstack/openstack_volumes.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/openstack/openstack_volumes.go#L316-L339 | go | train | // GetAttachmentDiskPath retrieves device path of attached volume to the compute running kubelet, as known by cinder | func (os *OpenStack) GetAttachmentDiskPath(instanceID, volumeID string) (string, error) | // GetAttachmentDiskPath retrieves device path of attached volume to the compute running kubelet, as known by cinder
func (os *OpenStack) GetAttachmentDiskPath(instanceID, volumeID string) (string, error) | {
// See issue #33128 - Cinder does not always tell you the right device path, as such
// we must only use this value as a last resort.
volume, err := os.getVolume(volumeID)
if err != nil {
return "", err
}
if volume.Status != VolumeInUseStatus {
errmsg := fmt.Sprintf("can not get device path of volume %s, its status is %s.", volume.Name, volume.Status)
glog.Error(errmsg)
return "", errors.New(errmsg)
}
if volume.AttachedServerID != "" {
if instanceID == volume.AttachedServerID {
// Attachment[0]["device"] points to the device path
// see http://developer.openstack.org/api-ref-blockstorage-v1.html
return volume.AttachedDevice, nil
}
errMsg := fmt.Sprintf("Disk %q is attached to a different compute: %q, should be detached before proceeding", volumeID, volume.AttachedServerID)
glog.Error(errMsg)
return "", errors.New(errMsg)
}
return "", fmt.Errorf("volume %s has no ServerId", volumeID)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | local-volume/provisioner/pkg/metrics/collectors/proc_table_collector.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/metrics/collectors/proc_table_collector.go#L53-L57 | go | train | // Describe implements the prometheus.Collector interface. | func (collector *procTableCollector) Describe(ch chan<- *prometheus.Desc) | // Describe implements the prometheus.Collector interface.
func (collector *procTableCollector) Describe(ch chan<- *prometheus.Desc) | {
ch <- procTableRunning
ch <- procTableSucceeded
ch <- procTableFailed
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | local-volume/provisioner/pkg/metrics/collectors/proc_table_collector.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/metrics/collectors/proc_table_collector.go#L60-L68 | go | train | // Collect implements the prometheus.Collector interface. | func (collector *procTableCollector) Collect(ch chan<- prometheus.Metric) | // Collect implements the prometheus.Collector interface.
func (collector *procTableCollector) Collect(ch chan<- prometheus.Metric) | {
stats := collector.procTable.Stats()
addGauge := func(desc *prometheus.Desc, v float64, lv ...string) {
ch <- prometheus.MustNewConstMetric(desc, prometheus.GaugeValue, v, lv...)
}
addGauge(procTableRunning, float64(stats.Running))
addGauge(procTableSucceeded, float64(stats.Succeeded))
addGauge(procTableFailed, float64(stats.Failed))
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | local-volume/provisioner/pkg/populator/populator.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/populator/populator.go#L33-L63 | go | train | // NewPopulator returns a Populator object to update the PV cache | func NewPopulator(config *common.RuntimeConfig) *Populator | // NewPopulator returns a Populator object to update the PV cache
func NewPopulator(config *common.RuntimeConfig) *Populator | {
p := &Populator{RuntimeConfig: config}
sharedInformer := config.InformerFactory.Core().V1().PersistentVolumes()
sharedInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
pv, ok := obj.(*v1.PersistentVolume)
if !ok {
glog.Errorf("Added object is not a v1.PersistentVolume type")
return
}
p.handlePVUpdate(pv)
},
UpdateFunc: func(oldObj, newObj interface{}) {
newPV, ok := newObj.(*v1.PersistentVolume)
if !ok {
glog.Errorf("Updated object is not a v1.PersistentVolume type")
return
}
p.handlePVUpdate(newPV)
},
DeleteFunc: func(obj interface{}) {
pv, ok := obj.(*v1.PersistentVolume)
if !ok {
glog.Errorf("Added object is not a v1.PersistentVolume type")
return
}
p.handlePVDelete(pv)
},
})
return p
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | local-volume/provisioner/pkg/util/volume_util.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/volume_util.go#L61-L74 | go | train | // IsDir checks if the given path is a directory | func (u *volumeUtil) IsDir(fullPath string) (bool, error) | // IsDir checks if the given path is a directory
func (u *volumeUtil) IsDir(fullPath string) (bool, error) | {
dir, err := os.Open(fullPath)
if err != nil {
return false, err
}
defer dir.Close()
stat, err := dir.Stat()
if err != nil {
return false, err
}
return stat.IsDir(), nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | local-volume/provisioner/pkg/util/volume_util.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/volume_util.go#L77-L89 | go | train | // ReadDir returns a list all the files under the given directory | func (u *volumeUtil) ReadDir(fullPath string) ([]string, error) | // ReadDir returns a list all the files under the given directory
func (u *volumeUtil) ReadDir(fullPath string) ([]string, error) | {
dir, err := os.Open(fullPath)
if err != nil {
return nil, err
}
defer dir.Close()
files, err := dir.Readdirnames(-1)
if err != nil {
return nil, err
}
return files, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | local-volume/provisioner/pkg/util/volume_util.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/volume_util.go#L92-L112 | go | train | // DeleteContents deletes all the contents under the given directory | func (u *volumeUtil) DeleteContents(fullPath string) error | // DeleteContents deletes all the contents under the given directory
func (u *volumeUtil) DeleteContents(fullPath string) error | {
dir, err := os.Open(fullPath)
if err != nil {
return err
}
defer dir.Close()
files, err := dir.Readdirnames(-1)
if err != nil {
return err
}
errList := []error{}
for _, file := range files {
err = os.RemoveAll(filepath.Join(fullPath, file))
if err != nil {
errList = append(errList, err)
}
}
return utilerrors.NewAggregate(errList)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | local-volume/provisioner/pkg/util/volume_util.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/volume_util.go#L117-L120 | go | train | // GetFsCapacityByte returns capacity in bytes about a mounted filesystem.
// fullPath is the pathname of any file within the mounted filesystem. Capacity
// returned here is total capacity. | func (u *volumeUtil) GetFsCapacityByte(fullPath string) (int64, error) | // GetFsCapacityByte returns capacity in bytes about a mounted filesystem.
// fullPath is the pathname of any file within the mounted filesystem. Capacity
// returned here is total capacity.
func (u *volumeUtil) GetFsCapacityByte(fullPath string) (int64, error) | {
_, capacity, _, _, _, _, err := fs.FsInfo(fullPath)
return capacity, err
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | local-volume/provisioner/pkg/util/volume_util.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/volume_util.go#L151-L156 | go | train | // NewFakeVolumeUtil returns a VolumeUtil object for use in unit testing | func NewFakeVolumeUtil(deleteShouldFail bool, dirFiles map[string][]*FakeDirEntry) *FakeVolumeUtil | // NewFakeVolumeUtil returns a VolumeUtil object for use in unit testing
func NewFakeVolumeUtil(deleteShouldFail bool, dirFiles map[string][]*FakeDirEntry) *FakeVolumeUtil | {
return &FakeVolumeUtil{
directoryFiles: dirFiles,
deleteShouldFail: deleteShouldFail,
}
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | local-volume/provisioner/pkg/util/volume_util.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/volume_util.go#L180-L194 | go | train | // IsBlock checks if the given path is a block device | func (u *FakeVolumeUtil) IsBlock(fullPath string) (bool, error) | // IsBlock checks if the given path is a block device
func (u *FakeVolumeUtil) IsBlock(fullPath string) (bool, error) | {
dir, file := filepath.Split(fullPath)
dir = filepath.Clean(dir)
files, found := u.directoryFiles[dir]
if !found {
return false, fmt.Errorf("Directory %q not found", dir)
}
for _, f := range files {
if file == f.Name {
return f.VolumeType == FakeEntryBlock, nil
}
}
return false, fmt.Errorf("Directory entry %q not found", fullPath)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | local-volume/provisioner/pkg/util/volume_util.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/util/volume_util.go#L197-L207 | go | train | // ReadDir returns the list of all files under the given directory | func (u *FakeVolumeUtil) ReadDir(fullPath string) ([]string, error) | // ReadDir returns the list of all files under the given directory
func (u *FakeVolumeUtil) ReadDir(fullPath string) ([]string, error) | {
fileNames := []string{}
files, found := u.directoryFiles[fullPath]
if !found {
return nil, fmt.Errorf("Directory %q not found", fullPath)
}
for _, file := range files {
fileNames = append(fileNames, file.Name)
}
return fileNames, nil
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.