glusterfs.go 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package glusterfs
  14. import (
  15. "fmt"
  16. "math"
  17. "math/rand"
  18. "os"
  19. "path/filepath"
  20. "runtime"
  21. "strconv"
  22. dstrings "strings"
  23. "sync"
  24. gcli "github.com/heketi/heketi/client/api/go-client"
  25. gapi "github.com/heketi/heketi/pkg/glusterfs/api"
  26. "k8s.io/api/core/v1"
  27. "k8s.io/apimachinery/pkg/api/errors"
  28. "k8s.io/apimachinery/pkg/api/resource"
  29. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  30. "k8s.io/apimachinery/pkg/labels"
  31. "k8s.io/apimachinery/pkg/types"
  32. "k8s.io/apimachinery/pkg/util/sets"
  33. "k8s.io/apimachinery/pkg/util/uuid"
  34. clientset "k8s.io/client-go/kubernetes"
  35. volumehelpers "k8s.io/cloud-provider/volume/helpers"
  36. "k8s.io/klog"
  37. v1helper "k8s.io/kubernetes/pkg/apis/core/v1/helper"
  38. "k8s.io/kubernetes/pkg/util/mount"
  39. "k8s.io/kubernetes/pkg/volume"
  40. volutil "k8s.io/kubernetes/pkg/volume/util"
  41. utilstrings "k8s.io/utils/strings"
  42. )
  43. // ProbeVolumePlugins is the primary entrypoint for volume plugins.
  44. func ProbeVolumePlugins() []volume.VolumePlugin {
  45. return []volume.VolumePlugin{&glusterfsPlugin{host: nil, gidTable: make(map[string]*MinMaxAllocator)}}
  46. }
  47. type glusterfsPlugin struct {
  48. host volume.VolumeHost
  49. gidTable map[string]*MinMaxAllocator
  50. gidTableLock sync.Mutex
  51. }
  52. var _ volume.VolumePlugin = &glusterfsPlugin{}
  53. var _ volume.PersistentVolumePlugin = &glusterfsPlugin{}
  54. var _ volume.DeletableVolumePlugin = &glusterfsPlugin{}
  55. var _ volume.ProvisionableVolumePlugin = &glusterfsPlugin{}
  56. var _ volume.ExpandableVolumePlugin = &glusterfsPlugin{}
  57. var _ volume.Provisioner = &glusterfsVolumeProvisioner{}
  58. var _ volume.Deleter = &glusterfsVolumeDeleter{}
  59. const (
  60. glusterfsPluginName = "kubernetes.io/glusterfs"
  61. volPrefix = "vol_"
  62. dynamicEpSvcPrefix = "glusterfs-dynamic"
  63. replicaCount = 3
  64. durabilityType = "replicate"
  65. secretKeyName = "key" // key name used in secret
  66. gciLinuxGlusterMountBinaryPath = "/sbin/mount.glusterfs"
  67. defaultGidMin = 2000
  68. defaultGidMax = math.MaxInt32
  69. // maxCustomEpNamePrefix is the maximum number of chars.
  70. // which can be used as ep/svc name prefix. This number is carved
  71. // out from below formula.
  72. // max length of name of an ep - length of pvc uuid
  73. // where max length of name of an ep is 63 and length of uuid is 37
  74. maxCustomEpNamePrefixLen = 26
  75. // absoluteGidMin/Max are currently the same as the
  76. // default values, but they play a different role and
  77. // could take a different value. Only thing we need is:
  78. // absGidMin <= defGidMin <= defGidMax <= absGidMax
  79. absoluteGidMin = 2000
  80. absoluteGidMax = math.MaxInt32
  81. linuxGlusterMountBinary = "mount.glusterfs"
  82. heketiAnn = "heketi-dynamic-provisioner"
  83. glusterTypeAnn = "gluster.org/type"
  84. glusterDescAnn = "Gluster-Internal: Dynamically provisioned PV"
  85. heketiVolIDAnn = "gluster.kubernetes.io/heketi-volume-id"
  86. )
  87. func (plugin *glusterfsPlugin) Init(host volume.VolumeHost) error {
  88. plugin.host = host
  89. return nil
  90. }
  91. func (plugin *glusterfsPlugin) GetPluginName() string {
  92. return glusterfsPluginName
  93. }
  94. func (plugin *glusterfsPlugin) GetVolumeName(spec *volume.Spec) (string, error) {
  95. return "", fmt.Errorf("GetVolumeName() is unimplemented for GlusterFS")
  96. }
  97. func (plugin *glusterfsPlugin) CanSupport(spec *volume.Spec) bool {
  98. return (spec.PersistentVolume != nil && spec.PersistentVolume.Spec.Glusterfs != nil) ||
  99. (spec.Volume != nil && spec.Volume.Glusterfs != nil)
  100. }
  101. func (plugin *glusterfsPlugin) IsMigratedToCSI() bool {
  102. return false
  103. }
  104. func (plugin *glusterfsPlugin) RequiresRemount() bool {
  105. return false
  106. }
  107. func (plugin *glusterfsPlugin) SupportsMountOption() bool {
  108. return true
  109. }
  110. func (plugin *glusterfsPlugin) SupportsBulkVolumeVerification() bool {
  111. return false
  112. }
  113. func (plugin *glusterfsPlugin) RequiresFSResize() bool {
  114. return false
  115. }
  116. func (plugin *glusterfsPlugin) GetAccessModes() []v1.PersistentVolumeAccessMode {
  117. return []v1.PersistentVolumeAccessMode{
  118. v1.ReadWriteOnce,
  119. v1.ReadOnlyMany,
  120. v1.ReadWriteMany,
  121. }
  122. }
  123. func (plugin *glusterfsPlugin) NewMounter(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.Mounter, error) {
  124. epName, epNamespace, err := plugin.getEndpointNameAndNamespace(spec, pod.Namespace)
  125. if err != nil {
  126. return nil, err
  127. }
  128. kubeClient := plugin.host.GetKubeClient()
  129. if kubeClient == nil {
  130. return nil, fmt.Errorf("failed to get kube client to initialize mounter")
  131. }
  132. ep, err := kubeClient.CoreV1().Endpoints(epNamespace).Get(epName, metav1.GetOptions{})
  133. if err != nil {
  134. klog.Errorf("failed to get endpoint %s: %v", epName, err)
  135. return nil, err
  136. }
  137. klog.V(4).Infof("glusterfs pv endpoint %v", ep)
  138. return plugin.newMounterInternal(spec, ep, pod, plugin.host.GetMounter(plugin.GetPluginName()))
  139. }
  140. func (plugin *glusterfsPlugin) getEndpointNameAndNamespace(spec *volume.Spec, defaultNamespace string) (string, string, error) {
  141. if spec.Volume != nil && spec.Volume.Glusterfs != nil {
  142. endpoints := spec.Volume.Glusterfs.EndpointsName
  143. if endpoints == "" {
  144. return "", "", fmt.Errorf("no glusterFS endpoint specified")
  145. }
  146. return endpoints, defaultNamespace, nil
  147. } else if spec.PersistentVolume != nil &&
  148. spec.PersistentVolume.Spec.Glusterfs != nil {
  149. endpoints := spec.PersistentVolume.Spec.Glusterfs.EndpointsName
  150. endpointsNs := defaultNamespace
  151. overriddenNs := spec.PersistentVolume.Spec.Glusterfs.EndpointsNamespace
  152. if overriddenNs != nil {
  153. if len(*overriddenNs) > 0 {
  154. endpointsNs = *overriddenNs
  155. } else {
  156. return "", "", fmt.Errorf("endpointnamespace field set, but no endpointnamespace specified")
  157. }
  158. }
  159. return endpoints, endpointsNs, nil
  160. }
  161. return "", "", fmt.Errorf("spec does not reference a GlusterFS volume type")
  162. }
  163. func (plugin *glusterfsPlugin) newMounterInternal(spec *volume.Spec, ep *v1.Endpoints, pod *v1.Pod, mounter mount.Interface) (volume.Mounter, error) {
  164. volPath, readOnly, err := getVolumeInfo(spec)
  165. if err != nil {
  166. klog.Errorf("failed to get volumesource: %v", err)
  167. return nil, err
  168. }
  169. return &glusterfsMounter{
  170. glusterfs: &glusterfs{
  171. volName: spec.Name(),
  172. mounter: mounter,
  173. pod: pod,
  174. plugin: plugin,
  175. MetricsProvider: volume.NewMetricsStatFS(plugin.host.GetPodVolumeDir(pod.UID, utilstrings.EscapeQualifiedName(glusterfsPluginName), spec.Name())),
  176. },
  177. hosts: ep,
  178. path: volPath,
  179. readOnly: readOnly,
  180. mountOptions: volutil.MountOptionFromSpec(spec),
  181. }, nil
  182. }
  183. func (plugin *glusterfsPlugin) NewUnmounter(volName string, podUID types.UID) (volume.Unmounter, error) {
  184. return plugin.newUnmounterInternal(volName, podUID, plugin.host.GetMounter(plugin.GetPluginName()))
  185. }
  186. func (plugin *glusterfsPlugin) newUnmounterInternal(volName string, podUID types.UID, mounter mount.Interface) (volume.Unmounter, error) {
  187. return &glusterfsUnmounter{&glusterfs{
  188. volName: volName,
  189. mounter: mounter,
  190. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{UID: podUID}},
  191. plugin: plugin,
  192. MetricsProvider: volume.NewMetricsStatFS(plugin.host.GetPodVolumeDir(podUID, utilstrings.EscapeQualifiedName(glusterfsPluginName), volName)),
  193. }}, nil
  194. }
  195. func (plugin *glusterfsPlugin) ConstructVolumeSpec(volumeName, mountPath string) (*volume.Spec, error) {
  196. // To reconstruct volume spec we need endpoint where fetching endpoint from mount
  197. // string looks to be impossible, so returning error.
  198. return nil, fmt.Errorf("impossible to reconstruct glusterfs volume spec from volume mountpath")
  199. }
  200. // Glusterfs volumes represent a bare host file or directory mount of an Glusterfs export.
  201. type glusterfs struct {
  202. volName string
  203. pod *v1.Pod
  204. mounter mount.Interface
  205. plugin *glusterfsPlugin
  206. volume.MetricsProvider
  207. }
  208. type glusterfsMounter struct {
  209. *glusterfs
  210. hosts *v1.Endpoints
  211. path string
  212. readOnly bool
  213. mountOptions []string
  214. }
  215. var _ volume.Mounter = &glusterfsMounter{}
  216. func (b *glusterfsMounter) GetAttributes() volume.Attributes {
  217. return volume.Attributes{
  218. ReadOnly: b.readOnly,
  219. Managed: false,
  220. SupportsSELinux: false,
  221. }
  222. }
  223. // Checks prior to mount operations to verify that the required components (binaries, etc.)
  224. // to mount the volume are available on the underlying node.
  225. // If not, it returns an error
  226. func (b *glusterfsMounter) CanMount() error {
  227. exe := b.plugin.host.GetExec(b.plugin.GetPluginName())
  228. switch runtime.GOOS {
  229. case "linux":
  230. if _, err := exe.Run("test", "-x", gciLinuxGlusterMountBinaryPath); err != nil {
  231. return fmt.Errorf("required binary %s is missing", gciLinuxGlusterMountBinaryPath)
  232. }
  233. }
  234. return nil
  235. }
  236. // SetUp attaches the disk and bind mounts to the volume path.
  237. func (b *glusterfsMounter) SetUp(mounterArgs volume.MounterArgs) error {
  238. return b.SetUpAt(b.GetPath(), mounterArgs)
  239. }
  240. func (b *glusterfsMounter) SetUpAt(dir string, mounterArgs volume.MounterArgs) error {
  241. notMnt, err := b.mounter.IsLikelyNotMountPoint(dir)
  242. klog.V(4).Infof("mount setup: %s %v %v", dir, !notMnt, err)
  243. if err != nil && !os.IsNotExist(err) {
  244. return err
  245. }
  246. if !notMnt {
  247. return nil
  248. }
  249. if err := os.MkdirAll(dir, 0750); err != nil {
  250. return err
  251. }
  252. err = b.setUpAtInternal(dir)
  253. if err == nil {
  254. return nil
  255. }
  256. // Cleanup upon failure.
  257. mount.CleanupMountPoint(dir, b.mounter, false)
  258. return err
  259. }
  260. func (glusterfsVolume *glusterfs) GetPath() string {
  261. name := glusterfsPluginName
  262. return glusterfsVolume.plugin.host.GetPodVolumeDir(glusterfsVolume.pod.UID, utilstrings.EscapeQualifiedName(name), glusterfsVolume.volName)
  263. }
  264. type glusterfsUnmounter struct {
  265. *glusterfs
  266. }
  267. var _ volume.Unmounter = &glusterfsUnmounter{}
  268. func (c *glusterfsUnmounter) TearDown() error {
  269. return c.TearDownAt(c.GetPath())
  270. }
  271. func (c *glusterfsUnmounter) TearDownAt(dir string) error {
  272. return mount.CleanupMountPoint(dir, c.mounter, false)
  273. }
  274. func (b *glusterfsMounter) setUpAtInternal(dir string) error {
  275. var errs error
  276. options := []string{}
  277. hasLogFile := false
  278. hasLogLevel := false
  279. log := ""
  280. if b.readOnly {
  281. options = append(options, "ro")
  282. }
  283. // Check for log-file,log-level options existence in user supplied mount options, if provided, use those.
  284. for _, userOpt := range b.mountOptions {
  285. switch {
  286. case dstrings.HasPrefix(userOpt, "log-file"):
  287. klog.V(4).Infof("log-file mount option has provided")
  288. hasLogFile = true
  289. case dstrings.HasPrefix(userOpt, "log-level"):
  290. klog.V(4).Infof("log-level mount option has provided")
  291. hasLogLevel = true
  292. }
  293. }
  294. // If logfile has not been provided, create driver specific log file.
  295. if !hasLogFile {
  296. p := filepath.Join(b.glusterfs.plugin.host.GetPluginDir(glusterfsPluginName), b.glusterfs.volName)
  297. if err := os.MkdirAll(p, 0750); err != nil {
  298. return fmt.Errorf("failed to create directory %v: %v", p, err)
  299. }
  300. // adding log-level ERROR to remove noise
  301. // and more specific log path so each pod has
  302. // its own log based on PV + Pod
  303. log = filepath.Join(p, b.pod.Name+"-glusterfs.log")
  304. // Use derived log file in gluster fuse mount
  305. options = append(options, "log-file="+log)
  306. }
  307. if !hasLogLevel {
  308. options = append(options, "log-level=ERROR")
  309. }
  310. var addrlist []string
  311. if b.hosts == nil {
  312. return fmt.Errorf("glusterfs endpoint is nil in mounter")
  313. }
  314. addr := sets.String{}
  315. if b.hosts.Subsets != nil {
  316. for _, s := range b.hosts.Subsets {
  317. for _, a := range s.Addresses {
  318. if !addr.Has(a.IP) {
  319. addr.Insert(a.IP)
  320. addrlist = append(addrlist, a.IP)
  321. }
  322. }
  323. }
  324. }
  325. //Add backup-volfile-servers and auto_unmount options.
  326. options = append(options, "backup-volfile-servers="+dstrings.Join(addrlist[:], ":"))
  327. options = append(options, "auto_unmount")
  328. mountOptions := volutil.JoinMountOptions(b.mountOptions, options)
  329. // with `backup-volfile-servers` mount option in place, it is not required to
  330. // iterate over all the servers in the addrlist. A mount attempt with this option
  331. // will fetch all the servers mentioned in the backup-volfile-servers list.
  332. // Refer to backup-volfile-servers @ http://docs.gluster.org/en/latest/Administrator%20Guide/Setting%20Up%20Clients/
  333. if (len(addrlist) > 0) && (addrlist[0] != "") {
  334. ip := addrlist[rand.Intn(len(addrlist))]
  335. errs = b.mounter.Mount(ip+":"+b.path, dir, "glusterfs", mountOptions)
  336. if errs == nil {
  337. klog.Infof("successfully mounted directory %s", dir)
  338. return nil
  339. }
  340. if dstrings.Contains(errs.Error(), "Invalid option auto_unmount") ||
  341. dstrings.Contains(errs.Error(), "Invalid argument") {
  342. // Give a try without `auto_unmount` mount option, because
  343. // it could be that gluster fuse client is older version and
  344. // mount.glusterfs is unaware of `auto_unmount`.
  345. noAutoMountOptions := make([]string, 0, len(mountOptions))
  346. for _, opt := range mountOptions {
  347. if opt != "auto_unmount" {
  348. noAutoMountOptions = append(noAutoMountOptions, opt)
  349. }
  350. }
  351. errs = b.mounter.Mount(ip+":"+b.path, dir, "glusterfs", noAutoMountOptions)
  352. if errs == nil {
  353. klog.Infof("successfully mounted %s", dir)
  354. return nil
  355. }
  356. }
  357. } else {
  358. return fmt.Errorf("failed to execute mount command:[no valid ipaddress found in endpoint address list]")
  359. }
  360. // Failed mount scenario.
  361. // Since glusterfs does not return error text
  362. // it all goes in a log file, we will read the log file
  363. logErr := readGlusterLog(log, b.pod.Name)
  364. if logErr != nil {
  365. return fmt.Errorf("mount failed: %v, the following error information was pulled from the glusterfs log to help diagnose this issue: %v", errs, logErr)
  366. }
  367. return fmt.Errorf("mount failed: %v", errs)
  368. }
  369. //getVolumeInfo returns 'path' and 'readonly' field values from the provided glusterfs spec.
  370. func getVolumeInfo(spec *volume.Spec) (string, bool, error) {
  371. if spec.Volume != nil && spec.Volume.Glusterfs != nil {
  372. return spec.Volume.Glusterfs.Path, spec.Volume.Glusterfs.ReadOnly, nil
  373. } else if spec.PersistentVolume != nil &&
  374. spec.PersistentVolume.Spec.Glusterfs != nil {
  375. return spec.PersistentVolume.Spec.Glusterfs.Path, spec.ReadOnly, nil
  376. }
  377. return "", false, fmt.Errorf("spec does not reference a Glusterfs volume type")
  378. }
  379. func (plugin *glusterfsPlugin) NewProvisioner(options volume.VolumeOptions) (volume.Provisioner, error) {
  380. return plugin.newProvisionerInternal(options)
  381. }
  382. func (plugin *glusterfsPlugin) newProvisionerInternal(options volume.VolumeOptions) (volume.Provisioner, error) {
  383. return &glusterfsVolumeProvisioner{
  384. glusterfsMounter: &glusterfsMounter{
  385. glusterfs: &glusterfs{
  386. plugin: plugin,
  387. },
  388. },
  389. options: options,
  390. }, nil
  391. }
  392. type provisionerConfig struct {
  393. url string
  394. user string
  395. userKey string
  396. secretNamespace string
  397. secretName string
  398. secretValue string
  399. clusterID string
  400. gidMin int
  401. gidMax int
  402. volumeType gapi.VolumeDurabilityInfo
  403. volumeOptions []string
  404. volumeNamePrefix string
  405. thinPoolSnapFactor float32
  406. customEpNamePrefix string
  407. }
  408. type glusterfsVolumeProvisioner struct {
  409. *glusterfsMounter
  410. provisionerConfig
  411. options volume.VolumeOptions
  412. }
  413. func convertGid(gidString string) (int, error) {
  414. gid64, err := strconv.ParseInt(gidString, 10, 32)
  415. if err != nil {
  416. return 0, fmt.Errorf("failed to parse gid %v: %v", gidString, err)
  417. }
  418. if gid64 < 0 {
  419. return 0, fmt.Errorf("negative GIDs %v are not allowed", gidString)
  420. }
  421. // ParseInt returns a int64, but since we parsed only
  422. // for 32 bit, we can cast to int without loss:
  423. gid := int(gid64)
  424. return gid, nil
  425. }
  426. func convertVolumeParam(volumeString string) (int, error) {
  427. count, err := strconv.Atoi(volumeString)
  428. if err != nil {
  429. return 0, fmt.Errorf("failed to parse volumestring %q: %v", volumeString, err)
  430. }
  431. if count < 0 {
  432. return 0, fmt.Errorf("negative values are not allowed")
  433. }
  434. return count, nil
  435. }
  436. func (plugin *glusterfsPlugin) NewDeleter(spec *volume.Spec) (volume.Deleter, error) {
  437. return plugin.newDeleterInternal(spec)
  438. }
  439. func (plugin *glusterfsPlugin) newDeleterInternal(spec *volume.Spec) (volume.Deleter, error) {
  440. if spec.PersistentVolume != nil && spec.PersistentVolume.Spec.Glusterfs == nil {
  441. return nil, fmt.Errorf("spec.PersistentVolume.Spec.Glusterfs is nil")
  442. }
  443. return &glusterfsVolumeDeleter{
  444. glusterfsMounter: &glusterfsMounter{
  445. glusterfs: &glusterfs{
  446. volName: spec.Name(),
  447. plugin: plugin,
  448. },
  449. path: spec.PersistentVolume.Spec.Glusterfs.Path,
  450. },
  451. spec: spec.PersistentVolume,
  452. }, nil
  453. }
  454. type glusterfsVolumeDeleter struct {
  455. *glusterfsMounter
  456. provisionerConfig
  457. spec *v1.PersistentVolume
  458. }
  459. func (d *glusterfsVolumeDeleter) GetPath() string {
  460. name := glusterfsPluginName
  461. return d.plugin.host.GetPodVolumeDir(d.glusterfsMounter.glusterfs.pod.UID, utilstrings.EscapeQualifiedName(name), d.glusterfsMounter.glusterfs.volName)
  462. }
  463. // Traverse the PVs, fetching all the GIDs from those
  464. // in a given storage class, and mark them in the table.
  465. func (plugin *glusterfsPlugin) collectGids(className string, gidTable *MinMaxAllocator) error {
  466. kubeClient := plugin.host.GetKubeClient()
  467. if kubeClient == nil {
  468. return fmt.Errorf("failed to get kube client when collecting gids")
  469. }
  470. pvList, err := kubeClient.CoreV1().PersistentVolumes().List(metav1.ListOptions{LabelSelector: labels.Everything().String()})
  471. if err != nil {
  472. return fmt.Errorf("failed to get existing persistent volumes")
  473. }
  474. for _, pv := range pvList.Items {
  475. if v1helper.GetPersistentVolumeClass(&pv) != className {
  476. continue
  477. }
  478. pvName := pv.ObjectMeta.Name
  479. gidStr, ok := pv.Annotations[volutil.VolumeGidAnnotationKey]
  480. if !ok {
  481. klog.Warningf("no GID found in pv %v", pvName)
  482. continue
  483. }
  484. gid, err := convertGid(gidStr)
  485. if err != nil {
  486. klog.Errorf("failed to parse gid %s: %v", gidStr, err)
  487. continue
  488. }
  489. _, err = gidTable.Allocate(gid)
  490. if err == ErrConflict {
  491. klog.Warningf("GID %v found in pv %v was already allocated", gid, pvName)
  492. } else if err != nil {
  493. return fmt.Errorf("failed to store gid %v found in pv %v: %v", gid, pvName, err)
  494. }
  495. }
  496. return nil
  497. }
  498. // Return the gid table for a storage class.
  499. // - If this is the first time, fill it with all the gids
  500. // used in PVs of this storage class by traversing the PVs.
  501. // - Adapt the range of the table to the current range of the SC.
  502. func (plugin *glusterfsPlugin) getGidTable(className string, min int, max int) (*MinMaxAllocator, error) {
  503. plugin.gidTableLock.Lock()
  504. gidTable, ok := plugin.gidTable[className]
  505. plugin.gidTableLock.Unlock()
  506. if ok {
  507. err := gidTable.SetRange(min, max)
  508. if err != nil {
  509. return nil, err
  510. }
  511. return gidTable, nil
  512. }
  513. // create a new table and fill it
  514. newGidTable, err := NewMinMaxAllocator(0, absoluteGidMax)
  515. if err != nil {
  516. return nil, err
  517. }
  518. // collect gids with the full range
  519. err = plugin.collectGids(className, newGidTable)
  520. if err != nil {
  521. return nil, err
  522. }
  523. // and only reduce the range afterwards
  524. err = newGidTable.SetRange(min, max)
  525. if err != nil {
  526. return nil, err
  527. }
  528. // if in the meantime a table appeared, use it
  529. plugin.gidTableLock.Lock()
  530. defer plugin.gidTableLock.Unlock()
  531. gidTable, ok = plugin.gidTable[className]
  532. if ok {
  533. err = gidTable.SetRange(min, max)
  534. if err != nil {
  535. return nil, err
  536. }
  537. return gidTable, nil
  538. }
  539. plugin.gidTable[className] = newGidTable
  540. return newGidTable, nil
  541. }
  542. func (d *glusterfsVolumeDeleter) getGid() (int, bool, error) {
  543. gidStr, ok := d.spec.Annotations[volutil.VolumeGidAnnotationKey]
  544. if !ok {
  545. return 0, false, nil
  546. }
  547. gid, err := convertGid(gidStr)
  548. return gid, true, err
  549. }
  550. func (d *glusterfsVolumeDeleter) Delete() error {
  551. klog.V(2).Infof("delete volume %s", d.glusterfsMounter.path)
  552. volumeName := d.glusterfsMounter.path
  553. volumeID, err := getVolumeID(d.spec, volumeName)
  554. if err != nil {
  555. return fmt.Errorf("failed to get volumeID: %v", err)
  556. }
  557. class, err := volutil.GetClassForVolume(d.plugin.host.GetKubeClient(), d.spec)
  558. if err != nil {
  559. return err
  560. }
  561. cfg, err := parseClassParameters(class.Parameters, d.plugin.host.GetKubeClient())
  562. if err != nil {
  563. return err
  564. }
  565. d.provisionerConfig = *cfg
  566. klog.V(4).Infof("deleting volume %q", volumeID)
  567. gid, exists, err := d.getGid()
  568. if err != nil {
  569. klog.Error(err)
  570. } else if exists {
  571. gidTable, err := d.plugin.getGidTable(class.Name, cfg.gidMin, cfg.gidMax)
  572. if err != nil {
  573. return fmt.Errorf("failed to get gidTable: %v", err)
  574. }
  575. err = gidTable.Release(gid)
  576. if err != nil {
  577. return fmt.Errorf("failed to release gid %v: %v", gid, err)
  578. }
  579. }
  580. cli := gcli.NewClient(d.url, d.user, d.secretValue)
  581. if cli == nil {
  582. klog.Errorf("failed to create glusterfs REST client")
  583. return fmt.Errorf("failed to create glusterfs REST client, REST server authentication failed")
  584. }
  585. err = cli.VolumeDelete(volumeID)
  586. if err != nil {
  587. klog.Errorf("failed to delete volume %s: %v", volumeName, err)
  588. return err
  589. }
  590. klog.V(2).Infof("volume %s deleted successfully", volumeName)
  591. //Deleter takes endpoint and namespace from pv spec.
  592. pvSpec := d.spec.Spec
  593. var dynamicEndpoint, dynamicNamespace string
  594. if pvSpec.ClaimRef == nil {
  595. klog.Errorf("ClaimRef is nil")
  596. return fmt.Errorf("ClaimRef is nil")
  597. }
  598. if pvSpec.ClaimRef.Namespace == "" {
  599. klog.Errorf("namespace is nil")
  600. return fmt.Errorf("namespace is nil")
  601. }
  602. dynamicNamespace = pvSpec.ClaimRef.Namespace
  603. if pvSpec.Glusterfs.EndpointsName != "" {
  604. dynamicEndpoint = pvSpec.Glusterfs.EndpointsName
  605. }
  606. klog.V(3).Infof("dynamic namespace and endpoint %v/%v", dynamicNamespace, dynamicEndpoint)
  607. err = d.deleteEndpointService(dynamicNamespace, dynamicEndpoint)
  608. if err != nil {
  609. klog.Errorf("failed to delete endpoint/service %v/%v: %v", dynamicNamespace, dynamicEndpoint, err)
  610. } else {
  611. klog.V(1).Infof("endpoint %v/%v is deleted successfully ", dynamicNamespace, dynamicEndpoint)
  612. }
  613. return nil
  614. }
  615. func (p *glusterfsVolumeProvisioner) Provision(selectedNode *v1.Node, allowedTopologies []v1.TopologySelectorTerm) (*v1.PersistentVolume, error) {
  616. if !volutil.AccessModesContainedInAll(p.plugin.GetAccessModes(), p.options.PVC.Spec.AccessModes) {
  617. return nil, fmt.Errorf("invalid AccessModes %v: only AccessModes %v are supported", p.options.PVC.Spec.AccessModes, p.plugin.GetAccessModes())
  618. }
  619. if p.options.PVC.Spec.Selector != nil {
  620. klog.V(4).Infof("not able to parse your claim Selector")
  621. return nil, fmt.Errorf("not able to parse your claim Selector")
  622. }
  623. if volutil.CheckPersistentVolumeClaimModeBlock(p.options.PVC) {
  624. return nil, fmt.Errorf("%s does not support block volume provisioning", p.plugin.GetPluginName())
  625. }
  626. klog.V(4).Infof("provision volume with options %v", p.options)
  627. scName := v1helper.GetPersistentVolumeClaimClass(p.options.PVC)
  628. cfg, err := parseClassParameters(p.options.Parameters, p.plugin.host.GetKubeClient())
  629. if err != nil {
  630. return nil, err
  631. }
  632. p.provisionerConfig = *cfg
  633. gidTable, err := p.plugin.getGidTable(scName, cfg.gidMin, cfg.gidMax)
  634. if err != nil {
  635. return nil, fmt.Errorf("failed to get gidTable: %v", err)
  636. }
  637. gid, _, err := gidTable.AllocateNext()
  638. if err != nil {
  639. klog.Errorf("failed to reserve GID from table: %v", err)
  640. return nil, fmt.Errorf("failed to reserve GID from table: %v", err)
  641. }
  642. klog.V(2).Infof("allocated GID %d for PVC %s", gid, p.options.PVC.Name)
  643. glusterfs, sizeGiB, volID, err := p.CreateVolume(gid)
  644. if err != nil {
  645. if releaseErr := gidTable.Release(gid); releaseErr != nil {
  646. klog.Errorf("error when releasing GID in storageclass %s: %v", scName, releaseErr)
  647. }
  648. return nil, fmt.Errorf("failed to create volume: %v", err)
  649. }
  650. mode := v1.PersistentVolumeFilesystem
  651. pv := new(v1.PersistentVolume)
  652. pv.Spec.PersistentVolumeSource.Glusterfs = glusterfs
  653. pv.Spec.PersistentVolumeReclaimPolicy = p.options.PersistentVolumeReclaimPolicy
  654. pv.Spec.AccessModes = p.options.PVC.Spec.AccessModes
  655. pv.Spec.VolumeMode = &mode
  656. if len(pv.Spec.AccessModes) == 0 {
  657. pv.Spec.AccessModes = p.plugin.GetAccessModes()
  658. }
  659. pv.Spec.MountOptions = p.options.MountOptions
  660. gidStr := strconv.FormatInt(int64(gid), 10)
  661. pv.Annotations = map[string]string{
  662. volutil.VolumeGidAnnotationKey: gidStr,
  663. volutil.VolumeDynamicallyCreatedByKey: heketiAnn,
  664. glusterTypeAnn: "file",
  665. "Description": glusterDescAnn,
  666. heketiVolIDAnn: volID,
  667. }
  668. pv.Spec.Capacity = v1.ResourceList{
  669. v1.ResourceName(v1.ResourceStorage): resource.MustParse(fmt.Sprintf("%dGi", sizeGiB)),
  670. }
  671. return pv, nil
  672. }
  673. func (p *glusterfsVolumeProvisioner) CreateVolume(gid int) (r *v1.GlusterfsPersistentVolumeSource, size int, volID string, err error) {
  674. var clusterIDs []string
  675. customVolumeName := ""
  676. epServiceName := ""
  677. kubeClient := p.plugin.host.GetKubeClient()
  678. if kubeClient == nil {
  679. return nil, 0, "", fmt.Errorf("failed to get kube client to update endpoint")
  680. }
  681. if len(p.provisionerConfig.customEpNamePrefix) == 0 {
  682. epServiceName = string(p.options.PVC.UID)
  683. } else {
  684. epServiceName = p.provisionerConfig.customEpNamePrefix + "-" + string(p.options.PVC.UID)
  685. }
  686. epNamespace := p.options.PVC.Namespace
  687. endpoint, service, err := p.createOrGetEndpointService(epNamespace, epServiceName, p.options.PVC)
  688. if err != nil {
  689. klog.Errorf("failed to create endpoint/service %v/%v: %v", epNamespace, epServiceName, err)
  690. return nil, 0, "", fmt.Errorf("failed to create endpoint/service %v/%v: %v", epNamespace, epServiceName, err)
  691. }
  692. klog.V(3).Infof("dynamic endpoint %v and service %v ", endpoint, service)
  693. capacity := p.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]
  694. // GlusterFS/heketi creates volumes in units of GiB.
  695. sz, err := volumehelpers.RoundUpToGiBInt(capacity)
  696. if err != nil {
  697. return nil, 0, "", err
  698. }
  699. klog.V(2).Infof("create volume of size %dGiB", sz)
  700. if p.url == "" {
  701. return nil, 0, "", fmt.Errorf("failed to create glusterfs REST client, REST URL is empty")
  702. }
  703. cli := gcli.NewClient(p.url, p.user, p.secretValue)
  704. if cli == nil {
  705. return nil, 0, "", fmt.Errorf("failed to create glusterfs REST client, REST server authentication failed")
  706. }
  707. if p.provisionerConfig.clusterID != "" {
  708. clusterIDs = dstrings.Split(p.clusterID, ",")
  709. klog.V(4).Infof("provided clusterIDs %v", clusterIDs)
  710. }
  711. if p.provisionerConfig.volumeNamePrefix != "" {
  712. customVolumeName = fmt.Sprintf("%s_%s_%s_%s", p.provisionerConfig.volumeNamePrefix, p.options.PVC.Namespace, p.options.PVC.Name, uuid.NewUUID())
  713. }
  714. gid64 := int64(gid)
  715. snaps := struct {
  716. Enable bool `json:"enable"`
  717. Factor float32 `json:"factor"`
  718. }{
  719. true,
  720. p.provisionerConfig.thinPoolSnapFactor,
  721. }
  722. volumeReq := &gapi.VolumeCreateRequest{Size: sz, Name: customVolumeName, Clusters: clusterIDs, Gid: gid64, Durability: p.volumeType, GlusterVolumeOptions: p.volumeOptions, Snapshot: snaps}
  723. volume, err := cli.VolumeCreate(volumeReq)
  724. if err != nil {
  725. return nil, 0, "", fmt.Errorf("failed to create volume: %v", err)
  726. }
  727. klog.V(1).Infof("volume with size %d and name %s created", volume.Size, volume.Name)
  728. volID = volume.Id
  729. dynamicHostIps, err := getClusterNodes(cli, volume.Cluster)
  730. if err != nil {
  731. return nil, 0, "", fmt.Errorf("failed to get cluster nodes for volume %s: %v", volume, err)
  732. }
  733. addrlist := make([]v1.EndpointAddress, len(dynamicHostIps))
  734. for i, v := range dynamicHostIps {
  735. addrlist[i].IP = v
  736. }
  737. subset := make([]v1.EndpointSubset, 1)
  738. ports := []v1.EndpointPort{{Port: 1, Protocol: "TCP"}}
  739. endpoint.Subsets = subset
  740. endpoint.Subsets[0].Addresses = addrlist
  741. endpoint.Subsets[0].Ports = ports
  742. _, err = kubeClient.CoreV1().Endpoints(epNamespace).Update(endpoint)
  743. if err != nil {
  744. deleteErr := cli.VolumeDelete(volume.Id)
  745. if deleteErr != nil {
  746. klog.Errorf("failed to delete volume: %v, manual deletion of the volume required", deleteErr)
  747. }
  748. klog.V(3).Infof("failed to update endpoint, deleting %s", endpoint)
  749. err = kubeClient.CoreV1().Services(epNamespace).Delete(epServiceName, nil)
  750. if err != nil && errors.IsNotFound(err) {
  751. klog.V(1).Infof("service %s does not exist in namespace %s", epServiceName, epNamespace)
  752. err = nil
  753. }
  754. if err != nil {
  755. klog.Errorf("failed to delete service %s/%s: %v", epNamespace, epServiceName, err)
  756. }
  757. klog.V(1).Infof("service/endpoint: %s/%s deleted successfully", epNamespace, epServiceName)
  758. return nil, 0, "", fmt.Errorf("failed to update endpoint %s: %v", endpoint, err)
  759. }
  760. klog.V(3).Infof("endpoint %s updated successfully", endpoint)
  761. return &v1.GlusterfsPersistentVolumeSource{
  762. EndpointsName: endpoint.Name,
  763. EndpointsNamespace: &epNamespace,
  764. Path: volume.Name,
  765. ReadOnly: false,
  766. }, sz, volID, nil
  767. }
  768. // createOrGetEndpointService() makes sure an endpoint and service
  769. // exist for the given namespace, PVC name, endpoint name
  770. // I.e. the endpoint or service is only created
  771. // if it does not exist yet.
  772. func (p *glusterfsVolumeProvisioner) createOrGetEndpointService(namespace string, epServiceName string, pvc *v1.PersistentVolumeClaim) (endpoint *v1.Endpoints, service *v1.Service, err error) {
  773. pvcNameOrID := ""
  774. if len(pvc.Name) >= 63 {
  775. pvcNameOrID = string(pvc.UID)
  776. } else {
  777. pvcNameOrID = pvc.Name
  778. }
  779. endpoint = &v1.Endpoints{
  780. ObjectMeta: metav1.ObjectMeta{
  781. Namespace: namespace,
  782. Name: epServiceName,
  783. Labels: map[string]string{
  784. "gluster.kubernetes.io/provisioned-for-pvc": pvcNameOrID,
  785. },
  786. },
  787. }
  788. kubeClient := p.plugin.host.GetKubeClient()
  789. if kubeClient == nil {
  790. return nil, nil, fmt.Errorf("failed to get kube client when creating endpoint service")
  791. }
  792. _, err = kubeClient.CoreV1().Endpoints(namespace).Create(endpoint)
  793. if err != nil && errors.IsAlreadyExists(err) {
  794. klog.V(1).Infof("endpoint %s already exist in namespace %s", endpoint, namespace)
  795. err = nil
  796. }
  797. if err != nil {
  798. klog.Errorf("failed to create endpoint: %v", err)
  799. return nil, nil, fmt.Errorf("failed to create endpoint: %v", err)
  800. }
  801. service = &v1.Service{
  802. ObjectMeta: metav1.ObjectMeta{
  803. Name: epServiceName,
  804. Namespace: namespace,
  805. Labels: map[string]string{
  806. "gluster.kubernetes.io/provisioned-for-pvc": pvcNameOrID,
  807. },
  808. },
  809. Spec: v1.ServiceSpec{
  810. Ports: []v1.ServicePort{
  811. {Protocol: "TCP", Port: 1}}}}
  812. _, err = kubeClient.CoreV1().Services(namespace).Create(service)
  813. if err != nil && errors.IsAlreadyExists(err) {
  814. klog.V(1).Infof("service %s already exist in namespace %s", service, namespace)
  815. err = nil
  816. }
  817. if err != nil {
  818. klog.Errorf("failed to create service: %v", err)
  819. return nil, nil, fmt.Errorf("error creating service: %v", err)
  820. }
  821. return endpoint, service, nil
  822. }
  823. func (d *glusterfsVolumeDeleter) deleteEndpointService(namespace string, epServiceName string) (err error) {
  824. kubeClient := d.plugin.host.GetKubeClient()
  825. if kubeClient == nil {
  826. return fmt.Errorf("failed to get kube client when deleting endpoint service")
  827. }
  828. err = kubeClient.CoreV1().Services(namespace).Delete(epServiceName, nil)
  829. if err != nil {
  830. return fmt.Errorf("failed to delete service %s/%s: %v", namespace, epServiceName, err)
  831. }
  832. klog.V(1).Infof("service/endpoint: %s/%s deleted successfully", namespace, epServiceName)
  833. return nil
  834. }
  835. // parseSecret finds a given Secret instance and reads user password from it.
  836. func parseSecret(namespace, secretName string, kubeClient clientset.Interface) (string, error) {
  837. secretMap, err := volutil.GetSecretForPV(namespace, secretName, glusterfsPluginName, kubeClient)
  838. if err != nil {
  839. klog.Errorf("failed to get secret: %s/%s: %v", namespace, secretName, err)
  840. return "", fmt.Errorf("failed to get secret %s/%s: %v", namespace, secretName, err)
  841. }
  842. if len(secretMap) == 0 {
  843. return "", fmt.Errorf("empty secret map")
  844. }
  845. secret := ""
  846. for k, v := range secretMap {
  847. if k == secretKeyName {
  848. return v, nil
  849. }
  850. secret = v
  851. }
  852. // If not found, the last secret in the map wins as done before
  853. return secret, nil
  854. }
  855. // getClusterNodes() returns the cluster nodes of a given cluster
  856. func getClusterNodes(cli *gcli.Client, cluster string) (dynamicHostIps []string, err error) {
  857. clusterinfo, err := cli.ClusterInfo(cluster)
  858. if err != nil {
  859. return nil, fmt.Errorf("failed to get cluster details: %v", err)
  860. }
  861. // For the dynamically provisioned volume, we gather the list of node IPs
  862. // of the cluster on which provisioned volume belongs to, as there can be multiple
  863. // clusters.
  864. for _, node := range clusterinfo.Nodes {
  865. nodeInfo, err := cli.NodeInfo(string(node))
  866. if err != nil {
  867. return nil, fmt.Errorf("failed to get host ipaddress: %v", err)
  868. }
  869. ipaddr := dstrings.Join(nodeInfo.NodeAddRequest.Hostnames.Storage, "")
  870. dynamicHostIps = append(dynamicHostIps, ipaddr)
  871. }
  872. klog.V(3).Infof("host list :%v", dynamicHostIps)
  873. if len(dynamicHostIps) == 0 {
  874. return nil, fmt.Errorf("no hosts found: %v", err)
  875. }
  876. return dynamicHostIps, nil
  877. }
  878. // parseClassParameters parses StorageClass parameters.
  879. func parseClassParameters(params map[string]string, kubeClient clientset.Interface) (*provisionerConfig, error) {
  880. var cfg provisionerConfig
  881. var err error
  882. cfg.gidMin = defaultGidMin
  883. cfg.gidMax = defaultGidMax
  884. cfg.customEpNamePrefix = dynamicEpSvcPrefix
  885. authEnabled := true
  886. parseVolumeType := ""
  887. parseVolumeOptions := ""
  888. parseVolumeNamePrefix := ""
  889. parseThinPoolSnapFactor := ""
  890. //thin pool snap factor default to 1.0
  891. cfg.thinPoolSnapFactor = float32(1.0)
  892. for k, v := range params {
  893. switch dstrings.ToLower(k) {
  894. case "resturl":
  895. cfg.url = v
  896. case "restuser":
  897. cfg.user = v
  898. case "restuserkey":
  899. cfg.userKey = v
  900. case "secretname":
  901. cfg.secretName = v
  902. case "secretnamespace":
  903. cfg.secretNamespace = v
  904. case "clusterid":
  905. if len(v) != 0 {
  906. cfg.clusterID = v
  907. }
  908. case "restauthenabled":
  909. authEnabled = dstrings.ToLower(v) == "true"
  910. case "gidmin":
  911. parseGidMin, err := convertGid(v)
  912. if err != nil {
  913. return nil, fmt.Errorf("invalid gidMin value %q for volume plugin %s", k, glusterfsPluginName)
  914. }
  915. if parseGidMin < absoluteGidMin {
  916. return nil, fmt.Errorf("gidMin must be >= %v", absoluteGidMin)
  917. }
  918. if parseGidMin > absoluteGidMax {
  919. return nil, fmt.Errorf("gidMin must be <= %v", absoluteGidMax)
  920. }
  921. cfg.gidMin = parseGidMin
  922. case "gidmax":
  923. parseGidMax, err := convertGid(v)
  924. if err != nil {
  925. return nil, fmt.Errorf("invalid gidMax value %q for volume plugin %s", k, glusterfsPluginName)
  926. }
  927. if parseGidMax < absoluteGidMin {
  928. return nil, fmt.Errorf("gidMax must be >= %v", absoluteGidMin)
  929. }
  930. if parseGidMax > absoluteGidMax {
  931. return nil, fmt.Errorf("gidMax must be <= %v", absoluteGidMax)
  932. }
  933. cfg.gidMax = parseGidMax
  934. case "volumetype":
  935. parseVolumeType = v
  936. case "volumeoptions":
  937. if len(v) != 0 {
  938. parseVolumeOptions = v
  939. }
  940. case "volumenameprefix":
  941. if len(v) != 0 {
  942. parseVolumeNamePrefix = v
  943. }
  944. case "snapfactor":
  945. if len(v) != 0 {
  946. parseThinPoolSnapFactor = v
  947. }
  948. case "customepnameprefix":
  949. // If the string has > 'maxCustomEpNamePrefixLen' chars, the final endpoint name will
  950. // exceed the limitation of 63 chars, so fail if prefix is > 'maxCustomEpNamePrefixLen'
  951. // characters. This is only applicable for 'customepnameprefix' string and default ep name
  952. // string will always pass.
  953. if len(v) <= maxCustomEpNamePrefixLen {
  954. cfg.customEpNamePrefix = v
  955. } else {
  956. return nil, fmt.Errorf("'customepnameprefix' value should be < %d characters", maxCustomEpNamePrefixLen)
  957. }
  958. default:
  959. return nil, fmt.Errorf("invalid option %q for volume plugin %s", k, glusterfsPluginName)
  960. }
  961. }
  962. if len(cfg.url) == 0 {
  963. return nil, fmt.Errorf("StorageClass for provisioner %s must contain 'resturl' parameter", glusterfsPluginName)
  964. }
  965. if len(parseVolumeType) == 0 {
  966. cfg.volumeType = gapi.VolumeDurabilityInfo{Type: gapi.DurabilityReplicate, Replicate: gapi.ReplicaDurability{Replica: replicaCount}}
  967. } else {
  968. parseVolumeTypeInfo := dstrings.Split(parseVolumeType, ":")
  969. switch parseVolumeTypeInfo[0] {
  970. case "replicate":
  971. if len(parseVolumeTypeInfo) >= 2 {
  972. newReplicaCount, err := convertVolumeParam(parseVolumeTypeInfo[1])
  973. if err != nil {
  974. return nil, fmt.Errorf("error parsing volumeType %q: %s", parseVolumeTypeInfo[1], err)
  975. }
  976. cfg.volumeType = gapi.VolumeDurabilityInfo{Type: gapi.DurabilityReplicate, Replicate: gapi.ReplicaDurability{Replica: newReplicaCount}}
  977. } else {
  978. cfg.volumeType = gapi.VolumeDurabilityInfo{Type: gapi.DurabilityReplicate, Replicate: gapi.ReplicaDurability{Replica: replicaCount}}
  979. }
  980. case "disperse":
  981. if len(parseVolumeTypeInfo) >= 3 {
  982. newDisperseData, err := convertVolumeParam(parseVolumeTypeInfo[1])
  983. if err != nil {
  984. return nil, fmt.Errorf("error parsing volumeType %q: %s", parseVolumeTypeInfo[1], err)
  985. }
  986. newDisperseRedundancy, err := convertVolumeParam(parseVolumeTypeInfo[2])
  987. if err != nil {
  988. return nil, fmt.Errorf("error parsing volumeType %q: %s", parseVolumeTypeInfo[2], err)
  989. }
  990. cfg.volumeType = gapi.VolumeDurabilityInfo{Type: gapi.DurabilityEC, Disperse: gapi.DisperseDurability{Data: newDisperseData, Redundancy: newDisperseRedundancy}}
  991. } else {
  992. return nil, fmt.Errorf("StorageClass for provisioner %q must have data:redundancy count set for disperse volumes in storage class option '%s'", glusterfsPluginName, "volumetype")
  993. }
  994. case "none":
  995. cfg.volumeType = gapi.VolumeDurabilityInfo{Type: gapi.DurabilityDistributeOnly}
  996. default:
  997. return nil, fmt.Errorf("error parsing value for option 'volumetype' for volume plugin %s", glusterfsPluginName)
  998. }
  999. }
  1000. if !authEnabled {
  1001. cfg.user = ""
  1002. cfg.secretName = ""
  1003. cfg.secretNamespace = ""
  1004. cfg.userKey = ""
  1005. cfg.secretValue = ""
  1006. }
  1007. if len(cfg.secretName) != 0 || len(cfg.secretNamespace) != 0 {
  1008. // secretName + Namespace has precedence over userKey
  1009. if len(cfg.secretName) != 0 && len(cfg.secretNamespace) != 0 {
  1010. cfg.secretValue, err = parseSecret(cfg.secretNamespace, cfg.secretName, kubeClient)
  1011. if err != nil {
  1012. return nil, err
  1013. }
  1014. } else {
  1015. return nil, fmt.Errorf("StorageClass for provisioner %q must have secretNamespace and secretName either both set or both empty", glusterfsPluginName)
  1016. }
  1017. } else {
  1018. cfg.secretValue = cfg.userKey
  1019. }
  1020. if cfg.gidMin > cfg.gidMax {
  1021. return nil, fmt.Errorf("storageClass for provisioner %q must have gidMax value >= gidMin", glusterfsPluginName)
  1022. }
  1023. if len(parseVolumeOptions) != 0 {
  1024. volOptions := dstrings.Split(parseVolumeOptions, ",")
  1025. if len(volOptions) == 0 {
  1026. return nil, fmt.Errorf("storageClass for provisioner %q must have valid (for e.g., 'client.ssl on') volume option", glusterfsPluginName)
  1027. }
  1028. cfg.volumeOptions = volOptions
  1029. }
  1030. if len(parseVolumeNamePrefix) != 0 {
  1031. if dstrings.Contains(parseVolumeNamePrefix, "_") {
  1032. return nil, fmt.Errorf("storageclass parameter 'volumenameprefix' should not contain '_' in its value")
  1033. }
  1034. cfg.volumeNamePrefix = parseVolumeNamePrefix
  1035. }
  1036. if len(parseThinPoolSnapFactor) != 0 {
  1037. thinPoolSnapFactor, err := strconv.ParseFloat(parseThinPoolSnapFactor, 32)
  1038. if err != nil {
  1039. return nil, fmt.Errorf("failed to convert snapfactor %v to float: %v", parseThinPoolSnapFactor, err)
  1040. }
  1041. if thinPoolSnapFactor < 1.0 || thinPoolSnapFactor > 100.0 {
  1042. return nil, fmt.Errorf("invalid snapshot factor %v, the value must be between 1 to 100", thinPoolSnapFactor)
  1043. }
  1044. cfg.thinPoolSnapFactor = float32(thinPoolSnapFactor)
  1045. }
  1046. return &cfg, nil
  1047. }
  1048. // getVolumeID returns volumeID from the PV or volumename.
  1049. func getVolumeID(pv *v1.PersistentVolume, volumeName string) (string, error) {
  1050. volumeID := ""
  1051. // Get volID from pvspec if available, else fill it from volumename.
  1052. if pv != nil {
  1053. if pv.Annotations[heketiVolIDAnn] != "" {
  1054. volumeID = pv.Annotations[heketiVolIDAnn]
  1055. } else {
  1056. volumeID = dstrings.TrimPrefix(volumeName, volPrefix)
  1057. }
  1058. } else {
  1059. return volumeID, fmt.Errorf("provided PV spec is nil")
  1060. }
  1061. if volumeID == "" {
  1062. return volumeID, fmt.Errorf("volume ID is empty")
  1063. }
  1064. return volumeID, nil
  1065. }
  1066. func (plugin *glusterfsPlugin) ExpandVolumeDevice(spec *volume.Spec, newSize resource.Quantity, oldSize resource.Quantity) (resource.Quantity, error) {
  1067. pvSpec := spec.PersistentVolume.Spec
  1068. volumeName := pvSpec.Glusterfs.Path
  1069. klog.V(2).Infof("received request to expand volume %s", volumeName)
  1070. volumeID, err := getVolumeID(spec.PersistentVolume, volumeName)
  1071. if err != nil {
  1072. return oldSize, fmt.Errorf("failed to get volumeID for volume %s: %v", volumeName, err)
  1073. }
  1074. //Get details of StorageClass.
  1075. class, err := volutil.GetClassForVolume(plugin.host.GetKubeClient(), spec.PersistentVolume)
  1076. if err != nil {
  1077. return oldSize, err
  1078. }
  1079. cfg, err := parseClassParameters(class.Parameters, plugin.host.GetKubeClient())
  1080. if err != nil {
  1081. return oldSize, err
  1082. }
  1083. klog.V(4).Infof("expanding volume: %q", volumeID)
  1084. //Create REST server connection
  1085. cli := gcli.NewClient(cfg.url, cfg.user, cfg.secretValue)
  1086. if cli == nil {
  1087. klog.Errorf("failed to create glusterfs REST client")
  1088. return oldSize, fmt.Errorf("failed to create glusterfs REST client, REST server authentication failed")
  1089. }
  1090. // Find out delta size
  1091. expansionSize := resource.NewScaledQuantity((newSize.Value() - oldSize.Value()), 0)
  1092. expansionSizeGiB := int(volumehelpers.RoundUpToGiB(*expansionSize))
  1093. // Find out requested Size
  1094. requestGiB := volumehelpers.RoundUpToGiB(newSize)
  1095. //Check the existing volume size
  1096. currentVolumeInfo, err := cli.VolumeInfo(volumeID)
  1097. if err != nil {
  1098. klog.Errorf("error when fetching details of volume %s: %v", volumeName, err)
  1099. return oldSize, err
  1100. }
  1101. if int64(currentVolumeInfo.Size) >= requestGiB {
  1102. return newSize, nil
  1103. }
  1104. // Make volume expansion request
  1105. volumeExpandReq := &gapi.VolumeExpandRequest{Size: expansionSizeGiB}
  1106. // Expand the volume
  1107. volumeInfoRes, err := cli.VolumeExpand(volumeID, volumeExpandReq)
  1108. if err != nil {
  1109. klog.Errorf("failed to expand volume %s: %v", volumeName, err)
  1110. return oldSize, err
  1111. }
  1112. klog.V(2).Infof("volume %s expanded to new size %d successfully", volumeName, volumeInfoRes.Size)
  1113. newVolumeSize := resource.MustParse(fmt.Sprintf("%dGi", volumeInfoRes.Size))
  1114. return newVolumeSize, nil
  1115. }