Language: Ruby
Untitled Ruby (3-Nov @ 23:03)
Syntax Highlighted Code
- % irb
- ruby-1.8.7-p352 :012 > require 'yaml'
- ruby-1.8.7-p352 :015 > puts [ { 'key' => 'value' }, { 'key2' => 'value2' } ].to_yaml
- ---
- [2 more lines...]
Plain Code
% irb
ruby-1.8.7-p352 :012 > require 'yaml'
ruby-1.8.7-p352 :015 > puts [ { 'key' => 'value' }, { 'key2' => 'value2' } ].to_yaml
---
- key: value
- key2: value2
=> nil
Untitled Ruby (1-Jul @ 17:11)
Syntax Highlighted Code
- #!/usr/bin/ruby
- require 'puppet'
- require 'json'
- [53 more lines...]
Plain Code
#!/usr/bin/ruby
require 'puppet'
require 'json'
require 'stomp'
def newevent
event = {:subject => nil,
:type => "archive",
:metrics => {},
:origin => "puppet report",
:extended_data => {},
:severity => 0,
:eventtime => nil,
:text => nil,
:name => nil}
end
events = []
report = YAML.load_file("/var/lib/puppet/state/last_run_report.yaml")
report.resource_statuses.find_all {|f| f[1].changed?}.each do |resource|
event = newevent
event[:eventtime] = report.time.utc.to_i
event[:name] = resource.first
event[:subject] = report.host
event[:metrics][:change_count] = resource[1].change_count
event[:metrics][:evaluation_time] = resource[1].evaluation_time
event[:metrics][:events] = resource[1].events.size
event[:metrics][:out_of_sync_count] = resource[1].out_of_sync_count
event[:extended_data][:resource_type] = resource[1].resource_type
event[:extended_data][:resource_title] = resource[1].title
event[:extended_data][:events] = resource[1].events
event[:extended_data][:catalog_version] = report.configuration_version
events << event
end
config = {}
config[:stomp] = {:user => "xx",
:password => "xx",
:server => "stomp",
:port => 6163}
config[:output] = ["/queue/unimatrix.portal"]
begin
Timeout::timeout(2) {
conn = Stomp::Connection.new(config[:stomp][:user], config[:stomp][:password], config[:stomp][:server], config[:stomp][:port])
events.each do |event|
conn.publish(config[:output], event.to_json)
end
}
rescue Exception => e
STDERR.puts "Failed to send: #{e.class}: #{e}"
exit 1
end
Untitled Ruby (1-Jul @ 16:32)
Syntax Highlighted Code
- # parsing the new last_run_report.yaml for events.
- >>> YAML.load_file("last_run_report.yaml").resource_statuses.find_all {|f| f[1].changed?}.each{|r| p r.first}
- "File[/etc/puppet/puppet.conf]"
- [1 more lines...]
Plain Code
# parsing the new last_run_report.yaml for events.
>>> YAML.load_file("last_run_report.yaml").resource_statuses.find_all {|f| f[1].changed?}.each{|r| p r.first}
"File[/etc/puppet/puppet.conf]"
"File[/etc/mcollective/facts.yaml]"
"Service[httpd]"
Untitled Ruby (24-May @ 18:47)
Syntax Highlighted Code
- module MCollective
- module Registration
- class Foo<Base
- def body
- [26 more lines...]
Plain Code
module MCollective
module Registration
class Foo<Base
def body
config = Config.instance
collective = config.pluginconf["registration.target_collective"] || nil
if collective
data = ["hello world!"]
target = Util.make_target("registration", :command, collective)
reqid = Digest::MD5.hexdigest("#{config.identity}-#{Time.now.to_f.to_s}-#{target}")
filter = {"agent" => "registration"}
req = PluginManager["security_plugin"].encoderequest(config.identity, target, data, reqid, filter)
Log.debug("Sending registration #{reqid} to #{target} in collective #{collective}")
PluginManager["connector_plugin"].send(target, req)
return nil
else
return data
end
rescue Exception => e
Log.warn("Failed to send registration: #{e.class}: #{e}")
return nil
end
end
end
end
Untitled Ruby (23-May @ 08:03)
Syntax Highlighted Code
- def say_hello subj
- puts "Hello, #{subj}"
- end
Plain Code
def say_hello subj
puts "Hello, #{subj}"
end
Untitled Ruby (23-May @ 08:00)
Syntax Highlighted Code
- def say_hello subj
- puts "Hello, subj"
- end
Plain Code
def say_hello subj
puts "Hello, subj"
end
Untitled Ruby (1-Apr @ 10:21)
Syntax Highlighted Code
- err: /Stage[main]/Base::Puppet-client/Package[puppet]: Could not evaluate: Could not get latest version: Could not list gems: Execution of '/usr/bin/gem list --remote puppet' returned 1: ERROR: http://rubygems.org/ does not appear to be a repository
- ERROR: While executing gem ... (Gem::RemoteFetcher::FetchError)
- SocketError: getaddrinfo: Name or service not known (http://rubygems.org/yaml)
- [7 more lines...]
Plain Code
err: /Stage[main]/Base::Puppet-client/Package[puppet]: Could not evaluate: Could not get latest version: Could not list gems: Execution of '/usr/bin/gem list --remote puppet' returned 1: ERROR: http://rubygems.org/ does not appear to be a repository
ERROR: While executing gem ... (Gem::RemoteFetcher::FetchError)
SocketError: getaddrinfo: Name or service not known (http://rubygems.org/yaml)
package { puppet:
provider => gem,
ensure => latest,
#source => "puppet:///puppet-client/puppet-$name.gem",
source => "/tmp/puppet-$puppet_version.gem",
}
Untitled Ruby (8-Mar @ 14:48)
Syntax Highlighted Code
- #!/usr/bin/ruby
- require 'mcollective'
- require 'pp'
- [53 more lines...]
Plain Code
#!/usr/bin/ruby
require 'mcollective'
require 'pp'
agent = "filemgr"
# the simplerpc request
request = {:action => "status",
:data => {:file => "/tmp"}}
classname = "MCollective::Agent::#{agent.capitalize}"
class NoopConnector
def method_missing(*args)
MCollective::Log.debug("connector #{args.pretty_inspect}")
true
end
end
configfile = "server.cfg"
# stub the connector with a noop one
MCollective::PluginManager << {:type => "connector_plugin", :class => NoopConnector.new}
connection = MCollective::PluginManager["connector_plugin"]
config = MCollective::Config.instance
config.loadconfig(configfile) unless config.configured
MCollective::PluginManager.loadclass(classname)
MCollective::PluginManager << {:type => "#{agent}_agent", :class => classname}
pp MCollective::PluginManager["#{agent}_agent"].handlemsg({:body => request}, connection)
OUTPUT
======
debug 2011/03/08 15:23:37: ddl.rb:56:in `findddlfile' Found filemgr ddl at /usr/libexec/mcollective/mcollective/agent/filemgr.ddl
debug 2011/03/08 15:23:37: pluginmanager.rb:73:in `[]' Returning plugin filemgr_agent with class MCollective::Agent::Filemgr
debug 2011/03/08 15:23:37: filemgr.rb:63:in `status' Asked for status of '/tmp' - it is present
{:statusmsg=>"OK",
:data=>
{:ctime=>Tue Mar 08 15:07:57 +0000 2011,
:type=>"directory",
:present=>1,
:uid=>0,
:mtime_seconds=>1299596877,
:gid=>0,
:ctime_seconds=>1299596877,
:atime_seconds=>1299529385,
:atime=>Mon Mar 07 20:23:05 +0000 2011,
:size=>4096,
:output=>"present",
:name=>"/tmp",
:md5=>0,
:mtime=>Tue Mar 08 15:07:57 +0000 2011,
:mode=>"41777"},
:statuscode=>0}
Untitled Ruby (2-Mar @ 21:28)
Syntax Highlighted Code
- module Puppet::Parser::Functions
- newfunction(:from_json, :type => :rvalue) do |args|
- PSON.load(args[0])
- end
- end
Plain Code
module Puppet::Parser::Functions
newfunction(:from_json, :type => :rvalue) do |args|
PSON.load(args[0])
end
end
Untitled Ruby (2-Mar @ 17:24)
Syntax Highlighted Code
- module MCollective
- module Agent
- class Smith < RPC::Agent
- def report_action
- [50 more lines...]
Plain Code
module MCollective
module Agent
class Smith < RPC::Agent
def report_action
reply[:libdir] = @config.libdir
reply[:agents] = Agents.agentlist
end
def updateagent_action
validate :name, String
validate :source, String
validate :method, String
validate :reload, /(true|false)/
update_methods = [ "http", "file"]
if !update_methods.include? request[:method] then
reply.fail ":method must be one of " + update_methods.join(", ")
else
destination = @config.libdir.to_s+"/mcollective/agent/"+request[:name]+".rb"
reply[:destination] = destination
end
case request[:method]
when "http":
require "rubygems"
require 'open-uri'
# Get the file from http (request[:source]) to its destination
fp=open(destination,"w")
fp.write(open(request[:source]).read)
fp.close
# is there a way to control this ??
reply[:result] = true
when "file":
require 'ftools'
# copy the file from request[:source] to the right place
begin File.syscopy(request[:source],destination)
reply[:result] = true
rescue
reply.fail "could not copy file while updating !"
end
end # end of case
if request[:reload] == "true" then
Log.instance.debug("Reload requested after update of an agent (#{request[:name]})")
end
end # end of updateagent_action method
end # end of class/class/module
end
end
Untitled Ruby (18-Feb @ 14:24)
Syntax Highlighted Code
- Facter.add(:fourthoctet) do
- setcode do
- fourthoctet = Facter.value(:ipaddress).split("\.")[3]
- end
- [2 more lines...]
Plain Code
Facter.add(:fourthoctet) do
setcode do
fourthoctet = Facter.value(:ipaddress).split("\.")[3]
end
end
Untitled Ruby (11-Feb @ 09:34)
Syntax Highlighted Code
- #!/usr/bin/ruby
- require 'mcollective'
- [31 more lines...]
Plain Code
#!/usr/bin/ruby
require 'mcollective'
include MCollective::RPC
rpcutil = rpcclient("rpcutil")
hosts = {}
count = 0
rpcutil.inventory do |resp|
facts = resp[:body][:data][:facts]
pp resp[:body][:data] if facts["hostname"].nil?
next if facts["hostname"].nil?
role = facts["hostname"]
role = $1 if role =~ /gt-(.+?)\d+/
hosts[role] ||= []
hosts[role] << {:fqdn => facts["fqdn"], :address => facts["ipaddress"]}
count += 1
end
hosts.keys.sort.each do |group|
hosts[group].each do |node|
puts "[%s;%s]" % [group, node[:fqdn]]
puts "\taddress %s" % node[:address]
puts
end
end
STDERR.puts "Dumped #{count} hosts in #{hosts.keys.size} groups"
Untitled Ruby (7-Feb @ 08:53)
Syntax Highlighted Code
- #!/usr/bin/ruby
- require 'mcollective'
- [6 more lines...]
Plain Code
#!/usr/bin/ruby
require 'mcollective'
include MCollective::RPC
u = rpcclient("rpcutil")
u.get_fact(:fact => "uptime_days") do |resp|
puts "%-30s - %s" % [ resp[:senderid], resp[:body][:data][:value].class ]
end
Untitled Ruby (2-Feb @ 15:25)
Syntax Highlighted Code
- module MCollective
- module Agent
- class Echo<RPC::Agent
- metadata :name => "Echo Agent",
- [17 more lines...]
Plain Code
module MCollective
module Agent
class Echo<RPC::Agent
metadata :name => "Echo Agent",
:description => "Simple Echo Agent",
:author => "Me",
:license => "Apache v.2",
:version => "1.0",
:url => "http://www.devco.net/",
:timeout => 2
action "echo" do
validate :msg, String
reply.fail! "Boom!" if rand(10) % 2 == 0
reply[:msg] = request[:msg]
reply[:time] = Time.now.to_s
end
end
end
end
Untitled Ruby (2-Feb @ 15:15)
Syntax Highlighted Code
- module MCollective
- module Registration
- # A registration plugin that sends in all the meta data we have for a node:
- #
- [41 more lines...]
Plain Code
module MCollective
module Registration
# A registration plugin that sends in all the meta data we have for a node:
#
# - all facts
# - all agents
# - all classes if applicable
#
# will add cf classes soon
#
# http://code.google.com/p/mcollective-plugins/wiki/RegistrationMetaData
# Author: R.I.Pienaar <rip@devco.net>
# Licence: Apache 2
class Meta<Base
def initialize
@statefile = Config.instance.pluginconf["puppetd.statefile"] || "/var/lib/puppet/state/state.yaml"
@last_registration = -1
end
def body
if File.exists?(@statefile)
last_puppet_run = File.stat(@statefile).mtime.to_i
raise "no puppet run since last registration" unless last_puppet_run > @last_registration
@last_registration = Time.now.to_i
end
result = {:agentlist => [],
:facts => {},
:classes => []}
cfile = Config.instance.classesfile
Log.instance.info("Reading classes from #{cfile}")
if File.exist?(cfile)
result[:classes] = File.readlines(cfile).map {|i| i.chomp}
end
result[:agentlist] = Agents.agentlist
result[:facts] = PluginManager["facts_plugin"].get_facts
result
end
end
end
end
Untitled Ruby (27-Jan @ 12:21)
Syntax Highlighted Code
- #!/usr/bin/ruby
- require 'puppet'
- require 'yaml'
- require 'facter'
- [65 more lines...]
Plain Code
#!/usr/bin/ruby
require 'puppet'
require 'yaml'
require 'facter'
localconfig = ARGV[0] || "#{Puppet[:clientyamldir]}/catalog/#{ Facter.fqdn }.yaml"
unless File.exist?(localconfig)
puts("Can't find #{ Facter.fqdn }.yaml")
exit 1
end
lc = File.read(localconfig)
begin
pup = Marshal.load(lc)
rescue TypeError
pup = YAML.load(lc)
rescue Exception => e
raise
end
def user_key_files
# also the filename from AuthorizedKeysFile in the sshd configfile
sshkeys = [ ".ssh/authorized_keys", ".ssh/authorized_keys2" ]
found_keyfiles = []
File.open("/etc/passwd", 'r').each do | record |
homedir = record.split(":").values_at(5)
sshkeys.each do | keyfile |
found_keyfiles.push "#{homedir}/#{keyfile}" if File.exists? "#{homedir}/#{keyfile}"
end
end
return found_keyfiles
end
# horrid - make recursion work properly instead
@puppet_keys = []
def extract_resource(resource)
if resource.class == Puppet::Resource::Catalog
resource.edges.each do |b|
extract_resource b
end
elsif resource.class == Puppet::Relationship and resource.target.class == Puppet::Resource and resource.target.title != nil and resource.target.file != nil
target = resource.target
if target.type == "File" and target.title.include? "/authorized_keys"
@puppet_keys.push target.title
return target.title
end
end
end
extract_resource(pup)
unmanaged = user_key_files - @puppet_keys
if unmanaged
puts "CRIT: #{unmanaged.length} unmanaged key files - #{unmanaged.join(", ")}"
exit 2
else
puts "OK: all #{unmanaged.length} found key files are managed"
exit 0
end
Untitled Ruby (22-Jan @ 12:43)
Syntax Highlighted Code
- #!/usr/bin/ruby
- require 'rubygems'
- require 'stomp'
- [12 more lines...]
Plain Code
#!/usr/bin/ruby
require 'rubygems'
require 'stomp'
require 'pp'
c = Stomp::Connection.open("admin", "secret", "localhost", 6163, true)
10.times { c.publish("/queue/foo", "foo") }
c.subscribe("/queue/foo")
c.subscribe("/temp-queue/bar", { "transformation" => "jms-map-xml"})
c.publish("/queue/ActiveMQ.Statistics.Broker", "", {"reply-to" => "/temp-queue/bar"})
loop do
pp c.receive
end
Untitled Ruby (22-Jan @ 00:45)
Syntax Highlighted Code
- #!/usr/bin/ruby
- # simple prototype of a file upload server supposed to run on a
- # pair of drbd machines making a filesystem available. front it
- [114 more lines...]
Plain Code
#!/usr/bin/ruby
# simple prototype of a file upload server supposed to run on a
# pair of drbd machines making a filesystem available. front it
# with a load balancer and get a cheap cluster web file server
# that supports failover and scaling using shards of redudant
# storage servers
#
#
# - rest service |
# / - drbd
# client | ----- | load balancer |
# \ - drbd
# - rest service |
#
#
# On the DRBD lives a file 'owner' that is mode 000 and each REST
# service checks for the existence of this file to determine if it
# should serve requests. The load balancer health checks with GET
# on / which also checks for the existance of this file thus the
# load balancer picks the active host to send file writes and
# deletes to. Any IO failure results in a 500 error which the
# load balancer also understands as failure
#
# File reads to the CDN that fronts this will still be doing using
# normal apache or lighttpd
#
# This is a prototype showing the protocol, final version will be
# based on node.js
#
# upload with curl
# curl -F "file=@file.txt" http://localhost:4567/some/long/path/to/file/file.txt
#
# delete with telnet
# telnet localhost 4567
# DELETE /some/long/path/to/file/file.txt HTTP/1.0
#
# test with curl
# curl http://localhost:4567/
#
# R.I.Pienaar <rip@devco.net>
require 'rubygems'
require 'sinatra'
require 'fileutils'
# uploads to /tmp/uploads only if /tmp/uploads/owner exist
DEST="/tmp/uploads"
OWNERFILE="owner"
class Filer
class << self
def storage_owner?
File.exist?(File.join([DEST, OWNERFILE]))
end
def delete(file)
fpath = File.join([DEST, file])
FileUtils.rm(fpath) if File.exist?(fpath)
File.exist?(fpath) ? false : true
end
def upload(file, tempfile)
fpath = File.join([DEST, file])
dirname = File.dirname(fpath)
FileUtils.mkdir_p(dirname) unless File.exist?(dirname)
File.open(fpath, "w") do |f|
while blk = tempfile.read(65536)
f.print blk
end
end
return fpath
end
end
end
before { halt 500, "Not the storage owner\n" unless Filer.storage_owner? }
get "/" do
"ok\n"
end
post "/*" do
halt 500, "please specify a file name\n" unless params[:splat][0]
halt 500, "No file uploaded\n" unless params[:file] && params[:file][:tempfile]
tmpfile = params[:file][:tempfile]
saved_file = ""
begin
saved_file = Filer.upload(params[:splat][0], tmpfile)
rescue Exception => e
halt 500, "Failed to handle file upload: #{e}\n"
ensure
tmpfile.delete
end
"saved " << saved_file << "\n"
end
delete "/*" do
halt 500, "please specify a file name\n" unless params[:splat][0]
begin
if Filer.delete(params[:splat][0])
return "file deleted\n"
else
halt 500, "could not delete file\n"
end
rescue Exception => e
halt 500, "Failed to handle file delete: #{e}\n"
end
end
Untitled Ruby (21-Jan @ 13:26)
Syntax Highlighted Code
- # calculate duration
- if duration > 0 then
- end_date = "'now() + interval \'1 day\''"
- else
- [17 more lines...]
Plain Code
# calculate duration
if duration > 0 then
end_date = "'now() + interval \'1 day\''"
else
end_date=nil
end
puts "insertion de #{target}"
DB[:network_filter].insert(
:network => target,
:hardblock => bgp,
:explanation_id => 1,
:custom_message => message,
:start_date => nil,
:end_date => end_date,
:state => 1,
:cause_id => 1,
:cause => cause,
:contact => contact,
:removal_cause => '')
Untitled Ruby (20-Jan @ 21:35)
Syntax Highlighted Code
- receive_data: "CONNECT"
- receive_data: "\n"
- receive_data: "login:rip"
- receive_data: "\n"
- [22 more lines...]
Plain Code
receive_data: "CONNECT"
receive_data: "\n"
receive_data: "login:rip"
receive_data: "\n"
receive_data: "content-length:0"
receive_data: "\n"
receive_data: "passcode:xxx"
receive_data: "\n"
receive_data: "content-type: text/plain; charset=UTF-8"
receive_data: "\n"
receive_data: "\n"
receive_data: "\000"
Connecting
Sending frame CONNECTED
session:wow
receive_data: "SUBSCRIBE"
receive_data: "\ndestination:/topic/meh\ncontent-length:0\ncontent-type: text/plain; charset=UTF-8\n\n\000"
receive_data: "SEND\ndestination:/topic/meh\ncontent-length:5\ncontent-type: text/plain; charset=UTF-8\n\nhello\000"
Sending frame MESSAGE
message-id:msg-#stompcma-1
content-type:text/plain; charset=UTF-8
destination:/topic/meh
content-length:5
hello
Untitled Ruby (19-Jan @ 15:01)
Syntax Highlighted Code
- packagename = case node[:platform]
- when "debian" then "snmpd"
- when "freebsd" then "net-snmp"
- end
- [6 more lines...]
Plain Code
packagename = case node[:platform]
when "debian" then "snmpd"
when "freebsd" then "net-snmp"
end
package packagename do
action :install
if node[:platform] == "freebsd" then
source "ports"
end
end
Untitled Ruby (19-Jan @ 10:35)
Syntax Highlighted Code
- # handle debian flooding the logs
- if node[:platform] == "debian" then
- cookbook_file "snmpd_default" do
- [4 more lines...]
Plain Code
# handle debian flooding the logs
if node[:platform] == "debian" then
cookbook_file "snmpd_default" do
path "/etc/default/snmpd"
source "debian-default"
notifies :restart, "service[snmpd]", :immediatly
end
end
Untitled Ruby (18-Jan @ 18:34)
Syntax Highlighted Code
- >> rpc(:list, :pattern => "init") {|r| pp r}
- #<MCollective::RPC::Result:0xb7e881b0
- @action="list",
- @agent="process",
- [62 more lines...]
Plain Code
>> rpc(:list, :pattern => "init") {|r| pp r}
#<MCollective::RPC::Result:0xb7e881b0
@action="list",
@agent="process",
@results=
{:statusmsg=>"OK",
:data=>
{:pslist=>
[{:flags=>4194560,
:processor=>0,
:session=>1,
:cminflt=>185351732,
:euid=>0,
:rt_priority=>0,
:tty_nr=>0,
:kstkeip=>14746626,
:cutime=>417813,
:wchan=>0,
:endcode=>134544728,
:blocked=>0,
:utime=>0,
:name=>"init",
:uid=>0,
:egid=>0,
:cmdline=>"init [3]",
:startstack=>3219631088,
:username=>"root",
:signal=>0,
:ppid=>0,
:majflt=>18,
:cstime=>156676,
:vsize=>2228224,
:tpgid=>-1,
:cmajflt=>6610,
:gid=>0,
:nswap=>0,
:minflt=>1075,
:sigignore=>1475401980,
:pid=>1,
:cwd=>"/",
:comm=>"init",
:sigcatch=>671819267,
:environ=>
{"TERM"=>"linux",
"SELINUX_INIT"=>"YES",
"HOME"=>"/",
"PATH"=>"/bin:/usr/bin:/sbin:/usr/sbin"},
:rss=>151,
:nice=>0,
:cnswap=>0,
:policy=>0,
:itrealvalue=>0,
:starttime=>16,
:exit_signal=>0,
:pgrp=>1,
:exe=>"/sbin/init",
:rlim=>4294967295,
:state=>"S",
:kstkesp=>3219629772,
:stime=>8,
:priority=>15,
:fd=>{"10"=>"/dev/initctl"},
:startcode=>134512640,
:root=>"/"}]},
:statuscode=>0}>
Finished processing 1 / 1 hosts in 120.47 ms
Untitled Ruby (18-Jan @ 13:48)
Syntax Highlighted Code
- module MCollective
- module Agent
- # An agent that uses Opscode to manage services
- # Made from the puppet version
- [51 more lines...]
Plain Code
module MCollective
module Agent
# An agent that uses Opscode to manage services
# Made from the puppet version
class Service<RPC::Agent
metadata :name => "SimpleRPC Service Agent",
:description => "Agent to manage services",
:author => "R.I.Pienaar",
:license => "GPLv2",
:version => "1.2",
:url => "http://mcollective-plugins.googlecode.com/",
:timeout => 60
["stop", "start", "restart"].each do |act|
action act do
do_service_action(act)
end
end
private
# Does the actual work with the chef provider and sets appropriate reply options
def do_service_action(action)
validate :service, String
service = request[:service]
require 'chef'
require 'chef/client'
require 'chef/run_context'
begin
Chef::Config[:solo] = true
Chef::Config[:log_level] = :debug
Chef::Log.level(:debug)
client = Chef::Client.new
client.run_ohai
client.build_node
run_context = Chef::RunContext.new(client.node, Chef::CookbookCollection.new(Chef::CookbookLoader.new))
recipe = Chef::Recipe.new("adhoc", "default", run_context)
resource = recipe.send(:service, service)
resource.send("action",action)
Log.instance.debug("Doing '#{action}' for service '#{service}'")
Chef::Runner.new(run_context).converge
reply["status"] = true
rescue Exception => e
reply.fail "#{e}"
end
end
end
end
end
# vi:tabstop=4:expandtab:ai:filetype=ruby
Untitled Ruby (18-Jan @ 09:36)
Syntax Highlighted Code
- munin.mc:
- inventory do
- format "[%s;%s]\n\taddress %s\n\n"
- [12 more lines...]
Plain Code
munin.mc:
inventory do
format "[%s;%s]\n\taddress %s\n\n"
fields { [ facts["location"], identity, facts["ipaddress"] ] }
end
% mc-inventory --script munin.mc
[hetzner;xen3.xx.net]
address 213.x.x.x
[hetzner;ns1.yy.net]
address 78.x.x.x
Untitled Ruby (18-Jan @ 09:10)
Syntax Highlighted Code
- class MCollective::Application::Facts<MCollective::Application
- description "Reports on usage for a specific fact"
- # this will be available in configuration[:fact]
- [51 more lines...]
Plain Code
class MCollective::Application::Facts<MCollective::Application
description "Reports on usage for a specific fact"
# this will be available in configuration[:fact]
option :script,
:description => "Fact to report on",
:arguments => ["--fact FACT", "-f FACT"]
def post_option_parser(configuration)
configuration[:fact] = ARGV.shift if ARGV.size > 0
end
def validate_configuration(configuration)
raise "Please specify a fact to report for" unless configuration.include?(:fact)
end
def show_single_fact_report(fact, facts, verbose=false)
puts("Report for fact: #{fact}\n\n")
facts.keys.sort.each do |k|
printf(" %-40sfound %d times\n", k, facts[k].size)
if verbose
puts
facts[k].sort.each do |f|
puts(" #{f}")
end
puts
end
end
end
def main
rpcutil = rpcclient("rpcutil", :options => options)
rpcutil.progress = false
facts = {}
rpcutil.get_fact(:fact => configuration[:fact]) do |resp|
begin
value = resp[:body][:data][:value]
if value
facts.include?(value) ? facts[value] << resp[:senderid] : facts[value] = [ resp[:senderid] ]
end
rescue Exception => e
STDERR.puts "Could not parse facts for #{resp[:senderid]}: #{e.class}: #{e}"
end
end
show_single_fact_report(configuration[:fact], facts, options[:verbose])
printrpcstats
end
end
Untitled Ruby (16-Jan @ 21:02)
Syntax Highlighted Code
- class nagios::hostgroup::activemq_servers {
- $nodes = search_nodes("{'classes' => 'activemq', 'facts.monitors' => /${fqdn}/}")
- if $nodes != [] {
- [5 more lines...]
Plain Code
class nagios::hostgroup::activemq_servers {
$nodes = search_nodes("{'classes' => 'activemq', 'facts.monitors' => /${fqdn}/}")
if $nodes != [] {
nagios::hostgroup{"activemq_servers":
nodes => $nodes,
description => "ActiveMQ Servers"
}
}
}
Untitled Ruby (14-Jan @ 13:03)
Syntax Highlighted Code
- #!/usr/bin/ruby
- require 'mcollective'
- [15 more lines...]
Plain Code
#!/usr/bin/ruby
require 'mcollective'
include MCollective::RPC
rpc = rpcclient("puppetd")
enabled = running = 0
rpc.status do |resp|
begin
enabled += resp[:body][:data][:enabled]
running += resp[:body][:data][:running]
rescue Exception => e
STDERR.puts "Failed to get results: #{e}"
end
end
puts "enabled: #{enabled} runnig: #{running}"
Untitled Ruby (14-Jan @ 09:17)
Syntax Highlighted Code
- ====================
- #<Stomp::Message:0xb7e3d8e0
- @body=
- "{\"ConnectionInfo\": {\n \"commandId\": 0,\n \"responseRequired\": true,\n \"connectionId\": {\n \"value\": \"ID:xx.xx.net-57901-1294599217160-5:3943\"\n },\n \"clientId\": \"ID:xx.xx.net-57901-1294599217160-5:3943\",\n \"userName\": \"\",\n \"password\": \"\",\n \"brokerMasterConnector\": false,\n \"manageable\": false,\n \"clientMaster\": true,\n \"faultTolerant\": false,\n \"failoverReconnect\": false\n}}",
- [14 more lines...]
Plain Code
====================
#<Stomp::Message:0xb7e3d8e0
@body=
"{\"ConnectionInfo\": {\n \"commandId\": 0,\n \"responseRequired\": true,\n \"connectionId\": {\n \"value\": \"ID:xx.xx.net-57901-1294599217160-5:3943\"\n },\n \"clientId\": \"ID:xx.xx.net-57901-1294599217160-5:3943\",\n \"userName\": \"\",\n \"password\": \"\",\n \"brokerMasterConnector\": false,\n \"manageable\": false,\n \"clientMaster\": true,\n \"faultTolerant\": false,\n \"failoverReconnect\": false\n}}",
@command="MESSAGE",
@headers=
{"timestamp"=>"0",
"message-id"=>
"ID:xx.xx.net-57901-1294599217160-2:0:0:0:63185",
"expires"=>"0",
"destination"=>"/topic/ActiveMQ.Advisory.Connection",
"priority"=>"0",
"type"=>"Advisory",
"originBrokerURL"=>"tcp://xx.xx.net:6166",
"originBrokerId"=>"ID:xx.xx.net-57901-1294599217160-0:0",
"originBrokerName"=>"xx-xx"},
@original=
"MESSAGE\nmessage-id:ID:xx.xx.net-57901-1294599217160-2:0:0:0:63185\noriginBrokerName:xx-xx\ntype:Advisory\ndestination:/topic/ActiveMQ.Advisory.Connection\ntimestamp:0\nexpires:0\npriority:0\noriginBrokerURL:tcp://xx.xx.net:6166\noriginBrokerId:ID:xx.xx.net-57901-1294599217160-0:0\n\n{\"ConnectionInfo\": {\n \"commandId\": 0,\n \"responseRequired\": true,\n \"connectionId\": {\n \"value\": \"ID:xx.xx.net-57901-1294599217160-5:3943\"\n },\n \"clientId\": \"ID:xx.xx.net-57901-1294599217160-5:3943\",\n \"userName\": \"\",\n \"password\": \"\",\n \"brokerMasterConnector\": false,\n \"manageable\": false,\n \"clientMaster\": true,\n \"faultTolerant\": false,\n \"failoverReconnect\": false\n}}\000">
====================
Untitled Ruby (13-Jan @ 15:41)
Syntax Highlighted Code
- class ipsec::servers::monitor1 {
- $clients = search_nodes("{'classes' => 'ipsec::endpoint::monitor1'}")
- ipsec::endpoints_from_nodes{$clients: }
- [20 more lines...]
Plain Code
class ipsec::servers::monitor1 {
$clients = search_nodes("{'classes' => 'ipsec::endpoint::monitor1'}")
ipsec::endpoints_from_nodes{$clients: }
}
define ipsec::endpoints_from_nodes {
$node = load_node($name)
ipsec::endpoint{$node["fqdn"]:
dest => $node["facts"]["ipaddress"]
}
}
define ipsec::endpoint($dest, $ensure = "present", $mode = "transport") {
$safe_name = regsubst($name, '-', '_', 'G')
file{"/etc/sysconfig/network-scripts/ifcfg-ipsec.${safe_name}":
owner => root,
group => root,
mode => 644,
ensure => $ensure,
content => template("ipsec/${mode}-mode-endpoint.erb")
}
}
Untitled ActionScript (13-Jan @ 11:30)
Syntax Highlighted Code
- #!/usr/bin/ruby
- require 'mcollective'
- [6 more lines...]
Plain Code
#!/usr/bin/ruby
require 'mcollective'
include MCollective::RPC
rpc = rpcclient("rpcutil")
rpc.get_fact(:fact => "foo").each do |resp|
puts "%40s: %s %s" % [ resp[:sender], resp[:statuscode], resp[:statusmsg]]
end
Untitled Ruby (13-Jan @ 02:57)
Syntax Highlighted Code
- define ipsec::endpoints_from_nodes {
- $node = load_node($name)
- ipsec::endpoint{$node["fqdn"]:
- [8 more lines...]
Plain Code
define ipsec::endpoints_from_nodes {
$node = load_node($name)
ipsec::endpoint{$node["fqdn"]:
dest => $node["facts"]["ipaddress"]
}
}
class ipsec::servers::monitor1 {
$clients = search_nodes("{'classes' => 'ipsec::endpoint::monitor1'}")
ipsec::endpoints_from_nodes{$clients: }
}
Untitled Ruby (13-Jan @ 02:34)
Syntax Highlighted Code
- class ipsec::servers::monitor1 {
- $clients = search_nodes("{'classes' => 'ipsec::endpoint::monitor1'}")
- ipsec::endpoints_from_nodes{$clients: }
- [8 more lines...]
Plain Code
class ipsec::servers::monitor1 {
$clients = search_nodes("{'classes' => 'ipsec::endpoint::monitor1'}")
ipsec::endpoints_from_nodes{$clients: }
}
define ipsec::endpoints_from_nodes {
$node = load_node($name)
ipsec::endpoint{$node["facts"]["fqdn"]:
dest => $node["facts"]["ipaddress"]
}
}
Untitled Ruby (9-Dec @ 09:50)
Syntax Highlighted Code
- # traditional ways
- "a : bcd(1234: xyz)".gsub(/(\(\w*:)( )(\w*\))/, '\1ijk\3')
- [1 more lines...]
Plain Code
# traditional ways
"a : bcd(1234: xyz)".gsub(/(\(\w*:)( )(\w*\))/, '\1ijk\3')
# look-behind assertions
"a : bcd(1234: xyz)".gsub(/(?<=\w:) /, 'ijk')
Untitled Ruby (5-Oct @ 14:57)
Syntax Highlighted Code
- require 'net/http'
- require 'hpricot'
- require 'rss/maker'
- require 'uri'
- [61 more lines...]
Plain Code
require 'net/http'
require 'hpricot'
require 'rss/maker'
require 'uri'
class EMB
attr_writer :realm, :user, :password
def initialize ( realm = 'chs_programming', user='zichun', password='paksux' )
@realm, @user, @password = realm, user, password
@cookies = []
@cookie_string = ''
end
def get_cookie
http = Net::HTTP.new('smb.chs.edu.sg', 80)
resp,data = http.post('/cgi-bin/emb/login.pl',
"userid=#{@user}&password=#{@password}&login=+++Login+++",
{'referer'=>'http://smb.chs.edu.sg/emb/'+@realm+'/',
'user_agent'=>'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9) Gecko/2008051206 Firefox/3.0'
})
resp.get_fields('set-cookie').each { |x|
@cookies << x
@cookie_string += x.split("\; ")[0] + "\;"
}
@cookie_string
end
def get_main
http = Net::HTTP.new('smb.chs.edu.sg', 80)
http.get('/cgi-bin/emb/view.pl?date', {'Cookie'=>@cookie_string})
end
def get_msg (link)
url = URI.parse(link)
http = Net::HTTP.new('smb.chs.edu.sg',80)
http.get( url.path+'?'+url.query, {'Cookie'=>@cookie_string} )
end
end
emb_client = EMB.new
emb_client.get_cookie
res = emb_client.get_main
version = "2.0"
content = RSS::Maker.make(version) { |m|
m.channel.title = "EMB CHS_PROGRAMMING"
m.channel.link = "http://smb.chs.edu.sg/emb/chs_programming"
m.channel.description = "Extracted messages from chs_programming EMB"
m.items.do_sort = true
doc = Hpricot(res.body)
for i in 2...(doc/"form").length
item = m.items.new_item
x = (doc/"form")[i]
item.title = (x/"a").text
item.link = "http://smb.chs.edu.sg/emb/chs_programming/"
item.date = Time.parse(((x/"font")[0]).innerHTML.strip)
emb_body = Hpricot(emb_client.get_msg( x.at("a")['href'] ).body)
item.description = emb_body.at("pre")
item.author = (x/"td")[2].innerHTML.strip
end
}
$stdout.write(content)
Untitled Ruby (30-Sep @ 09:13)
Syntax Highlighted Code
- require 'rubygems'
- require 'sinatra'
- [34 more lines...]
Plain Code
require 'rubygems'
require 'sinatra'
get '/' do
haml <<END
!!!
%html
%head
%title Greetings
%body
%p Prepare to be greeted
%form{:action => 'hello', :method => 'post'}
%input{:type => 'text', :name => 'name'}
%input{:type => 'submit', :value => 'Greet'}
END
end
get '/hello/:name' do
greet(params[:name])
end
post '/hello' do
greet(params[:name])
end
private
def greet(name)
haml <<END
!!!
%html
%head
%title Greetz
%body
%h1 Heya!
%p= "Hello <em> #{name} </em>"
END
end
Untitled Ruby (21-Sep @ 22:20)
Syntax Highlighted Code
- puts "hello World"
Plain Code
puts "hello World"
Untitled Ruby (13-Sep @ 23:31)
Syntax Highlighted Code
- puts "hola que tal?"
Plain Code
puts "hola que tal?"
Untitled Ruby (27-Aug @ 10:05)
Syntax Highlighted Code
- p = ['a', 'b', 'c']
- p.each do |item|
- puts item
- end
Plain Code
p = ['a', 'b', 'c']
p.each do |item|
puts item
end
Untitled Ruby (28-Jul @ 10:22)
Syntax Highlighted Code
- before :deploy, "solr:stop"
- after :deploy, "solr:start"
Plain Code
before :deploy, "solr:stop"
after :deploy, "solr:start"
Untitled Ruby (4-Jul @ 09:50)
Syntax Highlighted Code
- a = String.new
- puts a.methods
Plain Code
a = String.new
puts a.methods
Untitled Ruby (18-Jun @ 21:58)
Syntax Highlighted Code
- class Carro
- def initialize
- [2 more lines...]
Plain Code
class Carro
def initialize
end
end
Untitled Ruby (28-May @ 10:32)
Syntax Highlighted Code
- class Example
- def foo
- put 'bar'
- end
- end
Plain Code
class Example
def foo
put 'bar'
end
end
Untitled Ruby (27-May @ 22:53)
Syntax Highlighted Code
- a = 123
- b = 123
- puts a + b
Plain Code
a = 123
b = 123
puts a + b
Untitled Ruby (12-May @ 08:05)
Syntax Highlighted Code
- include "hpricot"
Plain Code
include "hpricot"
Untitled Ruby (10-May @ 10:48)
Syntax Highlighted Code
- def test
- :foo => "bar"
- end
Plain Code
def test
:foo => "bar"
end