code
stringlengths
26
124k
docstring
stringlengths
23
125k
func_name
stringlengths
1
98
language
stringclasses
1 value
repo
stringlengths
5
53
path
stringlengths
7
151
url
stringlengths
50
211
license
stringclasses
7 values
def test raise AbstractMethodNotOverriddenError.new("PollCondition#test must be overridden in subclasses") end
Override this method in your Conditions (mandatory) Return true if the test passes (everything is ok) Return false otherwise
test
ruby
mojombo/god
lib/god/condition.rb
https://github.com/mojombo/god/blob/master/lib/god/condition.rb
MIT
def notify(message, time, priority, category, host) raise AbstractMethodNotOverriddenError.new("Contact#notify must be overridden in subclasses") end
Abstract Send the message to the external source +message+ is the message body returned from the condition +time+ is the Time at which the notification was made +priority+ is the arbitrary priority String +category+ is the arbitrary category String +host+ is the hostname of the server
notify
ruby
mojombo/god
lib/god/contact.rb
https://github.com/mojombo/god/blob/master/lib/god/contact.rb
MIT
def friendly_name super + " Contact '#{self.name}'" end
Construct the friendly name of this Contact, looks like: Contact FooBar
friendly_name
ruby
mojombo/god
lib/god/contact.rb
https://github.com/mojombo/god/blob/master/lib/god/contact.rb
MIT
def initialize(delay = 0) self.at = Time.now + delay end
Instantiate a new TimedEvent that will be triggered after the specified delay. delay - The optional Numeric number of seconds from now at which to trigger (default: 0).
initialize
ruby
mojombo/god
lib/god/driver.rb
https://github.com/mojombo/god/blob/master/lib/god/driver.rb
MIT
def due? Time.now >= self.at end
Is the current event due (current time >= event time)? Returns true if the event is due, false if not.
due?
ruby
mojombo/god
lib/god/driver.rb
https://github.com/mojombo/god/blob/master/lib/god/driver.rb
MIT
def initialize(delay, task, condition) super(delay) @task = task @condition = condition end
Initialize a new DriverEvent. delay - The Numeric delay for this event. task - The Task associated with this event. condition - The Condition associated with this event.
initialize
ruby
mojombo/god
lib/god/driver.rb
https://github.com/mojombo/god/blob/master/lib/god/driver.rb
MIT
def initialize(task, name, args) super(0) @task = task @name = name @args = args end
Initialize a new DriverOperation. task - The Task upon which to operate. name - The Symbol name of the method to call. args - The Array of arguments to send to the method.
initialize
ruby
mojombo/god
lib/god/driver.rb
https://github.com/mojombo/god/blob/master/lib/god/driver.rb
MIT
def handle_event @task.send(@name, *@args) end
Handle the operation that was issued asynchronously. Returns nothing.
handle_event
ruby
mojombo/god
lib/god/driver.rb
https://github.com/mojombo/god/blob/master/lib/god/driver.rb
MIT
def shutdown @shutdown = true @monitor.synchronize do @resource.broadcast end end
Wake any sleeping threads after setting the sentinel. Returns nothing.
shutdown
ruby
mojombo/god
lib/god/driver.rb
https://github.com/mojombo/god/blob/master/lib/god/driver.rb
MIT
def pop @monitor.synchronize do if @events.empty? raise ThreadError, "queue empty" if @shutdown @resource.wait else delay = @events.first.at - Time.now @resource.wait(delay) if delay > 0 end @events.shift end end
Wait until the queue has something due, pop it off the queue, and return it. Returns the popped event.
pop
ruby
mojombo/god
lib/god/driver.rb
https://github.com/mojombo/god/blob/master/lib/god/driver.rb
MIT
def push(event) @monitor.synchronize do @events << event @events.sort! # If we've sorted the events and found the one we're adding is at # the front, it will likely need to run before the next due date. @resource.signal if @events.first == event end end
Add an event to the queue, wake any waiters if what we added needs to happen sooner than the next pending event. Returns nothing.
push
ruby
mojombo/god
lib/god/driver.rb
https://github.com/mojombo/god/blob/master/lib/god/driver.rb
MIT
def initialize(task) @task = task @events = God::DriverEventQueue.new @thread = Thread.new do loop do begin @events.pop.handle_event rescue ThreadError => e # queue is empty break rescue Object => e message = format("Unhandled exception in driver loop - (%s): %s\n%s", e.class, e.message, e.backtrace.join("\n")) applog(nil, :fatal, message) end end end end
Instantiate a new Driver and start the scheduler loop to handle events. task - The Task this Driver belongs to.
initialize
ruby
mojombo/god
lib/god/driver.rb
https://github.com/mojombo/god/blob/master/lib/god/driver.rb
MIT
def in_driver_context? Thread.current == @thread end
Check if we're in the driver context. Returns true if in driver thread, false if not.
in_driver_context?
ruby
mojombo/god
lib/god/driver.rb
https://github.com/mojombo/god/blob/master/lib/god/driver.rb
MIT
def message(name, args = []) @events.push(DriverOperation.new(@task, name, args)) end
Queue an asynchronous message. name - The Symbol name of the operation. args - An optional Array of arguments. Returns nothing.
message
ruby
mojombo/god
lib/god/driver.rb
https://github.com/mojombo/god/blob/master/lib/god/driver.rb
MIT
def schedule(condition, delay = condition.interval) applog(nil, :debug, "driver schedule #{condition} in #{delay} seconds") @events.push(DriverEvent.new(delay, @task, condition)) end
Create and schedule a new DriverEvent. condition - The Condition. delay - The Numeric number of seconds to delay (default: interval defined in condition). Returns nothing.
schedule
ruby
mojombo/god
lib/god/driver.rb
https://github.com/mojombo/god/blob/master/lib/god/driver.rb
MIT
def log(watch, level, text) # initialize watch log if necessary self.logs[watch.name] ||= Timeline.new(God::LOG_BUFFER_SIZE_DEFAULT) if watch # push onto capture and timeline for the given watch if @capture || (watch && (Time.now - @spool < 2)) @mutex.synchronize do @templogio.truncate(0) @templogio.rewind @templog.send(level, text) message = @templogio.string.dup if @capture @capture.puts(message) else self.logs[watch.name] << [Time.now, message] end end end # send to regular logger self.send(level, text) # send to syslog SysLogger.log(level, text) if Logger.syslog end
Log a message +watch+ is the String name of the Watch (may be nil if not Watch is applicable) +level+ is the log level [:debug|:info|:warn|:error|:fatal] +text+ is the String message Returns nothing
log
ruby
mojombo/god
lib/god/logger.rb
https://github.com/mojombo/god/blob/master/lib/god/logger.rb
MIT
def watch_log_since(watch_name, since) # initialize watch log if necessary self.logs[watch_name] ||= Timeline.new(God::LOG_BUFFER_SIZE_DEFAULT) # get and join lines since given time @mutex.synchronize do @spool = Time.now self.logs[watch_name].select do |x| x.first > since end.map do |x| x[1] end.join end end
Get all log output for a given Watch since a certain Time. +watch_name+ is the String name of the Watch +since+ is the Time since which to fetch log lines Returns String
watch_log_since
ruby
mojombo/god
lib/god/logger.rb
https://github.com/mojombo/god/blob/master/lib/god/logger.rb
MIT
def start_capture @mutex.synchronize do @capture = StringIO.new end end
private Enable capturing of log Returns nothing
start_capture
ruby
mojombo/god
lib/god/logger.rb
https://github.com/mojombo/god/blob/master/lib/god/logger.rb
MIT
def finish_capture @mutex.synchronize do cap = @capture.string if @capture @capture = nil cap end end
Disable capturing of log and return what was captured since capturing was enabled with Logger#start_capture Returns String
finish_capture
ruby
mojombo/god
lib/god/logger.rb
https://github.com/mojombo/god/blob/master/lib/god/logger.rb
MIT
def initialize(watch, destination = nil) self.watch = watch self.destination = destination self.conditions = [] end
Initialize a new Metric. watch - The Watch. destination - The optional destination Hash in canonical hash form.
initialize
ruby
mojombo/god
lib/god/metric.rb
https://github.com/mojombo/god/blob/master/lib/god/metric.rb
MIT
def condition(kind) # Create the condition. begin c = Condition.generate(kind, self.watch) rescue NoSuchConditionError => e abort e.message end # Send to block so config can set attributes. yield(c) if block_given? # Prepare the condition. c.prepare # Test generic and specific validity. unless Condition.valid?(c) && c.valid? abort "Exiting on invalid condition" end # Inherit interval from watch if no poll condition specific interval was # set. if c.kind_of?(PollCondition) && !c.interval if self.watch.interval c.interval = self.watch.interval else abort "No interval set for Condition '#{c.class.name}' in Watch " + "'#{self.watch.name}', and no default Watch interval from " + "which to inherit." end end # Add the condition to the list. self.conditions << c end
Public: Instantiate the given Condition and pass it into the optional block. Attributes of the condition must be set in the config file. kind - The Symbol name of the condition. Returns nothing.
condition
ruby
mojombo/god
lib/god/metric.rb
https://github.com/mojombo/god/blob/master/lib/god/metric.rb
MIT
def enable self.conditions.each do |c| self.watch.attach(c) end end
Enable all of this Metric's conditions. Poll conditions will be scheduled and event/trigger conditions will be registered. Returns nothing.
enable
ruby
mojombo/god
lib/god/metric.rb
https://github.com/mojombo/god/blob/master/lib/god/metric.rb
MIT
def disable self.conditions.each do |c| self.watch.detach(c) end end
Disable all of this Metric's conditions. Poll conditions will be halted and event/trigger conditions will be deregistered. Returns nothing.
disable
ruby
mojombo/god
lib/god/metric.rb
https://github.com/mojombo/god/blob/master/lib/god/metric.rb
MIT
def pid contents = File.read(self.pid_file).strip rescue '' real_pid = contents =~ /^\d+$/ ? contents.to_i : nil if real_pid @pid = real_pid real_pid else @pid end end
Fetch the PID from pid_file. If the pid_file does not exist, then use the PID from the last time it was read. If it has never been read, then return nil. Returns Integer(pid) or nil
pid
ruby
mojombo/god
lib/god/process.rb
https://github.com/mojombo/god/blob/master/lib/god/process.rb
MIT
def signal(sig) sig = sig.to_i if sig.to_i != 0 applog(self, :info, "#{self.name} sending signal '#{sig}' to pid #{self.pid}") ::Process.kill(sig, self.pid) rescue nil end
Send the given signal to this process. Returns nothing
signal
ruby
mojombo/god
lib/god/process.rb
https://github.com/mojombo/god/blob/master/lib/god/process.rb
MIT
def spawn(command) fork do File.umask self.umask if self.umask uid_num = Etc.getpwnam(self.uid).uid if self.uid gid_num = Etc.getgrnam(self.gid).gid if self.gid gid_num = Etc.getpwnam(self.uid).gid if self.gid.nil? && self.uid ::Dir.chroot(self.chroot) if self.chroot ::Process.setsid ::Process.groups = [gid_num] if gid_num ::Process.initgroups(self.uid, gid_num) if self.uid && gid_num ::Process::Sys.setgid(gid_num) if gid_num ::Process::Sys.setuid(uid_num) if self.uid self.dir ||= '/' Dir.chdir self.dir $0 = command STDIN.reopen "/dev/null" if self.log_cmd STDOUT.reopen IO.popen(self.log_cmd, "a") else STDOUT.reopen file_in_chroot(self.log), "a" end if err_log_cmd STDERR.reopen IO.popen(err_log_cmd, "a") elsif err_log && (log_cmd || err_log != log) STDERR.reopen file_in_chroot(err_log), "a" else STDERR.reopen STDOUT end # close any other file descriptors 3.upto(256){|fd| IO::new(fd).close rescue nil} if self.env && self.env.is_a?(Hash) self.env.each do |(key, value)| ENV[key] = value.to_s end end exec command unless command.empty? end end
Fork/exec the given command, returns immediately +command+ is the String containing the shell command Returns nothing
spawn
ruby
mojombo/god
lib/god/process.rb
https://github.com/mojombo/god/blob/master/lib/god/process.rb
MIT
def ensure_stop applog(self, :warn, "#{self.name} ensuring stop...") unless self.pid applog(self, :warn, "#{self.name} stop called but pid is uknown") return end # Poll to see if it's dead @stop_timeout.times do begin ::Process.kill(0, self.pid) rescue Errno::ESRCH # It died. Good. return end sleep 1 end # last resort ::Process.kill('KILL', self.pid) rescue nil applog(self, :warn, "#{self.name} still alive after #{@stop_timeout}s; sent SIGKILL") end
Ensure that a stop command actually stops the process. Force kill if necessary. Returns nothing
ensure_stop
ruby
mojombo/god
lib/god/process.rb
https://github.com/mojombo/god/blob/master/lib/god/process.rb
MIT
def initialize(port = nil, user = nil, group = nil, perm = nil) @port = port @user = user @group = group @perm = perm start end
Create a new Server and star the DRb server +port+ is the port on which to start the DRb service (default nil)
initialize
ruby
mojombo/god
lib/god/socket.rb
https://github.com/mojombo/god/blob/master/lib/god/socket.rb
MIT
def method_missing(*args, &block) God.send(*args, &block) end
Forward API calls to God Returns whatever the forwarded call returns
method_missing
ruby
mojombo/god
lib/god/socket.rb
https://github.com/mojombo/god/blob/master/lib/god/socket.rb
MIT
def stop DRb.stop_service FileUtils.rm_f(self.socket_file) end
Stop the DRb server and delete the socket file Returns nothing
stop
ruby
mojombo/god
lib/god/socket.rb
https://github.com/mojombo/god/blob/master/lib/god/socket.rb
MIT
def start begin @drb ||= DRb.start_service(self.socket, self) applog(nil, :info, "Started on #{DRb.uri}") rescue Errno::EADDRINUSE applog(nil, :info, "Socket already in use") server = DRbObject.new(nil, self.socket) begin Timeout.timeout(5) do server.ping end abort "Socket #{self.socket} already in use by another instance of god" rescue StandardError, Timeout::Error applog(nil, :info, "Socket is stale, reopening") File.delete(self.socket_file) rescue nil @drb ||= DRb.start_service(self.socket, self) applog(nil, :info, "Started on #{DRb.uri}") end end if File.exists?(self.socket_file) if @user user_method = @user.is_a?(Integer) ? :getpwuid : :getpwnam uid = Etc.send(user_method, @user).uid gid = Etc.send(user_method, @user).gid end if @group group_method = @group.is_a?(Integer) ? :getgrgid : :getgrnam gid = Etc.send(group_method, @group).gid end File.chmod(Integer(@perm), socket_file) if @perm File.chown(uid, gid, socket_file) if uid or gid end end
Start the DRb server. Abort if there is already a running god instance on the socket. Returns nothing
start
ruby
mojombo/god
lib/god/socket.rb
https://github.com/mojombo/god/blob/master/lib/god/socket.rb
MIT
def prepare self.valid_states.each do |state| self.metrics[state] ||= [] end end
Initialize the metrics to an empty state. Returns nothing.
prepare
ruby
mojombo/god
lib/god/task.rb
https://github.com/mojombo/god/blob/master/lib/god/task.rb
MIT
def valid? valid = true # A name must be specified. if self.name.nil? valid = false applog(self, :error, "No name String was specified.") end # Valid states must be specified. if self.valid_states.nil? valid = false applog(self, :error, "No valid_states Array or Symbols was specified.") end # An initial state must be specified. if self.initial_state.nil? valid = false applog(self, :error, "No initial_state Symbol was specified.") end valid end
Verify that the minimum set of configuration requirements has been met. Returns true if valid, false if not.
valid?
ruby
mojombo/god
lib/god/task.rb
https://github.com/mojombo/god/blob/master/lib/god/task.rb
MIT
def canonical_hash_form(to) to.instance_of?(Symbol) ? {true => to} : to end
########################################################################## Advanced mode ########################################################################## Convert the given input into canonical hash form which looks like: { true => :state } or { true => :state, false => :otherstate } to - The Symbol or Hash destination. Returns the canonical Hash.
canonical_hash_form
ruby
mojombo/god
lib/god/task.rb
https://github.com/mojombo/god/blob/master/lib/god/task.rb
MIT
def transition(start_states, end_states) # Convert end_states into canonical hash form. canonical_end_states = canonical_hash_form(end_states) Array(start_states).each do |start_state| # Validate start state. unless self.valid_states.include?(start_state) abort "Invalid state :#{start_state}. Must be one of the symbols #{self.valid_states.map{|x| ":#{x}"}.join(', ')}" end # Create a new metric to hold the task, end states, and conditions. m = Metric.new(self, canonical_end_states) if block_given? # Let the config file define some conditions on the metric. yield(m) else # Add an :always condition if no block was given. m.condition(:always) do |c| c.what = true end end # Populate the condition -> metric directory. m.conditions.each do |c| self.directory[c] = m end # Record the metric. self.metrics[start_state] ||= [] self.metrics[start_state] << m end end
Public: Define a transition handler which consists of a set of conditions start_states - The Symbol or Array of Symbols start state(s). end_states - The Symbol or Hash end states. Yields the Metric for this transition. Returns nothing.
transition
ruby
mojombo/god
lib/god/task.rb
https://github.com/mojombo/god/blob/master/lib/god/task.rb
MIT
def lifecycle # Create a new metric to hold the task and conditions. m = Metric.new(self) # Let the config file define some conditions on the metric. yield(m) # Populate the condition -> metric directory. m.conditions.each do |c| self.directory[c] = m end # Record the metric. self.metrics[nil] << m end
Public: Define a lifecycle handler. Conditions that belong to a lifecycle are active as long as the process is being monitored. Returns nothing.
lifecycle
ruby
mojombo/god
lib/god/task.rb
https://github.com/mojombo/god/blob/master/lib/god/task.rb
MIT
def move(to_state) if !self.driver.in_driver_context? # Called from outside Driver. Send an async message to Driver. self.driver.message(:move, [to_state]) else # Called from within Driver. Record original info. orig_to_state = to_state from_state = self.state # Log. msg = "#{self.name} move '#{from_state}' to '#{to_state}'" applog(self, :info, msg) # Cleanup from current state. self.driver.clear_events self.metrics[from_state].each { |m| m.disable } if to_state == :unmonitored self.metrics[nil].each { |m| m.disable } end # Perform action. self.action(to_state) # Enable simple mode. if [:start, :restart].include?(to_state) && self.metrics[to_state].empty? to_state = :up end # Move to new state. self.metrics[to_state].each { |m| m.enable } # If no from state, enable lifecycle metric. if from_state == :unmonitored self.metrics[nil].each { |m| m.enable } end # Set state. self.state = to_state # Broadcast to interested TriggerConditions. Trigger.broadcast(self, :state_change, [from_state, orig_to_state]) # Log. msg = "#{self.name} moved '#{from_state}' to '#{to_state}'" applog(self, :info, msg) end self end
Move to the given state. to_state - The Symbol representing the state to move to. Returns this Task.
move
ruby
mojombo/god
lib/god/task.rb
https://github.com/mojombo/god/blob/master/lib/god/task.rb
MIT
def trigger(condition) self.driver.message(:handle_event, [condition]) end
Notify the Driver that an EventCondition has triggered. condition - The Condition. Returns nothing.
trigger
ruby
mojombo/god
lib/god/task.rb
https://github.com/mojombo/god/blob/master/lib/god/task.rb
MIT
def action(a, c = nil) if !self.driver.in_driver_context? # Called from outside Driver. Send an async message to Driver. self.driver.message(:action, [a, c]) else # Called from within Driver. if self.respond_to?(a) command = self.send(a) case command when String msg = "#{self.name} #{a}: #{command}" applog(self, :info, msg) system(command) when Proc msg = "#{self.name} #{a}: lambda" applog(self, :info, msg) command.call else raise NotImplementedError end end end end
Perform the given action. a - The Symbol action. c - The Condition. Returns this Task.
action
ruby
mojombo/god
lib/god/task.rb
https://github.com/mojombo/god/blob/master/lib/god/task.rb
MIT
def handle_poll(condition) # Lookup metric. metric = self.directory[condition] # Run the test. begin result = condition.test rescue Object => e cname = condition.class.to_s.split('::').last message = format("Unhandled exception in %s condition - (%s): %s\n%s", cname, e.class, e.message, e.backtrace.join("\n")) applog(self, :error, message) result = false end # Log. messages = self.log_line(self, metric, condition, result) # Notify. if result && condition.notify self.notify(condition, messages.last) end # After-condition. condition.after # Get the destination. dest = if result && condition.transition # Condition override. condition.transition else # Regular. metric.destination && metric.destination[result] end # Transition or reschedule. if dest # Transition. begin self.move(dest) rescue EventRegistrationFailedError msg = self.name + ' Event registration failed, moving back to previous state' applog(self, :info, msg) dest = self.state retry end else # Reschedule. self.driver.schedule(condition) end end
########################################################################## Handlers ########################################################################## Evaluate and handle the given poll condition. Handles logging notifications, and moving to the new state if necessary. condition - The Condition to handle. Returns nothing.
handle_poll
ruby
mojombo/god
lib/god/task.rb
https://github.com/mojombo/god/blob/master/lib/god/task.rb
MIT
def handle_event(condition) # Lookup metric. metric = self.directory[condition] # Log. messages = self.log_line(self, metric, condition, true) # Notify. if condition.notify self.notify(condition, messages.last) end # Get the destination. dest = if condition.transition # Condition override. condition.transition else # Regular. metric.destination && metric.destination[true] end if dest self.move(dest) end end
Asynchronously evaluate and handle the given event condition. Handles logging notifications, and moving to the new state if necessary. condition - The Condition to handle. Returns nothing.
handle_event
ruby
mojombo/god
lib/god/task.rb
https://github.com/mojombo/god/blob/master/lib/god/task.rb
MIT
def trigger?(metric, result) metric.destination && metric.destination[result] end
Determine whether a trigger happened. metric - The Metric. result - The Boolean result from the condition's test. Returns Boolean
trigger?
ruby
mojombo/god
lib/god/task.rb
https://github.com/mojombo/god/blob/master/lib/god/task.rb
MIT
def log_line(watch, metric, condition, result) status = if self.trigger?(metric, result) "[trigger]" else "[ok]" end messages = [] # Log info if available. if condition.info Array(condition.info).each do |condition_info| messages << "#{watch.name} #{status} #{condition_info} (#{condition.base_name})" applog(watch, :info, messages.last) end else messages << "#{watch.name} #{status} (#{condition.base_name})" applog(watch, :info, messages.last) end # Log. debug_message = watch.name + ' ' + condition.base_name + " [#{result}] " + self.dest_desc(metric, condition) applog(watch, :debug, debug_message) messages end
Log info about the condition and return the list of messages logged. watch - The Watch. metric - The Metric. condition - The Condition. result - The Boolean result of the condition test evaluation. Returns the Array of String messages.
log_line
ruby
mojombo/god
lib/god/task.rb
https://github.com/mojombo/god/blob/master/lib/god/task.rb
MIT
def dest_desc(metric, condition) if condition.transition {true => condition.transition}.inspect else if metric.destination metric.destination.inspect else 'none' end end end
Format the destination specification for use in debug logging. metric - The Metric. condition - The Condition. Returns the formatted String.
dest_desc
ruby
mojombo/god
lib/god/task.rb
https://github.com/mojombo/god/blob/master/lib/god/task.rb
MIT
def notify(condition, message) spec = Contact.normalize(condition.notify) unmatched = [] # Resolve contacts. resolved_contacts = spec[:contacts].inject([]) do |acc, contact_name_or_group| cons = Array(God.contacts[contact_name_or_group] || God.contact_groups[contact_name_or_group]) unmatched << contact_name_or_group if cons.empty? acc += cons acc end # Warn about unmatched contacts. unless unmatched.empty? msg = "#{condition.watch.name} no matching contacts for '#{unmatched.join(", ")}'" applog(condition.watch, :warn, msg) end # Notify each contact. resolved_contacts.each do |c| host = `hostname`.chomp rescue 'none' begin c.notify(message, Time.now, spec[:priority], spec[:category], host) msg = "#{condition.watch.name} #{c.info ? c.info : "notification sent for contact: #{c.name}"} (#{c.base_name})" applog(condition.watch, :info, msg % []) rescue Exception => e applog(condition.watch, :error, "#{e.message} #{e.backtrace}") msg = "#{condition.watch.name} Failed to deliver notification for contact: #{c.name} (#{c.base_name})" applog(condition.watch, :error, msg % []) end end end
Notify all recipients of the given condition with the specified message. condition - The Condition. message - The String message to send. Returns nothing.
notify
ruby
mojombo/god
lib/god/task.rb
https://github.com/mojombo/god/blob/master/lib/god/task.rb
MIT
def initialize(max_size) super() @max_size = max_size end
Instantiate a new Timeline +max_size+ is the maximum size to which the timeline should grow Returns Timeline
initialize
ruby
mojombo/god
lib/god/timeline.rb
https://github.com/mojombo/god/blob/master/lib/god/timeline.rb
MIT
def push(val) self.concat([val]) shift if size > @max_size end
Push a value onto the Timeline +val+ is the value to push Returns Timeline
push
ruby
mojombo/god
lib/god/timeline.rb
https://github.com/mojombo/god/blob/master/lib/god/timeline.rb
MIT
def valid? super && @process.valid? end
Is this Watch valid? Returns true if the Watch is valid, false if not.
valid?
ruby
mojombo/god
lib/god/watch.rb
https://github.com/mojombo/god/blob/master/lib/god/watch.rb
MIT
def behavior(kind) # Create the behavior. begin b = Behavior.generate(kind, self) rescue NoSuchBehaviorError => e abort e.message end # Send to block so config can set attributes. yield(b) if block_given? # Abort if the Behavior is invalid, the Behavior will have printed # out its own error messages by now. abort unless b.valid? self.behaviors << b end
########################################################################## Behavior ########################################################################## Public: Add a behavior to this Watch. See lib/god/behavior.rb. kind - The Symbol name of the Behavior to add. Yields the newly instantiated Behavior. Returns nothing.
behavior
ruby
mojombo/god
lib/god/watch.rb
https://github.com/mojombo/god/blob/master/lib/god/watch.rb
MIT
def keepalive(options = {}) if God::EventHandler.loaded? self.transition(:init, { true => :up, false => :start }) do |on| on.condition(:process_running) do |c| c.interval = options[:interval] || DEFAULT_KEEPALIVE_INTERVAL c.running = true end end self.transition([:start, :restart], :up) do |on| on.condition(:process_running) do |c| c.interval = options[:interval] || DEFAULT_KEEPALIVE_INTERVAL c.running = true end end self.transition(:up, :start) do |on| on.condition(:process_exits) end else self.start_if do |start| start.condition(:process_running) do |c| c.interval = options[:interval] || DEFAULT_KEEPALIVE_INTERVAL c.running = false end end end self.restart_if do |restart| if options[:memory_max] restart.condition(:memory_usage) do |c| c.interval = options[:interval] || DEFAULT_KEEPALIVE_INTERVAL c.above = options[:memory_max] c.times = options[:memory_times] || DEFAULT_KEEPALIVE_MEMORY_TIMES end end if options[:cpu_max] restart.condition(:cpu_usage) do |c| c.interval = options[:interval] || DEFAULT_KEEPALIVE_INTERVAL c.above = options[:cpu_max] c.times = options[:cpu_times] || DEFAULT_KEEPALIVE_CPU_TIMES end end end end
Public: A set of conditions for easily getting started with simple watch scenarios. Keepalive is intended for use by beginners or on processes that do not need very sophisticated monitoring. If events are enabled, it will use the :process_exit event to determine if a process fails. Otherwise it will use the :process_running poll. options - The option Hash. Possible values are: :interval - The Integer number of seconds on which to poll for process status. Affects CPU, memory, and :process_running conditions (if used). Default: 5.seconds. :memory_max - The Integer memory max. A bare integer means kilobytes. You may use Numeric.kilobytes, Numeric#megabytes, and Numeric#gigabytes to makes things more clear. :memory_times - If :memory_max is set, :memory_times can be set to either an Integer or a 2 element Integer Array to specify the number of times the memory condition must fail. Examples: 3 (three times), [3, 5] (three out of any five checks). Default: [3, 5]. :cpu_max - The Integer CPU percentage max. Range is 0 to 100. You may use the Numberic#percent sugar to clarify e.g. 50.percent. :cpu_times - If :cpu_max is set, :cpu_times can be set to either an Integer or a 2 element Integer Array to specify the number of times the memory condition must fail. Examples: 3 (three times), [3, 5] (three out of any five checks). Default: [3, 5].
keepalive
ruby
mojombo/god
lib/god/watch.rb
https://github.com/mojombo/god/blob/master/lib/god/watch.rb
MIT
def start_if self.transition(:up, :start) do |on| yield(on) end end
########################################################################## Simple mode ########################################################################## Public: Start the process if any of the given conditions are triggered. Yields the Metric upon which conditions can be added. Returns nothing.
start_if
ruby
mojombo/god
lib/god/watch.rb
https://github.com/mojombo/god/blob/master/lib/god/watch.rb
MIT
def restart_if self.transition(:up, :restart) do |on| yield(on) end end
Public: Restart the process if any of the given conditions are triggered. Yields the Metric upon which conditions can be added. Returns nothing.
restart_if
ruby
mojombo/god
lib/god/watch.rb
https://github.com/mojombo/god/blob/master/lib/god/watch.rb
MIT
def stop_if self.transition(:up, :stop) do |on| yield(on) end end
Public: Stop the process if any of the given conditions are triggered. Yields the Metric upon which conditions can be added. Returns nothing.
stop_if
ruby
mojombo/god
lib/god/watch.rb
https://github.com/mojombo/god/blob/master/lib/god/watch.rb
MIT
def monitor if !self.metrics[:init].empty? self.move(:init) else self.move(:up) end end
########################################################################## Lifecycle ########################################################################## Enable monitoring. Start at the first available of the init or up states. Returns nothing.
monitor
ruby
mojombo/god
lib/god/watch.rb
https://github.com/mojombo/god/blob/master/lib/god/watch.rb
MIT
def action(a, c = nil) if !self.driver.in_driver_context? # Called from outside Driver. Send an async message to Driver. self.driver.message(:action, [a, c]) else # Called from within Driver. case a when :start call_action(c, :start) sleep(self.start_grace + self.grace) when :restart if self.restart call_action(c, :restart) else action(:stop, c) action(:start, c) end sleep(self.restart_grace + self.grace) when :stop call_action(c, :stop) sleep(self.stop_grace + self.grace) end end self end
########################################################################## Actions ########################################################################## Perform an action. a - The Symbol action to perform. One of :start, :restart, :stop. c - The Condition. Returns this Watch.
action
ruby
mojombo/god
lib/god/watch.rb
https://github.com/mojombo/god/blob/master/lib/god/watch.rb
MIT
def call_action(condition, action) # Before. before_items = self.behaviors before_items += [condition] if condition before_items.each do |b| info = b.send("before_#{action}") if info msg = "#{self.name} before_#{action}: #{info} (#{b.base_name})" applog(self, :info, msg) end end # Log. if self.send(action) msg = "#{self.name} #{action}: #{self.send(action).to_s}" applog(self, :info, msg) end # Execute. @process.call_action(action) # After. after_items = self.behaviors after_items += [condition] if condition after_items.each do |b| info = b.send("after_#{action}") if info msg = "#{self.name} after_#{action}: #{info} (#{b.base_name})" applog(self, :info, msg) end end end
Perform the specifics of the action. condition - The Condition. action - The Symbol action. Returns nothing.
call_action
ruby
mojombo/god
lib/god/watch.rb
https://github.com/mojombo/god/blob/master/lib/god/watch.rb
MIT
def unregister! God.registry.remove(@process) super end
Unregister the Process in the global process registry. Returns nothing.
unregister!
ruby
mojombo/god
lib/god/watch.rb
https://github.com/mojombo/god/blob/master/lib/god/watch.rb
MIT
def exists? !!::Process.kill(0, @pid) rescue false end
Return true if this process is running, false otherwise
exists?
ruby
mojombo/god
lib/god/system/process.rb
https://github.com/mojombo/god/blob/master/lib/god/system/process.rb
MIT
def percent_cpu stats = stat total_time = stats[:utime].to_i + stats[:stime].to_i # in jiffies seconds = uptime - stats[:starttime].to_i / @@hertz if seconds == 0 0 else ((total_time * 1000 / @@hertz) / seconds) / 10 end rescue # This shouldn't fail is there's an error (or proc doesn't exist) 0 end
TODO: Change this to calculate the wma instead
percent_cpu
ruby
mojombo/god
lib/god/system/slash_proc_poller.rb
https://github.com/mojombo/god/blob/master/lib/god/system/slash_proc_poller.rb
MIT
def test_stop_all_with_non_killing_signal_long_timeout with_god_cleanup do God.start God.watch do |w| w.name = 'long_timeout' w.stop_signal = 'USR1' w.stop_timeout = ::God::STOP_TIMEOUT_DEFAULT + 1 w.start = File.join(GOD_ROOT, *%w[test configs usr1_trapper.rb]) end God.watches['long_timeout'].action(:start) sleep 2 assert_equal true, God.watches['long_timeout'].alive? God.stop_all assert_watch_running('long_timeout') end end
default 10s timeout will expire before SIGKILL sent
test_stop_all_with_non_killing_signal_long_timeout
ruby
mojombo/god
test/test_god_system.rb
https://github.com/mojombo/god/blob/master/test/test_god_system.rb
MIT
def test_stop_all_with_non_killing_signal_short_timeout with_god_cleanup do God.start God.watch do |w| w.name = 'short_timeout' w.stop_signal = 'USR1' w.stop_timeout = ::God::STOP_TIMEOUT_DEFAULT - 1 w.start = File.join(GOD_ROOT, *%w[test configs usr1_trapper.rb]) end God.watches['short_timeout'].action(:start) sleep 2 assert_equal true, God.watches['short_timeout'].alive? God.stop_all assert_equal false, God.watches.any? { |name, w| w.alive? } end end
use short timeout to send SIGKILL before 10s timeout
test_stop_all_with_non_killing_signal_short_timeout
ruby
mojombo/god
test/test_god_system.rb
https://github.com/mojombo/god/blob/master/test/test_god_system.rb
MIT
def test_stop_all_with_many_watches with_god_cleanup do God.start 20.times do |i| God.watch do |w| w.name = "many_watches_#{i}" w.start = File.join(GOD_ROOT, *%w[test configs complex simple_server.rb]) end God.watches["many_watches_#{i}"].action(:start) end while true do all_running = God.watches.select{ |name, w| name =~ /many_watches_/ }.all?{ |name, w| w.alive? } size = God.watches.size break if all_running && size >= 20 sleep 2 end God.stop_all assert_equal false, God.watches.any? { |name, w| w.alive? } end end
should be able to stop many simple watches within default timeout
test_stop_all_with_many_watches
ruby
mojombo/god
test/test_god_system.rb
https://github.com/mojombo/god/blob/master/test/test_god_system.rb
MIT
def test_stop_all_with_many_watches_short_timeout with_god_cleanup do God.start God.terminate_timeout = 1 100.times do |i| God.watch do |w| w.name = "tons_of_watches_#{i}" w.start = File.join(GOD_ROOT, *%w[test configs complex simple_server.rb]) w.keepalive end God.watches["tons_of_watches_#{i}"].action(:start) end while true do all_running = God.watches.select{ |name, w| name =~ /tons_of_watches_/ }.all?{ |name, w| w.alive? } size = God.watches.size break if all_running && size >= 100 sleep 2 end God.stop_all assert_equal false, God.watches.any? { |name, w| w.alive? } end end
should be able to stop many simple watches within short timeout
test_stop_all_with_many_watches_short_timeout
ruby
mojombo/god
test/test_god_system.rb
https://github.com/mojombo/god/blob/master/test/test_god_system.rb
MIT
def test_condition_should_abort_if_not_subclass_of_poll_or_event metric = Metric.new(stub(:name => 'foo', :interval => 10), nil) assert_abort do metric.condition(:fake_condition) { |c| } end end
This doesn't currently work: def test_condition_should_allow_generation_of_subclasses_of_poll_or_event metric = Metric.new(stub(:name => 'foo', :interval => 10), nil) assert_nothing_raised do metric.condition(:fake_poll_condition) metric.condition(:fake_event_condition) end end
test_condition_should_abort_if_not_subclass_of_poll_or_event
ruby
mojombo/god
test/test_metric.rb
https://github.com/mojombo/god/blob/master/test/test_metric.rb
MIT
def exec(*args) raise "You forgot to stub exec" end
def fork raise "You forgot to stub fork" end
exec
ruby
mojombo/god
test/test_process.rb
https://github.com/mojombo/god/blob/master/test/test_process.rb
MIT
def test_call_action_with_string_should_call_system @p.start = "do something" @p.expects(:fork) Process.expects(:waitpid2).returns([123, 0]) @p.call_action(:start) end
call_action These actually excercise call_action in the back at this point - Kev
test_call_action_with_string_should_call_system
ruby
mojombo/god
test/test_process.rb
https://github.com/mojombo/god/blob/master/test/test_process.rb
MIT
def regexp(options = {}) options = parse_options(options) case options[:mode] when :loose loose_regexp(options) when :rfc rfc_regexp(options) when :strict options[:require_fqdn] = true strict_regexp(options) else fail EmailValidator::Error, "Validation mode '#{options[:mode]}' is not supported by EmailValidator" end end
Refs: https://tools.ietf.org/html/rfc2822 : 3.2. Lexical Tokens, 3.4.1. Addr-spec specification https://tools.ietf.org/html/rfc5321 : 4.1.2. Command Argument Syntax
regexp
ruby
K-and-R/email_validator
lib/email_validator.rb
https://github.com/K-and-R/email_validator/blob/master/lib/email_validator.rb
MIT
def edit @image_core = ImageCore.find(params[:id]) @image_core.image_tags.build if @image_core.image_tags.empty? end
GET /image_cores/new def new @image_core = ImageCore.new end GET /image_cores/1/edit
edit
ruby
neonwatty/meme-search
meme_search_pro/meme_search_app/app/controllers/image_cores_controller.rb
https://github.com/neonwatty/meme-search/blob/master/meme_search_pro/meme_search_app/app/controllers/image_cores_controller.rb
Apache-2.0
def update image_tags = @image_core.image_tags.map { |tag| tag.id } image_tags.each do |tag| ImageTag.destroy(tag) end # check if description has changed to update status update_params = image_update_params update_description_embeddings = false if @image_core.description != update_params[:description] update_description_embeddings = true end respond_to do |format| if @image_core.update(update_params) # recompute embeddings if description has changed if update_description_embeddings @image_core.refresh_description_embeddings end flash[:notice] = "Meme succesfully updated!" format.html { redirect_to @image_core } else flash[:alert] = @image_core.errors.full_messages[0] format.html { render :edit, status: :unprocessable_entity } end end end
POST /image_cores or /image_cores.json def create @image_core = ImageCore.new(image_core_params) respond_to do |format| if @image_core.save flash[:notice] = "Image data was successfully created." format.html { redirect_to @image_core } else flash[:alert] = @image_core.errors.full_messages[0] format.html { render :new, status: :unprocessable_entity } end end end PATCH/PUT /image_cores/1 or /image_cores/1.json
update
ruby
neonwatty/meme-search
meme_search_pro/meme_search_app/app/controllers/image_cores_controller.rb
https://github.com/neonwatty/meme-search/blob/master/meme_search_pro/meme_search_app/app/controllers/image_cores_controller.rb
Apache-2.0
def set_image_core @image_core = ImageCore.find(params[:id]) end
Use callbacks to share common setup or constraints between actions.
set_image_core
ruby
neonwatty/meme-search
meme_search_pro/meme_search_app/app/controllers/image_cores_controller.rb
https://github.com/neonwatty/meme-search/blob/master/meme_search_pro/meme_search_app/app/controllers/image_cores_controller.rb
Apache-2.0
def set_image_embedding @image_embedding = ImageEmbedding.find(params[:id]) end
Use callbacks to share common setup or constraints between actions.
set_image_embedding
ruby
neonwatty/meme-search
meme_search_pro/meme_search_app/app/controllers/image_embeddings_controller.rb
https://github.com/neonwatty/meme-search/blob/master/meme_search_pro/meme_search_app/app/controllers/image_embeddings_controller.rb
Apache-2.0
def image_embedding_params params.fetch(:image_embedding, {}) end
Only allow a list of trusted parameters through.
image_embedding_params
ruby
neonwatty/meme-search
meme_search_pro/meme_search_app/app/controllers/image_embeddings_controller.rb
https://github.com/neonwatty/meme-search/blob/master/meme_search_pro/meme_search_app/app/controllers/image_embeddings_controller.rb
Apache-2.0
def set_image_tag @image_tag = ImageTag.find(params[:id]) end
Use callbacks to share common setup or constraints between actions.
set_image_tag
ruby
neonwatty/meme-search
meme_search_pro/meme_search_app/app/controllers/image_tags_controller.rb
https://github.com/neonwatty/meme-search/blob/master/meme_search_pro/meme_search_app/app/controllers/image_tags_controller.rb
Apache-2.0
def image_tag_params params.fetch(:image_tag, {}) end
Only allow a list of trusted parameters through.
image_tag_params
ruby
neonwatty/meme-search
meme_search_pro/meme_search_app/app/controllers/image_tags_controller.rb
https://github.com/neonwatty/meme-search/blob/master/meme_search_pro/meme_search_app/app/controllers/image_tags_controller.rb
Apache-2.0
def set_image_path @image_path = ImagePath.find(params[:id]) end
Use callbacks to share common setup or constraints between actions.
set_image_path
ruby
neonwatty/meme-search
meme_search_pro/meme_search_app/app/controllers/settings/image_paths_controller.rb
https://github.com/neonwatty/meme-search/blob/master/meme_search_pro/meme_search_app/app/controllers/settings/image_paths_controller.rb
Apache-2.0
def set_image_to_text @image_to_text = ImageToText.find(params[:id]) end
Use callbacks to share common setup or constraints between actions.
set_image_to_text
ruby
neonwatty/meme-search
meme_search_pro/meme_search_app/app/controllers/settings/image_to_texts_controller.rb
https://github.com/neonwatty/meme-search/blob/master/meme_search_pro/meme_search_app/app/controllers/settings/image_to_texts_controller.rb
Apache-2.0
def image_to_text_params params.require(:image_to_text).permit(:name, :description) end
Only allow a list of trusted parameters through.
image_to_text_params
ruby
neonwatty/meme-search
meme_search_pro/meme_search_app/app/controllers/settings/image_to_texts_controller.rb
https://github.com/neonwatty/meme-search/blob/master/meme_search_pro/meme_search_app/app/controllers/settings/image_to_texts_controller.rb
Apache-2.0
def set_tag_name @tag_name = TagName.find(params[:id]) end
Use callbacks to share common setup or constraints between actions.
set_tag_name
ruby
neonwatty/meme-search
meme_search_pro/meme_search_app/app/controllers/settings/tag_names_controller.rb
https://github.com/neonwatty/meme-search/blob/master/meme_search_pro/meme_search_app/app/controllers/settings/tag_names_controller.rb
Apache-2.0
def tag_name_params params.require(:tag_name).permit(:name, :color) end
Only allow a list of trusted parameters through.
tag_name_params
ruby
neonwatty/meme-search
meme_search_pro/meme_search_app/app/controllers/settings/tag_names_controller.rb
https://github.com/neonwatty/meme-search/blob/master/meme_search_pro/meme_search_app/app/controllers/settings/tag_names_controller.rb
Apache-2.0
def start with_pid_lock do |file| # Check if the daemon is already started... if running?(file) @ui.info "[landrush] DNS server already running with pid #{read_pid(file)}" unless @ui.nil? return end # On a machine with just Vagrant installed there might be no other Ruby except the # one bundled with Vagrant. Let's make sure the embedded bin directory containing # the Ruby executable is added to the PATH. Landrush::Util::Path.ensure_ruby_on_path ruby_bin = Landrush::Util::Path.embedded_vagrant_ruby.nil? ? 'ruby' : Landrush::Util::Path.embedded_vagrant_ruby start_server_script = Pathname(__dir__).join('start_server.rb').to_s @ui.detail("[landrush] starting DNS server: '#{ruby_bin} #{start_server_script} #{port} #{working_dir} #{gems_dir}'") unless @ui.nil? if Vagrant::Util::Platform.windows? # Need to handle Windows differently. Kernel.spawn fails to work, if # the shell creating the process is closed. # See https://github.com/vagrant-landrush/landrush/issues/199 # # Note to the Future: Windows does not have a # file handle inheritance issue like Linux and Mac (see: # https://github.com/vagrant-landrush/landrush/issues/249) # # On windows, if no filehandle is passed then no files get # inherited by default, but if any filehandle is passed to # a spawned process then all files that are # set as inheritable will get inherited. In another project this # created a problem (see: https://github.com/dustymabe/vagrant-sshfs/issues/41). # # Today we don't pass any filehandles, so it isn't a problem. # Future self, make sure this doesn't become a problem. info = Process.create(command_line: "#{ruby_bin} #{start_server_script} #{port} #{working_dir} #{gems_dir}", creation_flags: Process::DETACHED_PROCESS, process_inherit: false, thread_inherit: true, cwd: working_dir.to_path) pid = info.process_id else # Fix https://github.com/vagrant-landrush/landrush/issues/249) # by turning of filehandle inheritance with :close_others => true # and by explicitly closing STDIN, STDOUT, and STDERR pid = spawn(ruby_bin, start_server_script, port.to_s, working_dir.to_s, gems_dir.to_s, in: :close, out: :close, err: :close, close_others: true, chdir: working_dir.to_path, pgroup: true) Process.detach pid end write_pid(pid, file) # As of Vagrant 1.8.6 this additional sleep is needed, otherwise the child process dies!? sleep 1 end end
Used to start the Landrush DNS server as a child process using ChildProcess gem
start
ruby
vagrant-landrush/landrush
lib/landrush/server.rb
https://github.com/vagrant-landrush/landrush/blob/master/lib/landrush/server.rb
MIT
def private_network_ips # machine.config.vm.networks is an array of two elements. The first containing the type as symbol, the second is a # hash containing other config data which varies between types machine.config.vm.networks.select { |network| network[0] == :private_network && !network[1][:ip].nil? } .map { |network| network[1][:ip] } end
@return [Array<String] IPv4 addresses of all private networks
private_network_ips
ruby
vagrant-landrush/landrush
lib/landrush/action/setup.rb
https://github.com/vagrant-landrush/landrush/blob/master/lib/landrush/action/setup.rb
MIT
def admin_mode? `reg query HKU\\S-1-5-19 2>&1` $CHILD_STATUS.exitstatus.zero? end
If this registry query succeeds we assume we have Admin rights http://stackoverflow.com/questions/8268154/run-ruby-script-in-elevated-mode/27954953 https://stackoverflow.com/a/2400/1040571 "[...] $?, which is the same as $CHILD_STATUS, accesses the status of the last system executed command if you use the backticks, system() or %x{} [...]"
admin_mode?
ruby
vagrant-landrush/landrush
lib/landrush/cap/host/windows/configure_visibility_on_host.rb
https://github.com/vagrant-landrush/landrush/blob/master/lib/landrush/cap/host/windows/configure_visibility_on_host.rb
MIT
def get_network_guid(address) address = IPAddr.new(address.to_s) interfaces do |interface_guid| interface = open_interface("#{INTERFACES}\\#{interface_guid}") if_ip, if_mask = interface_address(interface) next if if_ip.nil? if_net = IPAddr.new("#{if_ip}/#{if_mask}") return interface_guid if if_net.include?(address) end rescue StandardError nil end
Given an IP determines the network adapter guid, if any. We can't use netsh due to its output being locale dependant. Using Windows registry we achieve the same result of netsh in whatever language Windows is.
get_network_guid
ruby
vagrant-landrush/landrush
lib/landrush/cap/host/windows/configure_visibility_on_host.rb
https://github.com/vagrant-landrush/landrush/blob/master/lib/landrush/cap/host/windows/configure_visibility_on_host.rb
MIT
def interfaces Win32::Registry::HKEY_LOCAL_MACHINE.open(INTERFACES) do |interfaces| interfaces.each_key do |guid, _| yield guid end end end
Fetch interfaces from registry This is a separate method to make testing easier
interfaces
ruby
vagrant-landrush/landrush
lib/landrush/cap/host/windows/configure_visibility_on_host.rb
https://github.com/vagrant-landrush/landrush/blob/master/lib/landrush/cap/host/windows/configure_visibility_on_host.rb
MIT
def interface_address(interface) dhcp_enabled = interface.read('EnableDHCP')[1] if dhcp_enabled if_ip = interface.read('DhcpIPAddress')[1] if_mask = interface.read('DhcpSubnetMask')[1] else if_ip = interface.read('IPAddress')[1] if_mask = interface.read('SubnetMask')[1] end if if_ip.is_a? Array if_ip = if_ip[0] end if if_mask.is_a? Array if_mask = if_mask[0] end if if_ip == '0.0.0.0' if_ip, if_mask = nil end [if_ip, if_mask] rescue StandardError [nil, nil] end
Fetches IP/mask info from registry from a given registry entry This is a separate method to make testing easier The registry may look like this: {46666082-84ff-4888-8d75-31079e325934}: EnableDHCP => 1 DhcpIPAddress => 172.29.5.24 DhcpSubnetMask => 255.255.254.0 {61e509a1-cffa-4b7f-8e7f-5a6991deba2b}: EnableDHCP => 0 IPAddress => ["192.168.56.1"] SubnetMask => ["255.255.255.0"] {6c902ac7-4845-46d4-843e-2707e2270b0d}: EnableDHCP => 0 IPAddress => ["0.0.0.0"] SubnetMask => ["0.0.0.0"] {6d2f3579-bc95-4a18-bed5-fb8b87b8673b}: EnableDHCP => 0 If a given interface does not have an address, win32/registry will trow an Win32::Registry::Error (which inherits directly from StandardError).
interface_address
ruby
vagrant-landrush/landrush
lib/landrush/cap/host/windows/configure_visibility_on_host.rb
https://github.com/vagrant-landrush/landrush/blob/master/lib/landrush/cap/host/windows/configure_visibility_on_host.rb
MIT
def ensure_prerequisites return false unless command_found('netsh') return false unless command_found('net') return false unless command_found('reg') unless wired_autoconfig_service_running? info('starting \'Wired AutoConfig\' service') if admin_mode? `net start dot3svc` else require 'win32ole' shell = WIN32OLE.new('Shell.Application') shell.ShellExecute('net', 'start dot3svc', nil, 'runas', 1) end service_has_started = Landrush::Util::Retry.retry(tries: 5, sleep: 1) do wired_autoconfig_service_running? end unless service_has_started info('Unable to start \'Wired AutoConfig\' service. Unable to configure DNS on host. Try manual configuration.') return false end info('\'Wired AutoConfig\' service has started.') end true end
Checks that all required tools are on the PATH and that the Wired AutoConfig service is started
ensure_prerequisites
ruby
vagrant-landrush/landrush
lib/landrush/cap/host/windows/configure_visibility_on_host.rb
https://github.com/vagrant-landrush/landrush/blob/master/lib/landrush/cap/host/windows/configure_visibility_on_host.rb
MIT
def update_network_adapter(ip, tld) # Need to defer loading to ensure cross OS compatibility require 'win32/registry' if admin_mode? address = IPAddr.new(ip) network_guid = get_network_guid(address) if network_guid.nil? info("unable to determine network GUID for #{ip}. DNS on host cannot be configured. Try manual configuration.") return end interface_path = INTERFACES + "\\#{network_guid}" Win32::Registry::HKEY_LOCAL_MACHINE.open(interface_path, Win32::Registry::KEY_ALL_ACCESS) do |reg| reg['NameServer'] = '127.0.0.1' reg['Domain'] = tld end else run_with_admin_privileges(__FILE__.to_s, ip, tld) end end
Does the actual update of the network configuration
update_network_adapter
ruby
vagrant-landrush/landrush
lib/landrush/cap/host/windows/configure_visibility_on_host.rb
https://github.com/vagrant-landrush/landrush/blob/master/lib/landrush/cap/host/windows/configure_visibility_on_host.rb
MIT
def get_guid(network_name) cmd_out = `netsh lan show interfaces` interface_details = cmd_out.split(/\n\n/).select { |settings| settings.match(/#{Regexp.quote(network_name)}/m) } return nil if interface_details.empty? interface_details[0].split(/\n/)[2].match(/.*:(.*)/).captures[0].strip end
Given a network name (as displayed on 'Control Panel\Network and Internet\Network Connections'), determines the GUID of this network interface using 'netsh'. To make this work the "Wired Autoconfig" service must be started (go figure). Output of netsh command which is being processed: There are 4 interfaces on the system: Name : Ethernet Description : Intel(R) Ethernet Connection (3) I218-LM GUID : fd9270f6-aff6-4f24-bc4a-1f90c032d5c3 Physical Address : 50-7B-9D-AB-25-1D \n\n ...
get_guid
ruby
vagrant-landrush/landrush
lib/landrush/cap/host/windows/configure_visibility_on_host.rb
https://github.com/vagrant-landrush/landrush/blob/master/lib/landrush/cap/host/windows/configure_visibility_on_host.rb
MIT
def run_with_admin_privileges(file, *args) require 'win32ole' shell = WIN32OLE.new('Shell.Application') shell.ShellExecute('ruby', "#{file} #{args.join(' ')}", nil, 'runas', 1) end
Makes sure that we have admin privileges and if nor starts a new shell with the required privileges
run_with_admin_privileges
ruby
vagrant-landrush/landrush
lib/landrush/cap/host/windows/configure_visibility_on_host.rb
https://github.com/vagrant-landrush/landrush/blob/master/lib/landrush/cap/host/windows/configure_visibility_on_host.rb
MIT
def which(cmd) exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : [''] ENV['PATH'].split(File::PATH_SEPARATOR).each do |path| exts.each do |ext| exe = File.join(path, "#{cmd}#{ext}") return exe if File.executable?(exe) && !File.directory?(exe) end end nil end
Cross-platform way of finding an executable in the $PATH. which('ruby') #=> /usr/bin/ruby
which
ruby
vagrant-landrush/landrush
lib/landrush/cap/host/windows/configure_visibility_on_host.rb
https://github.com/vagrant-landrush/landrush/blob/master/lib/landrush/cap/host/windows/configure_visibility_on_host.rb
MIT
def fake_addresses [ { 'name' => 'ipv6empty1', 'ipv4' => '172.28.128.10', 'ipv6' => '' }, { 'name' => 'ipv4empty1', 'ipv4' => '', 'ipv6' => '::10' }, { 'name' => 'ipv6empty2', 'ipv4' => '172.28.128.11', 'ipv6' => '' }, { 'name' => 'ipv4empty2', 'ipv4' => '', 'ipv6' => '::11' }, { 'name' => 'exclude1', 'ipv4' => '172.28.128.1', 'ipv6' => '::1' }, { 'name' => 'include1', 'ipv4' => '172.28.128.2', 'ipv6' => '::2' }, { 'name' => 'include2', 'ipv4' => '172.28.128.3', 'ipv6' => '::3' }, { 'name' => 'include3', 'ipv4' => '172.28.128.4', 'ipv6' => '::4' }, { 'name' => 'exclude2', 'ipv4' => '172.28.128.5', 'ipv6' => '::5' }, { 'name' => 'exclude3', 'ipv4' => '172.28.128.6', 'ipv6' => '::6' } ] end
Make sure to keep the numbering sequential here Putting include/exclude out of order is kind of the point though ;)
fake_addresses
ruby
vagrant-landrush/landrush
test/test_helper.rb
https://github.com/vagrant-landrush/landrush/blob/master/test/test_helper.rb
MIT
def gem_dir `gem environment gemdir`.strip! end
Returns the gem directory for running unit tests
gem_dir
ruby
vagrant-landrush/landrush
test/test_helper.rb
https://github.com/vagrant-landrush/landrush/blob/master/test/test_helper.rb
MIT
def create_test_interface cmd_out = `VBoxManage hostonlyif create` network_description = cmd_out.match(/.*'(.*)'.*/).captures[0] `VBoxManage.exe hostonlyif ipconfig \"#{network_description}\" --ip #{TEST_IP}` sleep 3 network_description end
Creates a test interface using VBoxMange and sets a known test IP
create_test_interface
ruby
vagrant-landrush/landrush
test/landrush/cap/host/windows/configure_visibility_on_host_test.rb
https://github.com/vagrant-landrush/landrush/blob/master/test/landrush/cap/host/windows/configure_visibility_on_host_test.rb
MIT
def array(method = nil) -> (v) do if v v.split(",").map{|a| cast(a, method) } end end end
optional :accronyms, array(string) => ['a', 'b'] optional :numbers, array(int) => [1, 2] optional :notype, array => ['a', 'b']
array
ruby
interagent/pliny
lib/pliny/config_helpers.rb
https://github.com/interagent/pliny/blob/master/lib/pliny/config_helpers.rb
MIT
def pliny_env warn "Config.pliny_env is deprecated and will be removed, " \ "use Config.app_env instead." env end
DEPRECATED: pliny_env is deprecated in favour of app_env. See more at https://github.com/interagent/pliny/issues/277 This method is kept temporary in case it is used somewhere in the app.
pliny_env
ruby
interagent/pliny
lib/pliny/config_helpers.rb
https://github.com/interagent/pliny/blob/master/lib/pliny/config_helpers.rb
MIT
def env legacy_env || app_env end
This method helps with transition from PLINY_ENV to APP_ENV.
env
ruby
interagent/pliny
lib/pliny/config_helpers.rb
https://github.com/interagent/pliny/blob/master/lib/pliny/config_helpers.rb
MIT
def legacy_env if ENV.key?('PLINY_ENV') warn "PLINY_ENV is deprecated in favour of APP_ENV, " \ "update .env file or application configuration." ENV['PLINY_ENV'] end end
PLINY_ENV is deprecated, but it might be still used by someone.
legacy_env
ruby
interagent/pliny
lib/pliny/config_helpers.rb
https://github.com/interagent/pliny/blob/master/lib/pliny/config_helpers.rb
MIT
def version(*versions, &block) condition = lambda { |env| versions.include?(env["HTTP_X_API_VERSION"]) } with_conditions(condition, &block) end
yield to a builder block in which all defined apps will only respond for the given version
version
ruby
interagent/pliny
lib/pliny/router.rb
https://github.com/interagent/pliny/blob/master/lib/pliny/router.rb
MIT
def ensure_repo_available if File.exist?(repo_dir) unless system("cd #{repo_dir} && git fetch --tags") abort("Could not update Pliny repo at #{repo_dir}") end else unless system("git clone https://github.com/interagent/pliny.git #{repo_dir}") abort("Could not git clone the Pliny repo") end end end
we need a local copy of the pliny repo to produce a diff
ensure_repo_available
ruby
interagent/pliny
lib/pliny/commands/updater.rb
https://github.com/interagent/pliny/blob/master/lib/pliny/commands/updater.rb
MIT
def serializer(serializer_class) set :serializer_class, serializer_class end
Provide a way to specify endpoint serializer class. class Endpoints::User < Base serializer Serializers::User get do encode serialize(User.all) end end
serializer
ruby
interagent/pliny
lib/pliny/helpers/serialize.rb
https://github.com/interagent/pliny/blob/master/lib/pliny/helpers/serialize.rb
MIT