Class: VagrantPlugins::VagrantHanewinNfs::WindowsService

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrant-hanewin-nfs/windows_service.rb

Overview

Class reprents a windows service and allows to control this service via the sc command

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ WindowsService

Returns a new instance of WindowsService.



9
10
11
12
13
14
# File 'lib/vagrant-hanewin-nfs/windows_service.rb', line 9

def initialize(name)
  @name = name
  @sc_cmd = "sc"
  @logger = Log4r::Logger.new("vagrant::hosts::windows")

end

Instance Method Details

#restartObject



53
54
55
56
# File 'lib/vagrant-hanewin-nfs/windows_service.rb', line 53

def restart
  stop
  start
end

#run_cmd(command) ⇒ Object

Run sc command



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
# File 'lib/vagrant-hanewin-nfs/windows_service.rb', line 17

def run_cmd(command)
  cmd = "#{@sc_cmd} #{command} \"#{@name}\""
  @logger.debug "WindowsServer run cmd #{cmd}"
  stdout, stderr, status = Open3.capture3(cmd)

  # Get allowed exit status
  if command == 'start'
    allowed_exitstatus = [0, 32]
  elsif command == 'stop'
    allowed_exitstatus = [0, 38]
  else
    allowed_exitstatus = [0]
  end

  # Check exitstatus
  if allowed_exitstatus.include? status.exitstatus
    return stdout
  elsif status.exitstatus == 5
    raise "Permission denied"
  elsif [36,103].include? status.exitstatus
    raise "Service #{@name} not found"
  else
    raise "Unknown return code #{status.exitstatus}: #{stdout}"    
  end
end

#startObject



43
44
45
46
# File 'lib/vagrant-hanewin-nfs/windows_service.rb', line 43

def start
  run_cmd('start')
  wait_for_status('RUNNING')
end

#statusObject



58
59
60
61
62
63
64
65
66
67
# File 'lib/vagrant-hanewin-nfs/windows_service.rb', line 58

def status
  output = run_cmd('query')
  # Match state
  status = /STATE[\s:]+\d+\s+([\S]+)/.match(output)
  if status.nil?
    return nil
  else
    return status[1]
  end
end

#stopObject



48
49
50
51
# File 'lib/vagrant-hanewin-nfs/windows_service.rb', line 48

def stop
  run_cmd('stop')
  wait_for_status('STOPPED')
end

#wait_for_status(state, sleep_duration = 0.1, max_tries = 20) ⇒ Object

Waits until service has desired state



70
71
72
73
74
75
76
77
78
79
# File 'lib/vagrant-hanewin-nfs/windows_service.rb', line 70

def wait_for_status(state,sleep_duration=0.1, max_tries=20)
  try = 0
  while status != state do
    try += 1
    sleep(sleep_duration)
    if try >= max_tries 
      raise "Error waiting for state '#{state}'"
    end
  end
end