File: nfs_datastore.rb

package info (click to toggle)
ruby-rbvmomi 1.8.2-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,756 kB
  • sloc: ruby: 5,590; sh: 36; makefile: 7
file content (95 lines) | stat: -rw-r--r-- 2,387 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/usr/bin/env ruby
require 'trollop'
require 'rbvmomi'
require 'rbvmomi/trollop'

VIM = RbVmomi::VIM
CMDS = %w(mount unmount)

opts = Trollop.options do
  banner <<-EOS
Mount/Unmount an NFS datastore from a cluster or single host system.

Usage:
    nfs_datastore.rb [options] resource mount nfs-hostname:/remote/path [name]
    nfs_datastore.rb [options] resource unmount nfs-hostname:/remote/path [name]

Commands: #{CMDS * ' '}

VIM connection options:
    EOS

    rbvmomi_connection_opts

    text <<-EOS

VM location options:
    EOS

    rbvmomi_datacenter_opt

    text <<-EOS

Other options:
  EOS

  stop_on CMDS
end

Trollop.die("must specify host") unless opts[:host]

cr_path = ARGV[0] or Trollop.die("no system name given")
cmd = ARGV[1] or Trollop.die("no command given")
abort "invalid command" unless CMDS.member? cmd
nfs_spec = ARGV[2] or Trollop.die("no nfs path given")
remoteHost, remotePath = nfs_spec.split(":")
localPath = ARGV[3] || remoteHost
mode = "readOnly" #hardcoded.

vim = VIM.connect opts
dc = vim.serviceInstance.find_datacenter(opts[:datacenter]) or abort "datacenter not found"
cr = dc.find_compute_resource(cr_path) || dc.hostFolder.children.find(cr_path).first
abort "compute resource not found" unless cr

case cr
when VIM::ClusterComputeResource
  hosts = cr.host
when VIM::ComputeResource
  hosts = [cr]
else
  abort "invalid resource"
end

hosts.each do |host|
  hds = host.configManager.datastoreSystem

  ds = hds.datastore.select {|ds|
    ds.info.respond_to?(:nas) and
    ds.info.name == localPath and
    ds.info.nas.remoteHost == remoteHost and
    ds.info.nas.remotePath == remotePath
  }.first

  case cmd
  when 'mount'
    if ds
      puts "already mounted on #{host.name} as #{ds.name}"
    else
      ds =
        hds.CreateNasDatastore(:spec => VIM.HostNasVolumeSpec(:remoteHost => remoteHost,
                                                              :remotePath => remotePath,
                                                              :localPath  => localPath,
                                                              :accessMode => mode))
      puts "mounted on #{host.name} as #{ds.name}"
    end
  when 'unmount'
    if ds
      hds.RemoveDatastore(:datastore => ds)
      puts "unmounted from #{host.name}"
    else
      puts "not mounted on #{host.name}"
    end
  else
    abort "invalid command"
  end
end