repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/spec/support/shared_examples_for_cpu.rb
spec/support/shared_examples_for_cpu.rb
CPU_8_BIT_REGISTERS = %w'a x y s' CPU_FLAGS = %w'n v d i z c' CPU_8_BIT_REGISTERS.each do |register| shared_examples_for "set #{register.upcase} value" do |expected| it do cpu.step value = cpu.send(register) expect(value).to be(expected), "Expected: #{hex_byte(expected)}, found: #{hex_byte(value)}" end end end CPU_FLAGS.each do |flag| shared_examples_for "set #{flag.upcase} flag" do it do cpu.step expect(cpu.send(flag)).to be_truthy end end shared_examples_for "reset #{flag.upcase} flag" do it do cpu.step expect(cpu.send(flag)).to be_falsey end end end shared_examples_for "preserve flags" do CPU_FLAGS.each do |flag| it "keeps #{flag} reset" do cpu.send("#{flag}=", false) cpu.step expect(cpu.send(flag)).to be_falsey end it "keeps #{flag} set" do cpu.send("#{flag}=", true) cpu.step expect(cpu.send(flag)).to be_truthy end end end shared_examples_for 'set PC value' do |expected| it do cpu.step value = cpu.pc expect(value).to be(expected), "Expected: #{hex_word(expected)}, found: #{hex_word(value)}" end end shared_examples_for 'set memory with value' do |position, expected| it do cpu.step value = cpu.memory[position] expect(value).to be(expected), "Expected: #{hex_byte(expected)} at address #{hex_word(position)}, found: #{hex_byte(value)}" end end 1.upto 3 do |number| shared_examples_for "advance PC by #{number.humanize}" do it { expect { cpu.step }.to change { cpu.pc }.by number } end end 2.upto 7 do |number| shared_examples_for "take #{number.humanize} cycles" do it { expect(cpu.step).to eq(number) } end end shared_examples_for 'add and set A/C/V' do |a, m, result, c, v| before do cpu.c = false # CLC cpu.a = a # LDA #$a cpu.memory[0..1] = 0x69, m # ADC #$m cpu.step end it { expect(cpu.a).to eq(result) } it { expect(cpu.c).to eq(c) } it { expect(cpu.v).to eq(v) } end shared_examples_for 'subtract and set A/C/V' do |a, m, result, c, v| before do cpu.c = true # SEC cpu.a = a # LDA #$a cpu.memory[0..1] = 0xE9, m # SBC #$m cpu.step end it { expect(cpu.a).to eq(result) } it { expect(cpu.c).to eq(c) } it { expect(cpu.v).to eq(v) } end shared_examples_for 'set memory with P for various flag values' do |address| context 'all flags set' do before { cpu.n = cpu.v = cpu.d = cpu.i = cpu.z = cpu.c = true } it_does 'set memory with value', address, 0b11111111 end context 'all flags clear' do before { cpu.n = cpu.v = cpu.d = cpu.i = cpu.z = cpu.c = false } it_does 'set memory with value', address, 0b00110000 end context 'mixed flags' do before do cpu.n = cpu.d = cpu.z = true cpu.v = cpu.i = cpu.c = false end it_does 'set memory with value', address, 0b10111010 end end shared_examples_for 'read flags (P) from memory for various values' do |address| context 'all flags set' do before { cpu.memory[address] = 0b11111111 } it_does 'set N flag' it_does 'set V flag' it_does 'set D flag' it_does 'set I flag' it_does 'set Z flag' it_does 'set C flag' end context 'all flags clear' do before { cpu.memory[address] = 0 } it_does 'reset N flag' it_does 'reset V flag' it_does 'reset D flag' it_does 'reset I flag' it_does 'reset Z flag' it_does 'reset C flag' end context 'mixed flags' do before { cpu.memory[address] = 0b10111010 } it_does 'set N flag' it_does 'set D flag' it_does 'set Z flag' it_does 'reset V flag' it_does 'reset I flag' it_does 'reset C flag' end end shared_examples_for "a branch instruction" do before { cpu.pc = 0x0510 } context 'no branch' do before do cpu.memory[0x0510..0x0511] = opcode, 0x02 # B?? $0514 cpu.send("#{flag}=", !branch_state) end it_does 'take two cycles' it_does 'advance PC by two' it_does 'preserve flags' end context 'branch' do before { cpu.send("#{flag}=", branch_state) } context 'forward on same page' do before { cpu.memory[0x0510..0x0511] = opcode, 0x02 } # B?? $0514 it_does 'take three cycles' it_does 'set PC value', 0x0514 it_does 'preserve flags' end context 'backward on same page' do before { cpu.memory[0x0510..0x0511] = opcode, 0xFC } # B?? $050E it_does 'take three cycles' it_does 'set PC value', 0x050E it_does 'preserve flags' end context 'forward on another page' do before do cpu.pc = 0x0590 cpu.memory[0x0590..0x0591] = opcode, 0x7F # B?? $0611 end it_does 'take four cycles' it_does 'set PC value', 0x0611 it_does 'preserve flags' end context 'backward on another page' do before { cpu.memory[0x0510..0x0511] = opcode, 0x80 } # B?? $0492 it_does 'take four cycles' it_does 'set PC value', 0x0492 it_does 'preserve flags' end context 'forward wrapping around memory' do before do cpu.pc = 0xFF90 cpu.memory[0xFF90..0xFF91] = opcode, 0x7F # B?? $0611 end it_does 'take four cycles' it_does 'set PC value', 0x0011 it_does 'preserve flags' end end end shared_examples_for 'compare and set flags' do |register, value| context 'register < value' do before { cpu.send("#{register}=", value - 1) } it_does 'set N flag' it_does 'reset C flag' it_does 'reset Z flag' end context 'register = value' do before { cpu.send("#{register}=", value) } it_does 'reset N flag' it_does 'set C flag' it_does 'set Z flag' end context 'register > value' do before { cpu.send("#{register}=", value + 1) } it_does 'reset N flag' it_does 'set C flag' it_does 'reset Z flag' end end shared_examples_for 'work on any memory position' do it 'works on lower 1KB' do 0x1000.downto 0x0000 do |position| step_and_check(code, position) end end it 'works on 2600 cart region' do |position| 0xFFFF.downto 0xF000 do |position| step_and_check(code, position) end end def step_and_check(code, position) store_in_64KB_memory code, position expected_pc = position + code.size & 0xFFFF randomize :a cpu.pc = position cpu.step expect(cpu.pc).to eq(expected_pc) expect(cpu.a).to eq(expected_a), "for position=#{hex_word(position)}" if expected_a end def store_in_64KB_memory(code, position) code.each do |byte| cpu.memory[position] = byte position = (position + 1) & 0xFFFF end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/spec/support/shared_examples_for_bus.rb
spec/support/shared_examples_for_bus.rb
%w'tia riot cart'.each do |chip| shared_examples_for "read address range from #{chip}" do |range| it do range.each do |address| value = Random.rand(256) allow(send(chip)).to receive(:[]).with(address).and_return(value) expect(subject[address]).to eq(value) end end end shared_examples_for "write address range to #{chip}" do |range| it do range.each do |address| value = Random.rand(256) expect(send(chip)).to receive(:[]=).with address, value subject[address] = value end end end end shared_examples_for 'set bits on RIOT port after switch is set/pressed' do |port, bits, switch| it 'updates portB' do expect(riot).to receive("#{port}=").with(bits) bus.send "#{switch}=", true end end shared_examples_for 'set bits on RIOT port after switch is reset/released' do |port, bits, switch| it 'updates portB' do expect(riot).to receive("#{port}=").with(bits) bus.send "#{switch}=", false end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/spec/support/shared_examples_for_tia.rb
spec/support/shared_examples_for_tia.rb
shared_examples_for 'update collision register bit for objects' do |register, bit, obj1, obj2| before do tia.reg[CXCLR] = 0 %w'p0 p1 m0 m1 bl pf'.each { |obj| turn_off obj } end context 'both objects output' do before do turn_on obj1 turn_on obj2 end it 'sets the flag' do tia.send(:update_collision_flags) expect(tia[register][bit]).to eq(1) end end context 'neither object outputs' do before do turn_off obj1 turn_off obj2 end it { expect { tia.send(:update_collision_flags) }.to_not change { tia[register][bit] } } end context 'only first object outputs' do before do turn_on obj1 turn_off obj2 end it { expect { tia.send(:update_collision_flags) }.to_not change { tia[register][bit] } } end context 'only second object outputs' do before do turn_off obj1 turn_on obj2 end it { expect { tia.send(:update_collision_flags) }.to_not change { tia[register][bit] } } end context 'all objects output' do before do %w'p0 p1 m0 m1 bl pf'.each { |obj| turn_on obj} end it 'sets the flag' do tia.send(:update_collision_flags) expect(tia[register][bit]).to eq(1) end end def turn_on(object) allow(tia.instance_variable_get("@#{object}")).to receive(:pixel).and_return(rand(256)) end def turn_off(object) allow(tia.instance_variable_get("@#{object}")).to receive(:pixel).and_return(nil) end end shared_examples_for 'reflect port input' do |port| it "sets/clears bit 7 on high/low level" do tia.set_port_level port, :low expect(tia[INPT0 + port][7]).to eq(0) tia.set_port_level port, :high expect(tia[INPT0 + port][7]).to eq(1) tia.set_port_level port, :low expect(tia[INPT0 + port][7]).to eq(0) end end shared_examples_for 'latch port input' do |port| context "- with the level initially high" do it "INPT#{port} bit 7 should latch to 0 once a low is received" do tia[VBLANK] = 0 tia.set_port_level port, :high tia[VBLANK] = 0b01000000 expect(tia[INPT0 + port][7]).to eq(1) tia.set_port_level port, :high expect(tia[INPT0 + port][7]).to eq(1) tia.set_port_level port, :low expect(tia[INPT0 + port][7]).to eq(0) tia.set_port_level port, :high expect(tia[INPT0 + port][7]).to eq(0) tia.set_port_level port, :low expect(tia[INPT0 + port][7]).to eq(0) end it "- INPT#{port} bit 7 should return to normal behavior after latching is disabled" do tia[VBLANK] = 0b01000000 tia.set_port_level port, :high tia[VBLANK] = 0 expect(tia[INPT0 + port][7]).to eq(1) tia.set_port_level port, :low expect(tia[INPT0 + port][7]).to eq(0) tia.set_port_level port, :high expect(tia[INPT0 + port][7]).to eq(1) tia.set_port_level port, :low expect(tia[INPT0 + port][7]).to eq(0) end end # Both the Stella manual and http://nocash.emubase.de/2k6specs.htm#controllersjoysticks # are imprecise on the real behaviour. This one is what Stella does, and it # is the only that simultaneously work with Pitfall, Donkey Kong and River Raid context "- with the level initially low" do it "INPT#{port} bit 7 should stay low, allow one high, then keep low" do tia[VBLANK] = 0 tia.set_port_level port, :low tia[VBLANK] = 0b01000000 expect(tia[INPT0 + port][7]).to eq(0) tia.set_port_level port, :high expect(tia[INPT0 + port][7]).to eq(1) tia.set_port_level port, :low expect(tia[INPT0 + port][7]).to eq(0) tia.set_port_level port, :high expect(tia[INPT0 + port][7]).to eq(0) tia.set_port_level port, :low expect(tia[INPT0 + port][7]).to eq(0) end it "- INPT#{port} bit 7 should return to normal behavior after latching is disabled" do tia.set_port_level port, :low tia[VBLANK] = 0b01000000 tia[VBLANK] = 0 expect(tia[INPT0 + port][7]).to eq(0) tia.set_port_level port, :low expect(tia[INPT0 + port][7]).to eq(0) tia.set_port_level port, :high expect(tia[INPT0 + port][7]).to eq(1) tia.set_port_level port, :low expect(tia[INPT0 + port][7]).to eq(0) end end end shared_examples_for 'dump port to ground' do |port| it "INPT#{port} bit 7 should not be affected by input (should always be 0)" do tia.set_port_level port, :low expect(tia[INPT0 + port][7]).to eq(0) tia.set_port_level port, :high expect(tia[INPT0 + port][7]).to eq(0) tia.set_port_level port, :low expect(tia[INPT0 + port][7]).to eq(0) end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/spec/support/shared_examples_for_riot.rb
spec/support/shared_examples_for_riot.rb
shared_examples_for 'a timer with clock interval' do |interval| let(:initial_value) { rand(50) + 200 } before { riot[timer_register] = initial_value } it 'decrements immediately after initialization' do expect(riot[INTIM]).to eq(initial_value - 1) end it 'reduces current value (INTM) on every 8th call' do 10.times do (interval - 1).times { expect{ riot.tick }.to_not change{ riot[INTIM] } } expect{ riot.tick }.to change{ riot[INTIM] }.by -1 end end it 'underflows gracefully' do riot[timer_register] = 0x02 expect(riot[INTIM]).to eq(0x01) interval.times { riot.tick } expect(riot[INTIM]).to eq(0x00) interval.times { riot.tick } expect(riot[INTIM]).to eq(0xFF) end it 'underflows immediately after initialization with 0' do riot[timer_register] = 0 expect(riot[INTIM]).to eq(0xFF) end it 'resets interval to 1 after underflow' do riot[timer_register] = 0x01 interval.times { riot.tick } expect(riot[INTIM]).to eq(0xFF) riot.tick expect(riot[INTIM]).to eq(0xFE) end context 'instat (timer status)' do it 'has bits 6 & 7 clear if no underflow happened' do 10.times do expect(riot[INSTAT][6]).to eq(0) expect(riot[INSTAT][7]).to eq(0) riot.tick end end it 'has bits 6 and 7 set after any underflow (and reset by an init)' do 3.times do riot[timer_register] = 0x01 expect(riot[INSTAT][6]).to eq(0) expect(riot[INSTAT][7]).to eq(0) interval.times { riot.tick } expect(riot[INSTAT][6]).to eq(1) expect(riot[INSTAT][7]).to eq(1) 10.times do 256.times { riot.tick } # interval now is 1 expect(riot[INSTAT][6]).to eq(1) expect(riot[INSTAT][7]).to eq(1) end end end it 'has bit 6 clear after it is read' do riot[timer_register] = 0x01 interval.times { riot.tick } expect(riot[INSTAT][6]).to eq(1) expect(riot[INSTAT][6]).to eq(0) end it 'does not have bit 7 affected by a read' do riot[timer_register] = 0x01 interval.times { riot.tick } expect(riot[INSTAT][7]).to eq(1) expect(riot[INSTAT][7]).to eq(1) end it '"However, the interval is automatically re-actived when reading from the INTIM register, ie. the timer does then continue to decrement at interval speed (originated at the current value)."' end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/spec/lib/ruby2600/cpu_spec.rb
spec/lib/ruby2600/cpu_spec.rb
require 'spec_helper' describe Ruby2600::CPU do subject(:cpu) { Ruby2600::CPU.new } CPU_FLAGS.each do |flag| it 'initializes with a readable #{flag} flag' do expect { cpu.send(flag) }.to_not raise_error end end %w'x y a s'.each do |register| it "initializes with a byte-size #{register} register" do expect(0..255).to cover(cpu.send(register)) end end describe '#reset' do before { cpu.memory = { 0xFFFC => 0x34, 0xFFFD => 0x12 } } it 'boots at the address on the RESET vector ($FFFC)' do cpu.reset expect(cpu.pc).to eq(0x1234) end end describe '#halted' do it 'needs to be tested' end describe '#tick' do it 'needs to be tested' end describe '#step' do before do # Most examples will run a single opcode from here cpu.pc = 0x0000 # Catch unexpected side effects randomize :a, :x, :y, :s, :n, :v, :i, :z, :c # Examples will refer to these values. Add, but don't change! cpu.memory = [] cpu.memory[0x0001] = 0xFE cpu.memory[0x0002] = 0xFF cpu.memory[0x0004] = 0x01 cpu.memory[0x0005] = 0x11 cpu.memory[0x0006] = 0x03 cpu.memory[0x0007] = 0x54 cpu.memory[0x000E] = 0xAC cpu.memory[0x0010] = 0x53 cpu.memory[0x0011] = 0xA4 cpu.memory[0x00A3] = 0xF5 cpu.memory[0x00A4] = 0xFF cpu.memory[0x00A5] = 0x33 cpu.memory[0x00A6] = 0x20 cpu.memory[0x00A7] = 0x01 cpu.memory[0x00A8] = 0xFE cpu.memory[0x00A9] = 0xFF cpu.memory[0x00B5] = 0x66 cpu.memory[0x00B6] = 0x02 cpu.memory[0x0100] = 0xAB cpu.memory[0x0151] = 0xB7 cpu.memory[0x0160] = 0xFF cpu.memory[0x0161] = 0x77 cpu.memory[0x0266] = 0xA4 cpu.memory[0x0311] = 0xB5 cpu.memory[0x1122] = 0x07 cpu.memory[0x1234] = 0x99 cpu.memory[0x1235] = 0xAA cpu.memory[0x1244] = 0xCC cpu.memory[0x1304] = 0xFF cpu.memory[0x1314] = 0x00 cpu.memory[0x1315] = 0xFF cpu.memory[0x1316] = 0x80 cpu.memory[0x2043] = 0x77 cpu.memory[0x2103] = 0x88 end def randomize(*attrs) attrs.each do |attr| value = attr =~ /[axys]/ ? rand(256) : [true, false].sample cpu.send "#{attr}=", value end end # Ensuring we deal well with page crossing and memory wraping it_does 'work on any memory position' do let(:code) { [0xEA] } # NOP let(:expected_a) { nil } end it_does 'work on any memory position' do let(:code) { [0xA9, 0x03] } # LDA #$03 let(:expected_a) { 0x03 } end it_does 'work on any memory position' do let(:code) { [0xAD, 0x34, 0x12] } # LDA $1234 let(:expected_a) { 0x99 } end # Full 650x instruction set context 'ADC' do before do cpu.a = 0xAC cpu.c = false cpu.d = false end context 'immediate' do before { cpu.memory[0..1] = 0x69, 0x22 } # ADC #$22 it_does 'advance PC by two' it_does 'take two cycles' it_does 'set A value', 0xCE it_does 'reset Z flag' it_does 'set N flag' it_does 'reset C flag' it_does 'reset V flag' context 'with_carry' do before { cpu.c = true } it_does 'set A value', 0xCF it_does 'reset C flag' end # http://www.6502.org/tutorials/vflag.html context 'Bruce Clark paper tests' do it_does 'add and set A/C/V', 0x01, 0x01, 0x02, false, false it_does 'add and set A/C/V', 0x01, 0xFF, 0x00, true, false it_does 'add and set A/C/V', 0x7F, 0x01, 0x80, false, true it_does 'add and set A/C/V', 0x80, 0xFF, 0x7F, true, true end context '2 - 10 = -8; no carry/overflow' do it_does 'add and set A/C/V', 0x02, 0xF6, 0xF8, false, false end context 'decimal mode' do before { cpu.d = true } context 'result <= 99' do before { cpu.a = 0x19 } it_does 'set A value', 0x41 it_does 'reset C flag' end context 'result > 99' do before { cpu.a = 0x78 } it_does 'set A value', 0x00 it_does 'set C flag' end end end context 'zero page' do before { cpu.memory[0..1] = 0x65, 0xA4 } # ADC $A4 it_does 'advance PC by two' it_does 'take three cycles' it_does 'set A value', 0xAB it_does 'set N flag' it_does 'set C flag' it_does 'reset V flag' end context 'zero page, x' do before do cpu.memory[0..1] = 0x75, 0xA5 # ADC $A5,X cpu.x = 0x10 end it_does 'advance PC by two' it_does 'take four cycles' it_does 'set A value', 0x12 it_does 'set C flag' context 'wrapping zero-page boundary' do before { cpu.x = 0x62 } it_does 'set A value', 0x00 it_does 'set C flag' it_does 'set Z flag' end end context 'absolute' do before do cpu.memory[0..2] = 0x6D, 0x34, 0x12 # ADC $1234 cpu.n = false end it_does 'advance PC by three' it_does 'take four cycles' it_does 'set A value', 0x45 it_does 'set C flag' end context 'absolute, x' do before do cpu.memory[0..2] = 0x7D, 0x34, 0x12 # ADC $1234,X cpu.x = 0x10 end it_does 'advance PC by three' it_does 'take four cycles' it_does 'set A value', 0x78 context 'crossing page boundary' do before { cpu.x = 0xD0 } it_does 'set A value', 0xAB it_does 'take five cycles' end context 'wrapping memory' do before { cpu.memory[0..2] = 0x7D, 0xF5, 0xFF } # ADC $FFF5,X it_does 'set A value', 0xBD end end context 'absolute, y' do before do cpu.memory[0..2] = 0x79, 0x34, 0x12 # ADC $1234,Y cpu.y = 0x10 end it_does 'advance PC by three' it_does 'take four cycles' it_does 'set A value', 0x78 context 'crossing page boundary' do before { cpu.y = 0xD0 } it_does 'set A value', 0xAB it_does 'take five cycles' end context 'wrapping memory' do before { cpu.memory[0..2] = 0x79, 0xF5, 0xFF } # ADC $FFF5,Y it_does 'set A value', 0xBD end end context '(indirect, x)' do before do cpu.memory[0..1] = 0x61, 0xA5 # ADC ($A5,X) cpu.x = 0x10 end it_does 'advance PC by two' it_does 'take six cycles' it_does 'set A value', 0x50 context 'wrapping around zero-page' do before { cpu.x = 0x60 } it_does 'set A value', 0x61 end end context '(indirect), y' do before do cpu.memory[0..1] = 0x71, 0xA5 # ADC ($A5),Y cpu.y = 0x10 end it_does 'advance PC by two' it_does 'take five cycles' it_does 'set A value', 0x23 context 'crossing page boundary' do before { cpu.y = 0xD0 } it_does 'set A value', 0x34 it_does 'take six cycles' end context 'wrapping memory' do before { cpu.memory[0..1] = 0x71, 0xA3} # ADC ($A3),Y it_does 'set A value', 0xBD end end end context 'AND' do before { cpu.a = 0b10101100 } # #$AC context 'immediate' do before { cpu.memory[0..1] = 0x29, 0x22 } # AND #$22 it_does 'advance PC by two' it_does 'take two cycles' it_does 'set A value', 0x20 it_does 'reset Z flag' it_does 'reset N flag' end context 'zero page' do before { cpu.memory[0..1] = 0x25, 0xA4 } # AND $A4 it_does 'advance PC by two' it_does 'take three cycles' it_does 'set A value', 0xAC end context 'zero page, x' do before do cpu.memory[0..1] = 0x35, 0xA5 # AND $A5,X cpu.x = 0x10 end it_does 'advance PC by two' it_does 'take four cycles' it_does 'set A value', 0x24 context 'wrapping around zero-page' do before { cpu.x = 0x60 } it_does 'set A value', 0x00 it_does 'set Z flag' end end context 'absolute' do before do cpu.memory[0..2] = 0x2D, 0x34, 0x12 # AND $1234 cpu.n = false end it_does 'advance PC by three' it_does 'take four cycles' it_does 'set A value', 0x88 it_does 'set N flag' end context 'absolute, x' do before do cpu.memory[0..2] = 0x3D, 0x34, 0x12 # AND $1234,X cpu.x = 0x10 end it_does 'advance PC by three' it_does 'take four cycles' it_does 'set A value', 0x8C context 'crossing page boundary' do before { cpu.x = 0xD0 } it_does 'set A value', 0xAC it_does 'take five cycles' end context 'wrapping memory' do before { cpu.memory[0..2] = 0x3D, 0xF5, 0xFF } # AND $FFF5,X it_does 'set A value', 0x00 end end context 'absolute, y' do before do cpu.memory[0..2] = 0x39, 0x34, 0x12 # AND $1234,Y cpu.y = 0x10 end it_does 'advance PC by three' it_does 'take four cycles' it_does 'set A value', 0x8C context 'crossing page boundary' do before { cpu.y = 0xD0 } it_does 'set A value', 0xAC it_does 'take five cycles' end context 'wrapping memory' do before { cpu.memory[0..2] = 0x39, 0xF5, 0xFF } # AND $FFF5,Y it_does 'set A value', 0x0 end end context '(indirect, x)' do before do cpu.memory[0..1] = 0x21, 0xA5 # AND ($A5,X) cpu.x = 0x10 end it_does 'advance PC by two' it_does 'take six cycles' it_does 'set A value', 0xA4 context 'wrapping around zero-page' do before { cpu.x = 0x60 } it_does 'set A value', 0xA4 end end context '(indirect), y' do before do cpu.memory[0..1] = 0x31, 0xA5 # AND ($A5),Y cpu.y = 0x10 end it_does 'advance PC by two' it_does 'take five cycles' it_does 'set A value', 0x24 context 'crossing page boundary' do before { cpu.y = 0xD0 } it_does 'set A value', 0x88 it_does 'take six cycles' end context 'wrapping memory' do before { cpu.memory[0..1] = 0x31, 0xA3} # AND ($A3),Y it_does 'set A value', 0x00 end end end context 'ASL' do context 'accumulator' do before do cpu.memory[0] = 0x0A # ASL A cpu.a = 0b11101110 end it_does 'advance PC by one' it_does 'take two cycles' it_does 'set A value', 0b11011100 it_does 'reset Z flag' it_does 'set C flag' it_does 'set N flag' context 'carry set' do before { cpu.c = true } it_does 'set A value', 0b11011100 # carry does not affect ASL end end context 'zero page' do before { cpu.memory[0..1] = 0x06, 0xA7 } # ASL $A7 it_does 'advance PC by two' it_does 'take five cycles' it_does 'set memory with value', 0x00A7, 0x02 it_does 'reset N flag' it_does 'reset C flag' it_does 'reset Z flag' end context 'zero page, x' do before do cpu.memory[0..1] = 0x16, 0xA5 # ASL $A5,X cpu.x = 0x11 end it_does 'advance PC by two' it_does 'take six cycles' it_does 'set memory with value', 0x00B6, 0x04 it_does 'reset N flag' it_does 'reset C flag' it_does 'reset Z flag' end context 'absolute' do before { cpu.memory[0..2] = 0x0E, 0x04, 0x13 } # ASL $1304 it_does 'advance PC by three' it_does 'take six cycles' it_does 'set memory with value', 0x1304, 0xFE it_does 'set N flag' it_does 'set C flag' it_does 'reset Z flag' end context 'absolute, x' do before do cpu.memory[0..2] = 0x1E, 0x04, 0x13 # ASL $1304,X cpu.x = 0x12 end it_does 'advance PC by three' it_does 'take seven cycles' it_does 'set memory with value', 0x1316, 0x00 it_does 'reset N flag' it_does 'set C flag' it_does 'set Z flag' end end context 'BCC' do it_behaves_like 'a branch instruction' do let(:opcode) { 0x90 } let(:flag) { :c } let(:branch_state) { false } end end context 'BCS' do it_behaves_like 'a branch instruction' do let(:opcode) { 0xB0 } let(:flag) { :c } let(:branch_state) { true } end end context 'BEQ' do it_behaves_like 'a branch instruction' do let(:opcode) { 0xF0 } let(:flag) { :z } let(:branch_state) { true } end end context 'BIT' do before { cpu.a = 0b10101100 } # #$AC context 'zero page' do before { cpu.memory[0..1] = 0x24, 0x11 } # BIT $11 it_does 'advance PC by two' it_does 'take three cycles' it_does 'set N flag' it_does 'reset Z flag' it_does 'reset V flag' it { expect{ cpu.step }.to_not change{ cpu.a } } context 'memory position with bit 6 set (even if AND result has it reset)' do before do cpu.memory[0..1] = 0x24, 0x07 # BIT $07 cpu.a = 0x00 end it_does 'set V flag' end context 'memory position with bit 7 set (even if AND result has it reset)' do before do cpu.memory[0..1] = 0x24, 0x11 # BIT $11 cpu.a = 0x00 end it_does 'set N flag' end context 'resulting in zero' do before do cpu.memory[0..1] = 0x24, 0xA8 # BIT $A8 cpu.a = 0x01 end it_does 'set Z flag' end end context 'absolute' do before { cpu.memory[0..2] = 0x2C, 0x22, 0x11 } # BIT $1122 it_does 'advance PC by three' it_does 'take four cycles' it_does 'reset N flag' it_does 'reset V flag' it_does 'reset Z flag' end end context 'BMI' do it_behaves_like 'a branch instruction' do let(:opcode) { 0x30 } let(:flag) { :n } let(:branch_state) { true } end end context 'BNE' do it_behaves_like 'a branch instruction' do let(:opcode) { 0xD0 } let(:flag) { :z } let(:branch_state) { false } end end context 'BPL' do it_behaves_like 'a branch instruction' do let(:opcode) { 0x10 } let(:flag) { :n } let(:branch_state) { false } end end context 'BRK' do before do cpu.memory[0x1234] = 0x00 # BRK cpu.memory[0xFFFE..0xFFFF] = 0x89, 0x67 # Interrupt vector cpu.pc = 0x1234 cpu.s = 0xF0 end it_does 'take seven cycles' it_does 'set memory with value', 0x01F0, 0x12 it_does 'set memory with value', 0x01EF, 0x35 it_does 'set S value', 0xED it_does 'set PC value', 0x6789 it_does 'set I flag' it_does 'set memory with P for various flag values', 0x01EE end context 'BVC' do it_behaves_like 'a branch instruction' do let(:opcode) { 0x50 } let(:flag) { :v } let(:branch_state) { false } end end context 'BVS' do it_behaves_like 'a branch instruction' do let(:opcode) { 0x70 } let(:flag) { :v } let(:branch_state) { true } end end context 'CLC' do before { cpu.memory[0] = 0x18 # SEC cpu.c = true } it_does 'reset C flag' end context 'CLD' do before { cpu.memory[0] = 0xD8 # CLD cpu.d = true } it_does 'reset D flag' end context 'CLI' do before { cpu.memory[0] = 0x58 # CLI cpu.i = true } it_does 'reset I flag' end context 'CLV' do before { cpu.memory[0] = 0xB8 # CLV cpu.v = true } it_does 'reset V flag' end context 'CMP' do before { cpu.a = 0xAC } context 'immediate' do before { cpu.memory[0..1] = 0xC9, 0x22 } # CMP #$22 it_does 'advance PC by two' it_does 'take two cycles' it_does 'reset Z flag' it_does 'set N flag' it_does 'set C flag' skip 'Z FLAG TEST' end context 'zero page' do before { cpu.memory[0..1] = 0xC5, 0xA4 } # CMP $A4 it_does 'advance PC by two' it_does 'take three cycles' it_does 'set N flag' it_does 'reset C flag' end context 'zero page, x' do before do cpu.memory[0..1] = 0xD5, 0xA5 # CMP $A5,X cpu.x = 0x10 end it_does 'advance PC by two' it_does 'take four cycles' it_does 'set C flag' context 'wrapping zero-page boundary' do before { cpu.x = 0x62 } it_does 'reset N flag' it_does 'set C flag' end end context 'absolute' do before do cpu.memory[0..2] = 0xCD, 0x34, 0x12 # CMP $1234 cpu.n = false end it_does 'advance PC by three' it_does 'take four cycles' it_does 'reset N flag' it_does 'set C flag' end context 'absolute, x' do before do cpu.memory[0..2] = 0xDD, 0x34, 0x12 # CMP $1234,X cpu.x = 0x10 end it_does 'advance PC by three' it_does 'take four cycles' it_does 'set N flag' it_does 'reset C flag' context 'crossing page boundary' do before { cpu.x = 0xD0 } it_does 'set N flag' it_does 'reset C flag' it_does 'take five cycles' end context 'wrapping memory' do before { cpu.memory[0..2] = 0xDD, 0xF5, 0xFF } # CMP $FFF5,X it_does 'set N flag' it_does 'set C flag' end end context 'absolute, y' do before do cpu.memory[0..2] = 0xD9, 0x34, 0x12 # CMP $1234,Y cpu.y = 0x10 end it_does 'advance PC by three' it_does 'take four cycles' it_does 'set N flag' it_does 'reset C flag' context 'crossing page boundary' do before { cpu.y = 0xD0 } it_does 'set N flag' it_does 'reset C flag' it_does 'take five cycles' end context 'wrapping memory' do before { cpu.memory[0..2] = 0xD9, 0xF5, 0xFF } # CMP $FFF5,Y it_does 'set N flag' it_does 'set C flag' end end context '(indirect, x)' do before do cpu.memory[0..1] = 0xC1, 0xA5 # CMP ($A5,X) cpu.x = 0x10 end it_does 'advance PC by two' it_does 'take six cycles' context 'wrapping around zero-page' do before { cpu.x = 0x60 } it_does 'set N flag' it_does 'reset C flag' end end context '(indirect), y' do before do cpu.memory[0..1] = 0xD1, 0xA5 # CMP ($A5),Y cpu.y = 0x10 end it_does 'advance PC by two' it_does 'take five cycles' it_does 'reset N flag' it_does 'set C flag' context 'crossing page boundary' do before { cpu.y = 0xD0 } it_does 'reset N flag' it_does 'set C flag' it_does 'take six cycles' end context 'wrapping memory' do before { cpu.memory[0..1] = 0xD1, 0xA8} # CMP ($A8),Y it_does 'reset N flag' it_does 'set C flag' it_does 'set Z flag' end end end context 'CPX' do context 'immediate' do before { cpu.memory[0..1] = 0xE0, 0xA5 } # CPX #$A5 it_does 'advance PC by two' it_does 'take two cycles' it_does 'compare and set flags', :x, 0xA5 end context 'zero page' do before { cpu.memory[0..1] = 0xE4, 0xA5 } # CPX $A5 it_does 'advance PC by two' it_does 'take three cycles' it_does 'compare and set flags', :x, 0x33 end context 'absolute' do before { cpu.memory[0..2] = 0xEC, 0x34, 0x12 } # CPX $1234 it_does 'advance PC by three' it_does 'take four cycles' it_does 'compare and set flags', :x, 0x99 end end context 'CPY' do context 'immediate' do before { cpu.memory[0..1] = 0xC0, 0xA3 } # CPY #$A3 it_does 'advance PC by two' it_does 'take two cycles' it_does 'compare and set flags', :y, 0xA3 end context 'zero page' do before { cpu.memory[0..1] = 0xC4, 0xA3 } # CPY $A3 it_does 'advance PC by two' it_does 'take three cycles' it_does 'compare and set flags', :y, 0xF5 end context 'absolute' do before { cpu.memory[0..2] = 0xCC, 0x44, 0x12 } # CPY $1234 it_does 'advance PC by three' it_does 'take four cycles' it_does 'compare and set flags', :y, 0xCC end end context 'DEC' do context 'zero page' do before { cpu.memory[0..1] = 0xC6, 0xA5 } # DEC $A5 it_does 'advance PC by two' it_does 'take five cycles' it_does 'set memory with value', 0xA5, 0x32 end context 'zero page, x' do before do cpu.memory[0..1] = 0xD6, 0xA5 # DEC $A5,X cpu.x = 0x10 end it_does 'advance PC by two' it_does 'take six cycles' it_does 'set memory with value', 0xB5, 0x65 context 'wrapping around zero-page' do before { cpu.x = 0x60 } it_does 'set memory with value', 0x05, 0x10 end end context 'absolute' do before do cpu.memory[0..2] = 0xCE, 0x34, 0x12 # DEC $1234 end it_does 'advance PC by three' it_does 'take six cycles' it_does 'set memory with value', 0x1234, 0x98 end context 'absolute, x' do before do cpu.memory[0..2] = 0xDE, 0x34, 0x12 # DEC $1234,X cpu.x = 0x10 end it_does 'advance PC by three' it_does 'take seven cycles' it_does 'set memory with value', 0x1244, 0xCB it_does 'set N flag' context 'crossing page boundary' do before { cpu.x = 0xE1 } it_does 'set memory with value', 0x1315, 0xFE it_does 'take seven cycles' it_does 'reset Z flag' end context 'wrapping memory' do before { cpu.memory[0..2] = 0xDE, 0xF4, 0xFF } # DEC $FFF5,X it_does 'set memory with value', 0x0004, 0x00 it_does 'set Z flag' end end end context 'DEX' do before do cpu.memory[0] = 0xCA # DEX cpu.x = 0x07 end it_does 'advance PC by one' it_does 'take two cycles' it_does 'set X value', 0x06 it_does 'reset Z flag' it_does 'reset N flag' context 'zero result' do before { cpu.x = 0x01 } it_does 'set Z flag' it_does 'reset N flag' end context 'negative result' do before { cpu.x = 0x00 } it_does 'set X value', 0xFF it_does 'reset Z flag' it_does 'set N flag' end end context 'DEY' do before do cpu.memory[0] = 0x88 # DEY cpu.y = 0x07 end it_does 'advance PC by one' it_does 'take two cycles' it_does 'set Y value', 0x06 it_does 'reset Z flag' it_does 'reset N flag' context 'zero result' do before { cpu.y = 0x01 } it_does 'set Z flag' it_does 'reset N flag' end context 'negative result' do before { cpu.y = 0x00 } it_does 'set Y value', 0xFF it_does 'reset Z flag' it_does 'set N flag' end end context 'EOR' do before { cpu.a = 0b10101100 } # #$AC context 'immediate' do before { cpu.memory[0..1] = 0x49, 0x22 } # EOR #$22 it_does 'advance PC by two' it_does 'take two cycles' it_does 'set A value', 0x8E it_does 'reset Z flag' it_does 'set N flag' context 'resulting positive' do before { cpu.a = 0x01 } it_does 'reset N flag' end context 'resulting zero' do before { cpu.a = 0x22 } it_does 'reset N flag' it_does 'set Z flag' end end context 'zero page' do before { cpu.memory[0..1] = 0x45, 0xA4 } # EOR $A4 it_does 'advance PC by two' it_does 'take three cycles' it_does 'set A value', 0x53 end context 'zero page, x' do before do cpu.memory[0..1] = 0x55, 0xA5 # EOR $A5,X cpu.x = 0x10 end it_does 'advance PC by two' it_does 'take four cycles' it_does 'set A value', 0xCA context 'wrapping around zero-page' do before { cpu.x = 0x60 } it_does 'set A value', 0xBD it_does 'reset Z flag' end end context 'absolute' do before do cpu.memory[0..2] = 0x4D, 0x34, 0x12 # EOR $1234 cpu.n = false end it_does 'advance PC by three' it_does 'take four cycles' it_does 'set A value', 0x35 it_does 'reset N flag' end context 'absolute, x' do before do cpu.memory[0..2] = 0x5D, 0x34, 0x12 # EOR $1234,X cpu.x = 0x10 end it_does 'advance PC by three' it_does 'take four cycles' it_does 'set A value', 0x60 context 'crossing page boundary' do before { cpu.x = 0xD0 } it_does 'set A value', 0x53 it_does 'take five cycles' end context 'wrapping memory' do before { cpu.memory[0..2] = 0x5D, 0xF5, 0xFF } # EOR $FFF5,X it_does 'set A value', 0xBD end end context 'absolute, y' do before do cpu.memory[0..2] = 0x59, 0x34, 0x12 # EOR $1234,Y cpu.y = 0x10 end it_does 'advance PC by three' it_does 'take four cycles' it_does 'set A value', 0x60 context 'crossing page boundary' do before { cpu.y = 0xD0 } it_does 'set A value', 0x53 it_does 'take five cycles' end context 'wrapping memory' do before { cpu.memory[0..2] = 0x59, 0xF5, 0xFF } # EOR $FFF5,Y it_does 'set A value', 0xBD end end context '(indirect, x)' do before do cpu.memory[0..1] = 0x41, 0xA5 # EOR ($A5,X) cpu.x = 0x10 end it_does 'advance PC by two' it_does 'take six cycles' it_does 'set A value', 0x08 context 'wrapping around zero-page' do before { cpu.x = 0x60 } it_does 'set A value', 0x19 end end context '(indirect), y' do before do cpu.memory[0..1] = 0x51, 0xA5 # EOR ($A5),Y cpu.y = 0x10 end it_does 'advance PC by two' it_does 'take five cycles' it_does 'set A value', 0xDB context 'crossing page boundary' do before { cpu.y = 0xD0 } it_does 'set A value', 0x24 it_does 'take six cycles' end context 'wrapping memory' do before { cpu.memory[0..1] = 0x51, 0xA3} # EOR ($A3),Y it_does 'set A value', 0xBD end end end context 'INC' do context 'zero page' do before { cpu.memory[0..1] = 0xE6, 0xA5 } # INC $A5 it_does 'advance PC by two' it_does 'take five cycles' it_does 'set memory with value', 0xA5, 0x34 end context 'zero page, x' do before do cpu.memory[0..1] = 0xF6, 0xA5 # INC $A5,X cpu.x = 0x10 end it_does 'advance PC by two' it_does 'take six cycles' it_does 'set memory with value', 0xB5, 0x67 context 'wrapping around zero-page' do before { cpu.x = 0x60 } it_does 'set memory with value', 0x05, 0x12 end end context 'absolute' do before do cpu.memory[0..2] = 0xEE, 0x34, 0x12 # INC $1234 end it_does 'advance PC by three' it_does 'take six cycles' it_does 'set memory with value', 0x1234, 0x9A end context 'absolute, x' do before do cpu.memory[0..2] = 0xFE, 0x34, 0x12 # INC $1234,X cpu.x = 0x10 end it_does 'advance PC by three' it_does 'take seven cycles' it_does 'set memory with value', 0x1244, 0xCD it_does 'set N flag' context 'crossing page boundary' do before { cpu.x = 0xE1 } it_does 'set memory with value', 0x1315, 0x00 it_does 'take seven cycles' it_does 'set Z flag' end context 'wrapping memory' do before { cpu.memory[0..2] = 0xFE, 0xF5, 0xFF } # INC $FFF5,X it_does 'set memory with value', 0x0005, 0x12 end end end context 'INX' do before do cpu.memory[0] = 0xE8 # INX cpu.x = 0x07 end it_does 'advance PC by one' it_does 'take two cycles' it_does 'set X value', 0x08 it_does 'reset Z flag' it_does 'reset N flag' context 'zero result' do before { cpu.x = 0xFF } it_does 'set Z flag' it_does 'reset N flag' it_does 'set X value', 0x00 end context 'negative result' do before { cpu.x = 0xA0 } it_does 'reset Z flag' it_does 'set N flag' end end context 'INY' do before do cpu.memory[0] = 0xC8 # INX cpu.y = 0x07 end it_does 'advance PC by one' it_does 'take two cycles' it_does 'set Y value', 0x08 it_does 'reset Z flag' it_does 'reset N flag' context 'zero result' do before { cpu.y = 0xFF } it_does 'set Z flag' it_does 'reset N flag' it_does 'set Y value', 0x00 end context 'negative result' do before { cpu.y = 0xA0 } it_does 'reset Z flag' it_does 'set N flag' end end context 'JMP' do context 'immediate' do before { cpu.memory[0..2] = 0x4C, 0x34, 0x12 } # JMP (1234) it_does 'set PC value', 0x1234 it_does 'preserve flags' end context 'indirect' do before { cpu.memory[0..2] = 0x6C, 0x34, 0x12 } # JMP ($1234) it_does 'set PC value', 0xAA99 it_does 'preserve flags' end context 'indirect mode bug' do skip 'not sure if will support' end end context 'JSR' do before do cpu.pc = 0x02FF cpu.memory[0x02FF..0x0301] = 0x20, 0x34, 0x12 # 02FF: JSR $1234 cpu.s = 0xF0 end it_does 'take six cycles' it_does 'preserve flags' it_does 'set PC value', 0x1234 it_does 'set S value', 0xEE it_does 'set memory with value', 0x01F0, 0x03 it_does 'set memory with value', 0x01EF, 0x01 end context 'LDA' do context 'immediate' do before do cpu.memory[0..1] = 0xA9, 0x22 # LDA #$22 cpu.z = true cpu.n = true end it_does 'advance PC by two' it_does 'take two cycles' it_does 'set A value', 0x22 it_does 'reset Z flag' it_does 'reset N flag' end context 'zero page' do before { cpu.memory[0..1] = 0xA5, 0xA5 } # LDA $A5 it_does 'advance PC by two' it_does 'take three cycles'
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
true
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/spec/lib/ruby2600/playfield_spec.rb
spec/lib/ruby2600/playfield_spec.rb
require 'spec_helper' describe Ruby2600::Playfield do let(:tia) { double 'tia', :reg => Array.new(64, 0), :scanline_stage => :visible } subject(:playfield) { Ruby2600::Playfield.new(tia, 0) } def scanline playfield.reset (0..159).map{ playfield.tick; playfield.pixel } end describe 'pixel' do it 'never outputs if COLUP0 is all zeros' do tia.reg[COLUP0] = 0 300.times { expect(playfield.pixel).to be_nil } end context 'drawing, reflection and score mode' do before do tia.reg[COLUPF] = 0xFF tia.reg[COLUP0] = 0x11 tia.reg[COLUP1] = 0x22 tia.reg[PF0] = 0b01000101 tia.reg[PF1] = 0b01001011 tia.reg[PF2] = 0b01001011 end it 'generates symmetrical playfield if bit 0 (reflect) is set' do tia.reg[CTRLPF] = 0b00000001 expect(scanline).to eq([nil, nil, nil, nil, nil, nil, nil, nil, 0xFF, 0xFF, 0xFF, 0xFF, nil, nil, nil, nil, nil, nil, nil, nil, 0xFF, 0xFF, 0xFF, 0xFF, nil, nil, nil, nil, nil, nil, nil, nil, 0xFF, 0xFF, 0xFF, 0xFF, nil, nil, nil, nil, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, nil, nil, nil, nil, 0xFF, 0xFF, 0xFF, 0xFF, nil, nil, nil, nil, nil, nil, nil, nil, 0xFF, 0xFF, 0xFF, 0xFF, nil, nil, nil, nil, nil, nil, nil, nil, 0xFF, 0xFF, 0xFF, 0xFF, nil, nil, nil, nil, nil, nil, nil, nil, 0xFF, 0xFF, 0xFF, 0xFF, nil, nil, nil, nil, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, nil, nil, nil, nil, 0xFF, 0xFF, 0xFF, 0xFF, nil, nil, nil, nil, nil, nil, nil, nil, 0xFF, 0xFF, 0xFF, 0xFF, nil, nil, nil, nil, nil, nil, nil, nil, 0xFF, 0xFF, 0xFF, 0xFF, nil, nil, nil, nil, nil, nil, nil, nil]) end it 'uses player colors for playfield if bit 1 is set (score mode)' do tia.reg[CTRLPF] = 0b00000010 expect(scanline).to eq([nil, nil, nil, nil, nil, nil, nil, nil, 0x11, 0x11, 0x11, 0x11, nil, nil, nil, nil, nil, nil, nil, nil, 0x11, 0x11, 0x11, 0x11, nil, nil, nil, nil, nil, nil, nil, nil, 0x11, 0x11, 0x11, 0x11, nil, nil, nil, nil, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, nil, nil, nil, nil, 0x11, 0x11, 0x11, 0x11, nil, nil, nil, nil, nil, nil, nil, nil, 0x11, 0x11, 0x11, 0x11, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, 0x22, 0x22, 0x22, 0x22, nil, nil, nil, nil, nil, nil, nil, nil, 0x22, 0x22, 0x22, 0x22, nil, nil, nil, nil, nil, nil, nil, nil, 0x22, 0x22, 0x22, 0x22, nil, nil, nil, nil, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, nil, nil, nil, nil, 0x22, 0x22, 0x22, 0x22, nil, nil, nil, nil, nil, nil, nil, nil, 0x22, 0x22, 0x22, 0x22, nil, nil, nil, nil]) end it 'combines score mode and reflect' do tia.reg[CTRLPF] = 0b00000011 expect(scanline).to eq([nil, nil, nil, nil, nil, nil, nil, nil, 0x11, 0x11, 0x11, 0x11, nil, nil, nil, nil, nil, nil, nil, nil, 0x11, 0x11, 0x11, 0x11, nil, nil, nil, nil, nil, nil, nil, nil, 0x11, 0x11, 0x11, 0x11, nil, nil, nil, nil, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, nil, nil, nil, nil, 0x11, 0x11, 0x11, 0x11, nil, nil, nil, nil, nil, nil, nil, nil, 0x11, 0x11, 0x11, 0x11, nil, nil, nil, nil, nil, nil, nil, nil, 0x22, 0x22, 0x22, 0x22, nil, nil, nil, nil, nil, nil, nil, nil, 0x22, 0x22, 0x22, 0x22, nil, nil, nil, nil, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, nil, nil, nil, nil, 0x22, 0x22, 0x22, 0x22, nil, nil, nil, nil, nil, nil, nil, nil, 0x22, 0x22, 0x22, 0x22, nil, nil, nil, nil, nil, nil, nil, nil, 0x22, 0x22, 0x22, 0x22, nil, nil, nil, nil, nil, nil, nil, nil]) end end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/spec/lib/ruby2600/cart_spec.rb
spec/lib/ruby2600/cart_spec.rb
require 'spec_helper' describe Ruby2600::Cart do let(:cart_4K) { Ruby2600::Cart.new(path_for_ROM :hello) } let(:cart_2K) { Ruby2600::Cart.new(path_for_ROM :hello2k) } it 'silently ignore writes' do old_value = cart_4K[0x0000] cart_4K[0x0000] = rand(256) expect(cart_4K[0x0000]).to eq(old_value) end it 'loads a 2K ROM' do expect(cart_2K[0x0000]).to eq(0xA9) # _000: LDA #02 (first instruction) expect(cart_2K[0x0001]).to eq(0x02) expect(cart_2K[0x07FE]).to eq(0x00) # _FFE: word $F800 (BRK vector) expect(cart_2K[0x07FF]).to eq(0XF8) end it 'loads a 4K ROM' do expect(cart_4K[0x0000]).to eq(0xA9) # _000: LDA #02 (first instruction) expect(cart_4K[0x0001]).to eq(0x02) expect(cart_4K[0x0FFE]).to eq(0x00) # _FFE: word $F000 (BRK vector) expect(cart_4K[0x0FFF]).to eq(0XF0) end it 'maps a 2K ROM as a doubled 4k' do 0x0000.upto(0x07FF) do |addr| expect(cart_2K[addr]).to eq(cart_2K[addr + 2048]) end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/spec/lib/ruby2600/missile_spec.rb
spec/lib/ruby2600/missile_spec.rb
require 'spec_helper' describe Ruby2600::Missile do let(:tia) { double 'tia', :reg => Array.new(64, 0), :scanline_stage => :visible } subject(:missile) { Ruby2600::Missile.new(tia, 0) } context 'missile 1' do subject(:missile1) { Ruby2600::Missile.new(tia, 1) } before do tia.reg[ENAM1] = 0 tia.reg[COLUP0] = 0x00 tia.reg[COLUP1] = 0xFF missile.reset 160.times { missile1.tick } end it 'never outputs if ENAM1 is disabled' do expect(pixels(missile1, 1, 160)).not_to include(0xFF) end it 'generates some output if ENAM1 is enabled' do tia.reg[ENAM1] = rand(256) | 0b10 expect(pixels(missile1, 1, 160)).to include(0xFF) end end describe 'pixel' do before do tia.reg[COLUP0] = rand(255) + 1 end it 'never outputs if ENAM0 is disabled' do tia.reg[ENAM0] = 0 expect(pixels(missile, 1, 300)).to eq(Array.new(300)) end it 'generates some output if ENAM0 is enabled' do tia.reg[ENAM0] = rand(256) | 0b10 expect(pixels(missile, 1, 300)).to include(tia.reg[COLUP0]) end context 'drawing (strobe)' do let(:color) { [rand(255) + 1] } before do # Cleanup and pick a random position tia.reg[ENAM0] = 0 rand(160).times { missile.tick } # Preemptive strobe (to ensure we don't have retriggering leftovers) missile.reset 80.times { missile.tick } # Setup tia.reg[ENAM0] = 0b10 tia.reg[COLUP0] = color[0] end context 'one copy' do before do tia.reg[NUSIZ0] = 0 missile.reset 4.times { missile.tick } # 4-bit delay end it 'does not draw anything on current scanline' do expect(pixels(missile, 1, 160)).to eq(Array.new(160)) end it 'draws after a full scanline (160pixels) + 4-bit delay' do 160.times { missile.tick } expect(pixels(missile, 1, 160)).to eq(color + Array.new(159)) end it 'draws again on subsequent scanlines' do 320.times { missile.tick } 10.times { expect(pixels(missile, 1, 160)).to eq(color + Array.new(159)) } end end context 'two copies, close' do before do tia.reg[NUSIZ0] = 1 missile.reset 4.times { missile.tick } end it 'onlys draw second copy on current scanline (after 4 bit delay)' do expect(pixels(missile, 1, 24)).to eq(Array.new(16) + color + Array.new(7)) end it 'draws both copies on subsequent scanlines' do 160.times { missile.tick } expect(pixels(missile, 1, 24)).to eq(color + Array.new(15) + color + Array.new(7)) end end context 'two copies, medium' do before do tia.reg[NUSIZ0] = 2 missile.reset 4.times { missile.tick } end it 'onlys draw second copy on current scanline (after 4 bit delay)' do expect(pixels(missile, 1, 40)).to eq(Array.new(32) + color + Array.new(7)) end it 'draws both copies on subsequent scanlines' do 160.times { missile.tick } expect(pixels(missile, 1, 40)).to eq(color + Array.new(7) + Array.new(24) + color + Array.new(7)) end end context 'three copies, close' do before do tia.reg[NUSIZ0] = 3 missile.reset 4.times { missile.tick } end it 'onlys draw second and third copy on current scanline (after 4 bit delay)' do expect(pixels(missile, 1, 40)).to eq(Array.new(16) + color + Array.new(7) + Array.new(8) + color + Array.new(7)) end it 'draws three copies on subsequent scanlines' do 160.times { missile.tick } expect(pixels(missile, 1, 40)).to eq(color + Array.new(7) + Array.new(8) + color + Array.new(7) + Array.new(8) + color + Array.new(7)) end end context 'two copies, wide' do before do tia.reg[NUSIZ0] = 4 missile.reset 4.times { missile.tick } end it 'onlys draw second copy on current scanline (after 4 bit delay)' do expect(pixels(missile, 1, 72)).to eq(Array.new(64) + color + Array.new(7)) end it 'draws both copies on subsequent scanlines' do 160.times { missile.tick } expect(pixels(missile, 1, 72)).to eq(color + Array.new(7) + Array.new(56) + color + Array.new(7)) end end context 'three copies, medium' do before do tia.reg[NUSIZ0] = 6 missile.reset 4.times { missile.tick } end it 'onlys draw second and third copy on current scanline (after 4 bit delay)' do expect(pixels(missile, 1, 72)).to eq(Array.new(32) + color + Array.new(7) + Array.new(24) + color + Array.new(7)) end it 'draws three copies on subsequent scanlines' do 160.times { missile.tick } expect(pixels(missile, 1, 72)).to eq(color + Array.new(7) + Array.new(24) + color + Array.new(7) + Array.new(24) + color + Array.new(7)) end context '2x' do before { tia.reg[NUSIZ0] = 0b00010110 } it 'draws 3 copies with size 2' do 160.times { missile.tick } expect(pixels(missile, 1, 160)).to eq(scanline_with_object(2, color[0], 3)) end end context '4x' do before { tia.reg[NUSIZ0] = 0b00100110 } it 'draws 3 copies with size 4' do 160.times { missile.tick } expect(pixels(missile, 1, 160)).to eq(scanline_with_object(4, color[0], 3)) end end context '8x' do before { tia.reg[NUSIZ0] = 0b00110110 } it 'draws 3 copies with size 8' do 160.times { missile.tick } expect(pixels(missile, 1, 160)).to eq(scanline_with_object(8, color[0], 3)) end end end end end describe '#reset_to' do let(:player) { Ruby2600::Player.new(tia, 0) } before do rand(160).times { player.tick } end it "does not affect the player's counter" do expect { missile.reset_to player }.to_not change { player.value } end it "sets both objects to the same clock phase (i.e., same value without drifting)" do missile.reset_to player 4.times do missile.tick player.tick expect(missile.value).to eq(player.value) end end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/spec/lib/ruby2600/player_spec.rb
spec/lib/ruby2600/player_spec.rb
require 'spec_helper' describe Ruby2600::Player do let(:tia) { double 'tia', :reg => Array.new(64, 0), :scanline_stage => :visible } subject(:player) { Ruby2600::Player.new(tia, 0) } context 'player 1' do subject(:player1) { Ruby2600::Player.new(tia, 1) } before do tia.reg[GRP0] = 0x00 tia.reg[COLUP0] = 0x00 tia.reg[COLUP1] = 0xFF player1.reset 160.times { player1.tick } end it 'does not draw anything without GRP1' do expect(pixels(player1, 1, 160)).not_to include(0xFF) end it 'draws if GRP1 is set' do tia.reg[GRP1] = 0xFF expect(pixels(player1, 1, 160)).to include(0xFF) end end describe 'pixel' do it 'never outputs if GRP0 is all zeros' do tia.reg[GRP0] = 0 300.times do player.tick expect(player.pixel).to be_nil end end context 'drawing (strobe, NUSIZ0, REFP0)' do COLOR = 2 * (rand(127) + 1) PIXELS = [COLOR, COLOR, nil, nil, COLOR, nil, COLOR, nil] PIXELS_2X = PIXELS.map { |p| [p, p] }.flatten PIXELS_4X = PIXELS_2X.map { |p| [p, p] }.flatten before do # Cleanup and pick a random position tia.reg[GRP0] = 0 rand(160).times { player.tick } # Preemptive strobe (to ensure we don't have retriggering leftovers) player.reset 80.times { player.tick } # Setup tia.reg[GRP0] = 0b11001010 tia.reg[COLUP0] = COLOR end context 'one copy' do before do tia.reg[NUSIZ0] = 0 player.reset 5.times { player.tick } end it 'does not draw anything on current scanline' do expect(pixels(player, 1, 160)).to eq(Array.new(160)) end it 'draws after a full scanline (160pixels) + 5-bit delay' do 160.times { player.tick } expect(pixels(player, 1, 8)).to eq(PIXELS) end it 'draws again on subsequent scanlines' do 320.times { player.tick } 10.times { expect(pixels(player, 1, 160)).to eq(PIXELS + Array.new(152)) } end end context 'two copies, close' do before do tia.reg[NUSIZ0] = 1 player.reset 5.times { player.tick } end it 'onlys draw second copy on current scanline (after 5 bit delay)' do expect(pixels(player, 1, 24)).to eq(Array.new(16) + PIXELS) end it 'draws both copies on subsequent scanlines' do 160.times { player.tick } expect(pixels(player, 1, 24)).to eq(PIXELS + Array.new(8) + PIXELS) end end context 'two copies, medium' do before do tia.reg[NUSIZ0] = 2 player.reset 5.times { player.tick } end it 'onlys draw second copy on current scanline (after 5 bit delay)' do expect(pixels(player, 1, 40)).to eq(Array.new(32) + PIXELS) end it 'draws both copies on subsequent scanlines' do 160.times { player.tick } expect(pixels(player, 1, 40)).to eq(PIXELS + Array.new(24) + PIXELS) end end context 'three copies, close' do before do tia.reg[NUSIZ0] = 3 player.reset 5.times { player.tick } end it 'onlys draw second and third copy on current scanline (after 5 bit delay)' do expect(pixels(player, 1, 40)).to eq(Array.new(16) + PIXELS + Array.new(8) + PIXELS) end it 'draws three copies on subsequent scanlines' do 160.times { player.tick } expect(pixels(player, 1, 40)).to eq(PIXELS + Array.new(8) + PIXELS + Array.new(8) + PIXELS) end end context 'two copies, wide' do before do tia.reg[NUSIZ0] = 4 player.reset 5.times { player.tick } end it 'onlys draw second copy on current scanline (after 5 bit delay)' do expect(pixels(player, 1, 72)).to eq(Array.new(64) + PIXELS) end it 'draws both copies on subsequent scanlines' do 160.times { player.tick } expect(pixels(player, 1, 72)).to eq(PIXELS + Array.new(56) + PIXELS) end end context 'one copy, double size' do before do tia.reg[NUSIZ0] = 5 player.reset 5.times { player.tick } end it 'does not draw anything on current scanline' do expect(pixels(player, 1, 160)).to eq(Array.new(160)) end it 'draws on subsequent scanlines' do 160.times { player.tick } expect(pixels(player, 1, 160)).to eq(PIXELS_2X + Array.new(144)) end end context 'three copies, medium' do before do tia.reg[NUSIZ0] = 6 player.reset 5.times { player.tick } end it 'onlys draw second and third copy on current scanline (after 5 bit delay)' do expect(pixels(player, 1, 72)).to eq(Array.new(32) + PIXELS + Array.new(24) + PIXELS) end it 'draws three copies on subsequent scanlines' do 160.times { player.tick } expect(pixels(player, 1, 72)).to eq(PIXELS + Array.new(24) + PIXELS + Array.new(24) + PIXELS) end context 'with REFP0 set' do before { tia.reg[REFP0] = rand(256) | 0b1000 } it 'reflects the drawing' do 160.times { player.tick } expect(pixels(player, 1, 72)).to eq(PIXELS.reverse + Array.new(24) + PIXELS.reverse + Array.new(24) + PIXELS.reverse) end end end context 'one copy, quad size' do before do tia.reg[NUSIZ0] = 7 player.reset 5.times { player.tick } end it 'does not draw anything on current scanline' do expect(pixels(player, 1, 160)).to eq(Array.new(160)) end it 'draws on subsequent scanlines' do 160.times { player.tick } expect(pixels(player, 1, 160)).to eq(PIXELS_4X + Array.new(128)) end context 'with REFP0 set' do before { tia.reg[REFP0] = rand(256) | 0b1000 } it 'reflects the drawing' do 160.times { player.tick } expect(pixels(player, 1, 160)).to eq(PIXELS_4X.reverse + Array.new(128)) end end end context 'one copy, double size with missile size set' do before do tia.reg[NUSIZ0] = 0b00110101 player.reset 5.times { player.tick } end it 'does not be affected (should draw on subsequent scanlines)' do 160.times { player.tick } expect(pixels(player, 1, 160)).to eq(PIXELS_2X + Array.new(144)) end end skip 'VDELPn test' skip 'dynamic change of GRPn/REFPn test' end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/spec/lib/ruby2600/bus_spec.rb
spec/lib/ruby2600/bus_spec.rb
require 'spec_helper' describe Ruby2600::Bus do let(:cpu) { double('cpu', :memory= => nil, :reset => nil) } let(:tia) { double('tia', :cpu= => nil, :riot= => nil, :reg => Array.new(64, rand(256))) } let(:cart) { double('cart') } let(:riot) { double('riot', :portA= => nil, :portB= => nil) } subject(:bus) { Ruby2600::Bus.new(cpu, tia, cart, riot) } # 6507 address lines (bits) A7 & A12 select which chip (TIA/RIOT/cart ROM) # will be read/written (and line A9 selects betwen RIOT's RAM and I/O+Timer). # See: http://nocash.emubase.de/2k6specs.htm#memorymirrors or # http://atariage.com/forums/topic/192418-mirrored-memory ALL_ADDRESSES = (0x0000..0xFFFF).to_a CART_ADDRESSES = ALL_ADDRESSES.select { |a| a[12] == 1 } TIA_ADDRESSES = ALL_ADDRESSES.select { |a| a[12] == 0 && a[7] == 0 } RIOT_IOT_ADDRESSES = ALL_ADDRESSES.select { |a| a[12] == 0 && a[9] == 1 && a[7] == 1 } RIOT_RAM_ADDRESSES = ALL_ADDRESSES.select { |a| a[12] == 0 && a[9] == 0 && a[7] == 1 } context 'initialization' do it 'wires itself as a memory proxy for CPU' do expect(cpu).to receive(:memory=).with(instance_of(Ruby2600::Bus)) bus end it 'wires TIA to CPU (so it can drive the CPU timing)' do expect(tia).to receive(:cpu=).with(cpu) bus end it 'wires TIA to RIOT (so it can drive the timers)' do expect(tia).to receive(:riot=).with(riot) bus end it 'resets CPU' do expect(cpu).to receive(:reset) bus end it 'puts all switches and inputs in default (reset/released) position' do # FIXME button 0 (on TIA) expect(riot).to receive(:portA=).with(0b11111111) expect(riot).to receive(:portB=).with(0b11111111) bus end end describe 'p0_joystick' do before do bus.p0_joystick_up = false bus.p0_joystick_down = false bus.p0_joystick_left = false bus.p0_joystick_right = false end context 'normal directions' do it_does 'set bits on RIOT port after switch is set/pressed', :portA, 0b11101111, :p0_joystick_up it_does 'set bits on RIOT port after switch is set/pressed', :portA, 0b11011111, :p0_joystick_down it_does 'set bits on RIOT port after switch is set/pressed', :portA, 0b10111111, :p0_joystick_left it_does 'set bits on RIOT port after switch is set/pressed', :portA, 0b01111111, :p0_joystick_right it_does 'set bits on RIOT port after switch is reset/released', :portA, 0b11111111, :p0_joystick_up it_does 'set bits on RIOT port after switch is reset/released', :portA, 0b11111111, :p0_joystick_down it_does 'set bits on RIOT port after switch is reset/released', :portA, 0b11111111, :p0_joystick_left it_does 'set bits on RIOT port after switch is reset/released', :portA, 0b11111111, :p0_joystick_right end context 'diagonal left + (up|down)' do before { bus.p0_joystick_left = true } it_does 'set bits on RIOT port after switch is set/pressed', :portA, 0b10101111, :p0_joystick_up it_does 'set bits on RIOT port after switch is reset/released', :portA, 0b10111111, :p0_joystick_up it_does 'set bits on RIOT port after switch is set/pressed', :portA, 0b10011111, :p0_joystick_down it_does 'set bits on RIOT port after switch is reset/released', :portA, 0b10111111, :p0_joystick_down end context 'diagonal right + (up|down)' do before { bus.p0_joystick_right = true } it_does 'set bits on RIOT port after switch is set/pressed', :portA, 0b01101111, :p0_joystick_up it_does 'set bits on RIOT port after switch is reset/released', :portA, 0b01111111, :p0_joystick_up it_does 'set bits on RIOT port after switch is set/pressed', :portA, 0b01011111, :p0_joystick_down it_does 'set bits on RIOT port after switch is reset/released', :portA, 0b01111111, :p0_joystick_down end context 'fire button' do it 'puts TIA input port 4 on low when pressed' do expect(tia).to receive(:set_port_level).with(4, :low) bus.p0_joystick_fire = true end it 'puts TIA input port 4 on high when released' do expect(tia).to receive(:set_port_level).with(4, :high) bus.p0_joystick_fire = false end end end context 'console switches' do before do bus.color_bw_switch = false bus.reset_switch = false bus.select_switch = false bus.p0_difficulty_switch = false bus.p1_difficulty_switch = false end context 'single-switch press/release' do it_does 'set bits on RIOT port after switch is set/pressed', :portB, 0b11111110, :reset_switch it_does 'set bits on RIOT port after switch is set/pressed', :portB, 0b11111101, :select_switch it_does 'set bits on RIOT port after switch is set/pressed', :portB, 0b11110111, :color_bw_switch it_does 'set bits on RIOT port after switch is set/pressed', :portB, 0b10111111, :p0_difficulty_switch it_does 'set bits on RIOT port after switch is set/pressed', :portB, 0b01111111, :p1_difficulty_switch it_does 'set bits on RIOT port after switch is reset/released', :portB, 0b11111111, :reset_switch it_does 'set bits on RIOT port after switch is reset/released', :portB, 0b11111111, :select_switch it_does 'set bits on RIOT port after switch is reset/released', :portB, 0b11111111, :color_bw_switch it_does 'set bits on RIOT port after switch is reset/released', :portB, 0b11111111, :p0_difficulty_switch it_does 'set bits on RIOT port after switch is reset/released', :portB, 0b11111111, :p1_difficulty_switch end context 'multiple switches' do context 'P1 difficulty set (A)' do before { bus.p1_difficulty_switch = true } it_does 'set bits on RIOT port after switch is set/pressed', :portB, 0b01111101, :select_switch it_does 'set bits on RIOT port after switch is reset/released', :portB, 0b01111111, :select_switch end context 'everything but reset set/pressed' do before do bus.select_switch = true bus.color_bw_switch = true bus.p0_difficulty_switch = true bus.p1_difficulty_switch = true end it_does 'set bits on RIOT port after switch is set/pressed', :portB, 0b00110100, :reset_switch it_does 'set bits on RIOT port after switch is reset/released', :portB, 0b00110101, :reset_switch end end end context 'CPU read/write' do # We need to check if reads/writes to the bus will read/write the # correct chip, but with a 64K-range, RSpec expectations will take # too long. Instead, we'll use arrays as chip stubs. let(:cart) { Array.new(4096) { rand(256) } } let(:tia) { Array.new(32) { rand(256) } } let(:riot) { Array.new(768) { rand(256) } } before do allow(tia).to receive :cpu= allow(tia).to receive :riot= allow(riot).to receive :portA= allow(riot).to receive :portB= end describe '#read' do it 'translates TIA mirror reads to 30-3F' do TIA_ADDRESSES.each do |a| expect(bus[a]).to eq(tia[a & 0b1111 | 0b110000]) end end it 'translates RAM mirror reads to RIOT $00-$7F' do RIOT_RAM_ADDRESSES.each do |a| expect(bus[a]).to eq(riot[a & 0b0000000001111111]) end end it 'translates I/O and timer mirror reads to RIOT $0280-$02FF' do RIOT_IOT_ADDRESSES.each do |a| expect(bus[a]).to eq(riot[a & 0b0000001011111111]) end end it 'translates cart mirror reads to 0000-0FFF (4Kbytes)' do CART_ADDRESSES.each do |a| expect(bus[a]).to eq(cart[a & 0b0000111111111111]) end end end describe '#write' do it 'translates TIA mirror writes to 00-3F' do TIA_ADDRESSES.each do |a| value = rand(256) bus[a] = value expect(tia[a & 0b0000000000111111]).to eq(value) end end it 'translates RAM mirror writes to RIOT $00-$FF' do RIOT_RAM_ADDRESSES.each do |a| value = rand(256) bus[a] = value expect(riot[a & 0b0000000001111111]).to eq(value) end end it 'translates I/O and timer mirror writes to RIOT $0280-$02FF' do RIOT_IOT_ADDRESSES.each do |a| value = rand(256) bus[a] = value expect(riot[a & 0b0000001011111111]).to eq(value) end end it 'translates cart mirror writes (some are not ROM-only) to 0000-0FFF (4Kbytes)' do CART_ADDRESSES.each do |a| value = rand(256) bus[a] = value expect(cart[a & 0b0000111111111111]).to eq(value) end end end end skip '2K carts / SARA / RIOT details from http://atariage.com/forums/topic/192418-mirrored-memory/' end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/spec/lib/ruby2600/tia_spec.rb
spec/lib/ruby2600/tia_spec.rb
require 'spec_helper' describe Ruby2600::TIA do subject(:tia) do tia = Ruby2600::TIA.new tia.cpu = double('cpu', :tick => nil, :halted= => nil) tia.riot = double('riot', :tick => nil) # Make registers accessible (for easier testing) def tia.reg @reg end tia end def clear_tia_registers 0x3F.downto(0) { |reg| tia[reg] = 0 } end describe '#initialize' do it 'initializes with random values on registers' do registers1 = Ruby2600::TIA.new.instance_variable_get(:@reg) registers2 = tia.instance_variable_get(:@reg) expect(registers1).not_to eq(registers2) end it "initializes with valid (byte-size) values on registers" do tia.instance_variable_get(:@reg).each do |register_value| expect(0..255).to cover register_value end end end describe '#topmost_pixel' do before do tia[COLUBK] = 0xBB tia[COLUPF] = 0xFF tia[PF0] = 0xF0 tia[PF1] = 0xFF tia[PF2] = 0xFF end context 'CTRLPF priority bit clear' do before { tia[CTRLPF] = rand(256) & 0b011 } it { expect(tia).to be_using_priority [:p0, :m0, :p1, :m1, :bl, :pf] } end context 'CTRLPF priority bit set' do before { tia[CTRLPF] = rand(256) | 0b100 } it { expect(tia).to be_using_priority [:pf, :bl, :p0, :m0, :p1, :m1] } end # This code tests that, for an ordered list of graphic objects, # the first one that generates color is the topmost_pixel # FIXME: the warning for the old syntax shows the smell of an overly complicated test class Ruby2600::TIA def using_priority?(enabled, disabled = []) # Makes color = order in list for enabled objects (and nil for disabled) enabled.count.times { |i| turn_on(enabled[i], i) } disabled.each { |p| turn_off(p) } # The first object (color = 0) should be the topmost... return false unless topmost_pixel == 0 # ...and we disable it to recursively check the second, third, etc. first = enabled.shift using_priority?(enabled, disabled << first) if enabled.any? # Also: if all of them are disabled, the background color should be used turn_off first topmost_pixel == @reg[COLUBK] end def turn_on(object, color) instance_variable_get("@#{object}").stub(:pixel).and_return(color) end def turn_off(object) instance_variable_get("@#{object}").stub(:pixel).and_return(nil) end end end describe '#vertical_blank?' do context 'VBLANK bit set' do before { tia[VBLANK] = rand_with_bit(1, :set) } it { expect(tia.vertical_blank?).to be_truthy } end context 'VBLANK bit clear' do before { tia[VBLANK] = rand_with_bit(1, :clear) } it { expect(tia.vertical_blank?).to be_falsey } end end describe '#[]=' do [ VSYNC, VBLANK, RSYNC, COLUP0, COLUP1, COLUPF, COLUBK, REFP0, REFP1, PF0, PF1, PF2, AUDC0, AUDC1, AUDF0, AUDF1, AUDV0, AUDV1, GRP0, GRP1, ENAM0, ENAM1, ENABL, HMP0, HMP1, HMM0, HMM1, HMBL, VDELP0, VDELP1, VDELBL ].each do |r| it "stores the value for #{r}" do value = rand(256) tia[r] = value expect(tia.reg[r]).to eq(value) end end # This registers have the bits 6, 7 protected from writing [ NUSIZ0, NUSIZ1, CTRLPF ].each do |r| it "stores the value for #{r}" do value = rand(63) tia[r] = value expect(tia.reg[r]).to eq(value) end end [ WSYNC, RESP0, RESP1, RESM0, RESM1, RESBL, HMOVE, HMCLR, CXCLR, CXM0P, CXM1P, CXP0FB, CXP1FB, CXM0FB, CXM1FB, CXBLPF, CXPPMM, INPT0, INPT1, INPT2, INPT3, INPT4, INPT5 ].each do |r| it "does not store the value for #{r}" do value = rand(256) expect(tia.reg).not_to receive(:[]=).with(r, value) tia[r] = value end end end context 'positioning' do 0.upto 1 do |n| describe "RESMP#{n}" do let(:player) { tia.instance_variable_get "@p#{n}" } let(:missile) { tia.instance_variable_get "@m#{n}" } it "resets m#{n}'s counter to p#{n}'s when strobed" do expect(missile).to receive(:reset_to).with(player) tia[RESMP0 + n] = rand(256) end end end end context 'collisions' do describe 'CXCLR' do before do CXM0P.upto(CXPPMM) { |flag_reg| tia.reg[flag_reg] = rand(256) } end it 'resets flags when written' do tia[CXCLR] = 0 expect(tia[CXM0P][6]).to eq(0) expect(tia[CXM0P][7]).to eq(0) expect(tia[CXM1P][6]).to eq(0) expect(tia[CXM1P][7]).to eq(0) expect(tia[CXP0FB][6]).to eq(0) expect(tia[CXP0FB][7]).to eq(0) expect(tia[CXP1FB][6]).to eq(0) expect(tia[CXP1FB][7]).to eq(0) expect(tia[CXM0FB][6]).to eq(0) expect(tia[CXM0FB][7]).to eq(0) expect(tia[CXM1FB][6]).to eq(0) expect(tia[CXM1FB][7]).to eq(0) # Bit 6 of CXBLPF is not used expect(tia[CXBLPF][7]).to eq(0) expect(tia[CXPPMM][6]).to eq(0) expect(tia[CXPPMM][7]).to eq(0) end end describe '#update_collision_flags' do it_does 'update collision register bit for objects', CXM0P, 6, :m0, :p0 it_does 'update collision register bit for objects', CXM0P, 7, :m0, :p1 it_does 'update collision register bit for objects', CXM1P, 6, :m1, :p1 it_does 'update collision register bit for objects', CXM1P, 7, :m1, :p0 it_does 'update collision register bit for objects', CXP0FB, 6, :p0, :bl it_does 'update collision register bit for objects', CXP0FB, 7, :p0, :pf it_does 'update collision register bit for objects', CXP1FB, 6, :p1, :bl it_does 'update collision register bit for objects', CXP1FB, 7, :p1, :pf it_does 'update collision register bit for objects', CXM0FB, 6, :m0, :bl it_does 'update collision register bit for objects', CXM0FB, 7, :m0, :pf it_does 'update collision register bit for objects', CXM1FB, 6, :m1, :bl it_does 'update collision register bit for objects', CXM1FB, 7, :m1, :pf # Bit 6 of CXBLPF is not used it_does 'update collision register bit for objects', CXBLPF, 7, :bl, :pf it_does 'update collision register bit for objects', CXPPMM, 6, :m0, :m1 it_does 'update collision register bit for objects', CXPPMM, 7, :p0, :p1 end end describe '#set_port_level / VBLANK register input control' do context 'normal mode' do before { tia[VBLANK] = 0 } 0.upto(5) { |p| it_does 'reflect port input', p } end context 'latched mode' do before { tia[VBLANK] = 0b01000000 } 0.upto(3) { |p| it_does 'reflect port input', p } 4.upto(5) { |p| it_does 'latch port input', p} end context 'grounded mode' do before { tia[VBLANK] = 0b10000000 } 0.upto(3) { |p| it_does 'dump port to ground', p } 4.upto(5) { |p| it_does 'reflect port input', p } end context 'latched + grounded mode' do before { tia[VBLANK] = 0b11000000 } 0.upto(3) { |p| it_does 'dump port to ground', p } 4.upto(5) { |p| it_does 'latch port input', p} end end # The "ideal" NTSC frame has 259 scanlines (+3 of vsync, which we don't return), # but we should allow some leeway (we won't emulate "screen roll" that TVs do # with irregular frames) describe '#frame' do def build_frame(lines) @counter ||= -10 # Start on the "previous" frame @counter += 1 case @counter when 0, lines + 3 then tia[VSYNC] = rand_with_bit(1, :set) # Begin frame when 3 then tia[VSYNC] = rand_with_bit(1, :clear) # End frame end tia[WSYNC] = 255 # Finish scanline end 258.upto(260).each do |lines| xit "generates a frame with #{lines} scanlines" do allow(tia.cpu).to receive(:tick) { build_frame(lines) } tia[VSYNC] = rand_with_bit 1, :clear tia.frame expect(tia.frame.size).to eq(lines) end end end skip "Latches: INPT4-INPT5 bit (6) and INPT6-INPT7 bit(7)" end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/spec/lib/ruby2600/frame_generator_spec.rb
spec/lib/ruby2600/frame_generator_spec.rb
require 'spec_helper' describe Ruby2600::FrameGenerator do let(:cpu) { double('cpu', :tick => nil, :halted= => nil) } let(:tia) { double('tia').as_null_object } let(:riot) { double('riot', :tick => nil) } subject(:frame_generator) { Ruby2600::FrameGenerator.new(cpu, tia, riot) } describe '#scanline' do context 'CPU timing' do it 'spends 76 CPU cycles generating a scanline' do expect(cpu).to receive(:tick).exactly(76).times frame_generator.scanline end end context 'RIOT timing' do it 'ticks RIOT 76 times while generating a scanline, regardless of CPU timing' do expect(riot).to receive(:tick).exactly(76).times frame_generator.scanline end it 'ticks RIOT even if CPU is halted' do allow(cpu).to receive(:tick) { allow(cpu).to receive(:halted).and_return(:true) } expect(riot).to receive(:tick).exactly(76).times frame_generator.scanline end end it '"un-halt"s the CPU before starting a new scanline (i.e., before its horizontal blank)' do expect(cpu).to receive(:halted=).with(false) do expect(frame_generator).to receive(:wait_horizontal_blank) end frame_generator.scanline end end it 'late hblank shifts everything' end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/spec/lib/ruby2600/counter_spec.rb
spec/lib/ruby2600/counter_spec.rb
require 'spec_helper' describe Ruby2600::Counter do let(:subject) { Ruby2600::Counter.new } let(:sample_of_initial_values) { Array.new(100) { Ruby2600::Counter.new.value } } describe '#initialize' do it 'initializes with a random value' do unique_value_count = sample_of_initial_values.uniq.length expect(unique_value_count).to be > 1 end it 'initializes with valid values' do sample_of_initial_values.each do |value| expect(value).to be_an Integer expect(0..39).to cover value end end end describe 'on_change' do let(:callback_double) { double 'callback' } before { subject.on_change(callback_double) } it 'is triggered every 4th call' do subject.value = rand(40) 3.times { subject.tick } expect(callback_double).to receive(:on_counter_change) subject.tick end it 'is triggered on wrap' do subject.value = 38 expect(callback_double).to receive(:on_counter_change).twice 8.times { subject.tick } end end describe '#strobe' do it 'resets counter with RESET value from http://www.atarihq.com/danb/files/TIA_HW_Notes.txt' do subject.reset expect(subject.value).to eq(39) end end describe '#tick' do context 'ordinary values' do before { subject.value = rand(38) } it 'increases value once every 4 ticks' do original_value = subject.value 2.times do 3.times { subject.tick } expect { subject.tick }.to change { subject.value }.by 1 end expect(subject.value).to eq(original_value + 2) end end context 'upper boundary (39)' do before { subject.value = 39 } it 'wraps to 0' do 3.times { subject.tick } expect { subject.tick }.to change { subject.value }.to 0 end end end describe '#start_hmove / #apply_hmove' do before { subject.value = 20 } # When HMOVE is strobed, TIA (and the TIA class here) extends the # horizontal blank (and shortens the visible scanline) by 8 pixels, # pushing every movable object 8 pixels to the right. # Then it compensates by inserting additional clocks, from none # (for a -8 move) to 15 (for a +7 move). THAT is done by #apply_move it 'adds no extra CLK ticks for a -8 move' do value = 0b10000000 subject.start_hmove value expect(subject).not_to receive(:tick) 16.times { subject.apply_hmove value } end it 'adds 1 extra CLK ticks for a -7 move' do value = 0b10010000 subject.start_hmove value expect(subject).to receive(:tick).once 16.times { subject.apply_hmove value } end it 'adds 2 extra CLK ticks for a -6 move' do value = 0b10100000 subject.start_hmove value expect(subject).to receive(:tick).twice 16.times { subject.apply_hmove value } end it 'adds 6 extra CLK ticks for a -2 move' do value = 0b11100000 subject.start_hmove value expect(subject).to receive(:tick).exactly(6).times 16.times { subject.apply_hmove value } end it 'adds 7 extra CLK ticks for a -1 move' do value = 0b11110000 subject.start_hmove value expect(subject).to receive(:tick).exactly(7).times 16.times { subject.apply_hmove value } end it 'adds 8 extra CLK ticks for a 0 move' do value = 0 subject.start_hmove value expect(subject).to receive(:tick).exactly(8).times 16.times { subject.apply_hmove value } end it 'adds 12 extra CLK ticks for a +4 move' do value = 0b01000000 subject.start_hmove value expect(subject).to receive(:tick).exactly(12).times 16.times { subject.apply_hmove value } end it 'adds 15 extra CLK ticks for a +7 move' do value = 0b01110000 subject.start_hmove value expect(subject).to receive(:tick).exactly(15).times 16.times { subject.apply_hmove value } end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/spec/lib/ruby2600/ball_spec.rb
spec/lib/ruby2600/ball_spec.rb
require 'spec_helper' describe Ruby2600::Ball do let(:tia) { double 'tia', :reg => Array.new(64, 0), :scanline_stage => :visible } subject(:ball) { Ruby2600::Ball.new(tia) } describe 'pixel' do let(:color) { [rand(255) + 1] } before do tia.reg[COLUPF] = color[0] ball.reset end it 'never outputs if ENABL is disabled' do tia.reg[ENABL] = 0 pixels(ball, 1, 300). == Array.new(300) end it 'generates some output if ENABL is enabled' do tia.reg[ENABL] = rand(256) | 0b10 expect(pixels(ball, 1, 300)).to include(color[0]) end context 'drawing (strobe)' do before do # Enable and strobe from an arbitrary position tia.reg[ENABL] = rand(256) | 0b10 rand(160).times { ball.tick } ball.reset 4.times { ball.tick } # 4-bit delay end context '1x' do before { tia.reg[CTRLPF] = 0b00000000 } it 'draws 1x ball on current scanline' do expect(pixels(ball, 1, 160)).to eq(scanline_with_object(1, color[0])) end it 'is NOT affected by NUSZ0 (it is not player/missile)' do tia.reg[NUSIZ0] = 1 expect(pixels(ball, 1, 160)).to eq(scanline_with_object(1, color[0])) end end context '2x' do before { tia.reg[CTRLPF] = 0b00010000 } it { expect(pixels(ball, 1, 160)).to eq(scanline_with_object(2, color[0])) } end context '4x' do before { tia.reg[CTRLPF] = 0b00100000 } it { expect(pixels(ball, 1, 160)).to eq(scanline_with_object(4, color[0])) } end context '8x' do before { tia.reg[CTRLPF] = 0b00110000 } it { expect(pixels(ball, 1, 160)).to eq(scanline_with_object(8, color[0])) } end end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/spec/lib/ruby2600/graphic_spec.rb
spec/lib/ruby2600/graphic_spec.rb
require 'spec_helper' describe Ruby2600::Graphic do let(:subject) { Ruby2600::Graphic.new(tia) } let(:tia) { double 'tia', :reg => Array.new(64, 0) } describe '#reg' do context 'p0 / m0 / bl' do let(:subject) { Ruby2600::Graphic.new(tia, 0) } it 'alwayss read the requested register' do expect(tia.reg).to receive(:[]).with(HMP0) subject.send(:reg, HMP0) end end context 'p1 / m1' do let(:subject) { Ruby2600::Graphic.new(tia, 1) } it 'reads the matching register for the other object' do expect(tia.reg).to receive(:[]).with(HMP1) subject.send(:reg, HMP0) end end end describe '#pixel' do shared_examples_for 'reflect graphic bit' do it 'by being nil if the graphic bit is clear' do subject.instance_variable_set(:@graphic_bit_value, 0) expect(subject.pixel).to eq(nil) end it "by being the graphic color register's value if the graphic bit is set" do subject.instance_variable_set(:@graphic_bit_value, 1) expect(subject.pixel).to eq(0xAB) end end before do allow(subject).to receive :tick allow(subject).to receive :tick_graphic_circuit subject.class.color_register = [COLUPF, COLUP0, COLUP1].sample tia.reg[subject.class.color_register] = 0xAB end # REVIEW these # context 'in visible scanline' do # it 'ticks the counter' do # subject.counter.should_receive(:tick) # subject.pixel # end # it 'advances the graphic bit' do # subject.should_receive(:tick_graphic_circuit) # subject.pixel # end # it_does 'reflect graphic bit' # end # context 'in extended hblank (aka "comb effect", caused by HMOVE during hblank)' do # it 'does not tick the counter' do # subject.counter.should_not_receive(:tick) # subject.pixel :extended_hblank => true # end # it 'does not advance the graphic' do # subject.should_not_receive(:tick_graphic_circuit) # subject.pixel :extended_hblank => true # end # it_does 'reflect graphic bit' # (won't be displayed, but needed for collision checking) # end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/spec/lib/ruby2600/riot_spec.rb
spec/lib/ruby2600/riot_spec.rb
require 'spec_helper' describe Ruby2600::RIOT do subject(:riot) { Ruby2600::RIOT.new } it 'initializes on a working state' do expect { riot.tick }.to_not raise_error expect { riot[SWCHA].to_i }.to_not raise_error expect { riot[SWCHB].to_i }.to_not raise_error end describe 'ram (#ram)' do it 'has lower 128 bytes available for reading/writing' do 0.upto(127).each do |position| value = Random.rand(256) riot[position] = value expect(riot[position]).to be(value), "Failed for value $#{value.to_s(16)} at $#{position.to_s(16)}" end end end describe 'timer (#tick / INTIM / INSTAT / TIM1T / TIM8T / TIM64T /T1024T)' do context '1-clock timer' do let(:timer_register) { TIM1T } it_behaves_like 'a timer with clock interval', 1 end context '8-clock timer' do let(:timer_register) { TIM8T } it_behaves_like 'a timer with clock interval', 8 end context '64-clock timer' do let(:timer_register) { TIM64T } it_behaves_like 'a timer with clock interval', 64 end context '1024-clock timer' do let(:timer_register) { T1024T } it_behaves_like 'a timer with clock interval', 1024 end end describe 'I/O port A (#portA= / SWACNT / SWCHA)' do before do riot[SWACNT] = 0b10101010 # 1 = output register, 0 = input port riot[SWCHA] = 0b11001100 # set internal register to 1_0_1_0_ riot.portA = 0b01010011 # read input ports as _1_1_0_1 end it 'reads output bits from register and input bits from hardware port' do expect(riot[SWCHA]).to eq(0b11011001) # combined result: 11011001 end end describe 'I/O port B (#portB= / SWBCNT / SWCHB)' do before do riot[SWBCNT] = 0b00100101 # 1 = output register, 0 = input port riot[SWCHB] = 0b11001100 # set internal register to __0__1_0 riot.portB = 0b01010011 # read input ports as 01_10_1_ end it 'reads output bits from register and input bits from hardware port' do expect(riot[SWCHB]).to eq(0b01010110) # combined result: 01010110 end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/spec/lib/ruby2600/constants_spec.rb
spec/lib/ruby2600/constants_spec.rb
require 'spec_helper' # Testing constants may sound nonsensical, but we must be 100% sure that # their addresses (used by RIOT and TIA classes) match the mapping on Bus, # guaranteeing that chips will work regardless of the mirror used by games describe Ruby2600::Constants do it 'uses $00-$3F mirror in all TIA constants' do [ VSYNC, VBLANK, WSYNC, RSYNC, NUSIZ0, NUSIZ1, COLUP0, COLUP1, COLUPF, COLUBK, CTRLPF, REFP0, REFP1, PF0, PF1, PF2, RESP0, RESP1, RESM0, RESM1, RESBL, AUDC0, AUDC1, AUDF0, AUDF1, AUDV0, AUDV1, GRP0, GRP1, ENAM0, ENAM1, ENABL, HMP0, HMP1, HMM0, HMM1, HMBL, VDELP0, VDELP1, VDELBL, RESMP0, RESMP1, HMOVE, HMCLR, CXCLR, CXM0P, CXM1P, CXP0FB, CXP1FB, CXM0FB, CXM1FB, CXBLPF, CXPPMM, INPT0, INPT1, INPT2, INPT3, INPT4, INPT5 ].each { |reg| expect(reg).to be <= 0x3F } end it 'uses $0280-$029x mirror in al RIOT constants' do [ SWCHA, SWACNT, SWCHB, SWBCNT, INTIM, INSTAT, TIM1T, TIM8T, TIM64T, T1024T ].each do |reg| expect(reg).to be >= 0x280 expect(reg).to be <= 0x29F end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/spec/functional/vertical_delay_spec.rb
spec/functional/vertical_delay_spec.rb
require 'spec_helper' describe 'vertical delay' do subject(:frame_generator) { Ruby2600::FrameGenerator.new(cpu, tia, riot) } let(:cpu) { double 'cpu', :tick => nil, :halted= => nil } let(:riot) { double 'riot', :tick => nil } let(:tia) do tia = Ruby2600::TIA.new tia.cpu = cpu tia.riot = riot tia end before do frame_generator.scanline 0x3F.downto(0) { |reg| tia[reg] = 0 } frame_generator.scanline end def grp_on_scanline frame_generator.scanline[5..12].join.to_i(2) end def ball_on_scanline frame_generator.scanline[4] end context 'VDELP0' do before do tia[COLUP0] = 0x01 tia[RESP0] = rand(256) frame_generator.scanline # Old register = AA, new register = BB tia[GRP0] = 0xAA tia[GRP1] = rand(256) tia[GRP0] = 0xBB end it "uses new player by default" do expect(grp_on_scanline).to eq(0xBB) end it "uses old player if VDELP0 bit 0 is set" do tia[VDELP0] = rand(256) | 1 expect(grp_on_scanline).to eq(0xAA) end end context 'VDELP1' do before do tia[COLUP1] = 0x01 tia[RESP1] = rand(256) frame_generator.scanline # Old register = AA, new register = BB tia[GRP1] = 0xAA tia[GRP0] = rand(256) tia[GRP1] = 0xBB end it "uses new player by default" do expect(grp_on_scanline).to eq(0xBB) end it "uses old player if VDELP0 bit 0 is set" do tia[VDELP1] = rand(256) | 1 expect(grp_on_scanline).to eq(0xAA) end end context 'VDELBL' do before do tia[COLUPF] = 0x22 tia[RESBL] = rand(256) # Old register = enable ball, new register = disable ball tia[ENABL] = 0b10 tia[GRP1] = rand(256) tia[ENABL] = 0b00 end it "uses new register (disabled) by default" do expect(ball_on_scanline).not_to eq(0x22) end it "uses old register (enabled) if VDELP0 bit 0 is set" do skip "intermitent failures on this test, fix it" tia[VDELBL] = rand(256) & 1 expect(ball_on_scanline).to eq(0x22) end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/spec/functional/diagonal_spec.rb
spec/functional/diagonal_spec.rb
require 'spec_helper' describe 'diagonal drawn with stetched missile and HMOV' do let(:cart) { Ruby2600::Cart.new(path_for_ROM :diagonal_hmov) } let(:tia) { Ruby2600::TIA.new } let(:cpu) { Ruby2600::CPU.new } let(:riot) { Ruby2600::RIOT.new } let!(:bus) { Ruby2600::Bus.new(cpu, tia, cart, riot) } it 'draws the diagonal' do skip 'adjust the off-by-one drawing' tia.frame # first frame won't sync, discard it 2.times { expect(text(tia.frame)).to eq(hello_world_text) } end def text(frame) trim_blank_lines( frame.inject('') do |text_frame, scanline| text_frame << scanline.map{ |c| c == 0 ? " " : "X" }.join.rstrip << "\n" end) end def trim_blank_lines(text) 2.times do text.chomp! until text.chomp == text text.reverse! end text end let :hello_world_text do trim_blank_lines <<-END XXXX XXX XX X X XX XXX XXXX XXXXX XXXXXX XXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXX XXXXXX XXXXX XXXX XXX XX X X XX XXX XXXX XXXXX XXXXXX XXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX END end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/spec/functional/hello_spec.rb
spec/functional/hello_spec.rb
require 'spec_helper' describe 'hello world with CPU, TIA, Cart and Bus' do let(:cart) { Ruby2600::Cart.new(path_for_ROM :hello) } let(:tia) { Ruby2600::TIA.new } let(:cpu) { Ruby2600::CPU.new } let(:riot) { Ruby2600::RIOT.new } let!(:bus) { Ruby2600::Bus.new(cpu, tia, cart, riot) } it 'generates frames with hello world' do bus.frame # first frame won't sync, discard it 2.times { expect(text(bus.frame)).to eq(hello_world_text) } end def text(frame) trim_blank_lines( frame.inject('') do |text_frame, scanline| text_frame << scanline.map{ |c| c == 0 ? " " : "X" }.join.rstrip << "\n" end) end def trim_blank_lines(text) 2.times do text.chomp! until text.chomp == text text.reverse! end text end let :hello_world_text do trim_blank_lines <<-END XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXX XXXX XXXX XXXX XXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXXXXXX XXXX XXXX XXXXXXXX XXXX XXXX XXXXXXXX XXXX XXXX XXXXXXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX END end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/lib/ruby2600.rb
lib/ruby2600.rb
require 'ruby2600/constants' require 'ruby2600/bus' require 'ruby2600/frame_generator' require 'ruby2600/cpu' require 'ruby2600/cart' require 'ruby2600/riot' require 'ruby2600/tia' require 'ruby2600/counter' require 'ruby2600/graphic' require 'ruby2600/player' require 'ruby2600/missile' require 'ruby2600/ball' require 'ruby2600/playfield' require 'ruby2600/fps_calculator'
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/lib/ruby2600/playfield.rb
lib/ruby2600/playfield.rb
module Ruby2600 class Playfield < Graphic @color_register = COLUPF # register+bit map for each playfield pixel REG_AND_BIT_FOR_PIXEL = [[PF0, 4], [PF0, 5], [PF0, 6], [PF0, 7], [PF1, 7], [PF1, 6], [PF1, 5], [PF1, 4], [PF1, 3], [PF1, 2], [PF1, 1], [PF1, 0], [PF2, 0], [PF2, 1], [PF2, 2], [PF2, 3], [PF2, 4], [PF2, 5], [PF2, 6], [PF2, 7]] # Playfield starts counting at 0 def initialize(*args) super(*args) reset end def reset @counter.value = 0 end def tick unless @tia.scanline_stage == :hblank tick_graphic_circuit @counter.tick end end def start_hmove # Playfield doesn't move end def apply_hmove # Playfield doesn't move end def on_counter_change self.class.color_register = score_mode? ? COLUP0 + @counter.value / 20 : COLUPF end private def tick_graphic_circuit pf_pixel = @counter.value % 20 pf_pixel = 19 - pf_pixel if reflect? register, bit = REG_AND_BIT_FOR_PIXEL[pf_pixel] @graphic_bit_value = reg(register)[bit] end def reflect? reg(CTRLPF)[0] == 1 && @counter.value > 19 end def score_mode? reg(CTRLPF)[1] == 1 end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/lib/ruby2600/version.rb
lib/ruby2600/version.rb
module Ruby2600 VERSION = "0.1.4" end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/lib/ruby2600/fps_calculator.rb
lib/ruby2600/fps_calculator.rb
module Ruby2600 class FPSCalculator def initialize(bus, summary_frequency_frames = 10, report_frequency_seconds = 2) @report_frequency_seconds = report_frequency_seconds @summary_frequency_frames = summary_frequency_frames bus.instance_variable_get(:@frame_generator). instance_variable_set(:@frame_counter, self) #puts "#{Time.now}: calculating average FPS every #{report_frequency_seconds} seconds, summary frequency: #{summary_frequency_frames} frames." end def reset_counters @fps_start = Time.now @frame_count = 0 @total_fps_start ||= @fps_start @total_frame_count ||= 0 end def add unless @fps_start puts "Skipping initial frame (typically bogus)" reset_counters return end now = Time.now puts "#{now}: Counting frame" @frame_count += 1 @total_frame_count += 1 time_elapsed = now - @fps_start total_time_elapsed = now - @total_fps_start if time_elapsed >= @report_frequency_seconds puts "#{now}: Current: #{sprintf("%8.2f", @frame_count / time_elapsed)} FPS" reset_counters end if @total_frame_count % @summary_frequency_frames == 0 puts "#{now}: SUMMARY: #{@total_frame_count} frames; #{sprintf("%8.2f", @total_frame_count / total_time_elapsed)} FPS" end end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/lib/ruby2600/frame_generator.rb
lib/ruby2600/frame_generator.rb
module Ruby2600 class FrameGenerator # A scanline "lasts" 228 "color clocks" (CLKs), of which 68 # are the horizontal blank period, and 160 are visible pixels HORIZONTAL_BLANK_CLK_COUNT = 68 VISIBLE_CLK_COUNT = 160 def initialize(cpu, tia, riot) @cpu = cpu @tia = tia @riot = riot end def frame buffer = [] scanline while @tia.vertical_sync? # VSync scanline while @tia.vertical_blank? # VBlank buffer << scanline until @tia.vertical_blank? # Picture scanline until @tia.vertical_sync? # Overscan @frame_counter.add if @frame_counter buffer end def scanline intialize_scanline wait_horizontal_blank draw_scanline end def intialize_scanline @cpu.halted = false @tia.late_reset_hblank = false end def wait_horizontal_blank @tia.scanline_stage = :hblank HORIZONTAL_BLANK_CLK_COUNT.times { |color_clock| sync_2600_with color_clock } end def draw_scanline scanline = Array.new(160, 0) VISIBLE_CLK_COUNT.times do |pixel| @tia.scanline_stage = @tia.late_reset_hblank && pixel < 8 ? :late_hblank : :visible @tia.update_collision_flags sync_2600_with pixel + HORIZONTAL_BLANK_CLK_COUNT scanline[pixel] = @tia.topmost_pixel if @tia.scanline_stage == :visible && !@tia.vertical_blank? end scanline end # All Atari chips use the same crystal for their clocks (with RIOT and # CPU running at 1/3 of TIA speed). def sync_2600_with(color_clock) @riot.tick if color_clock % 3 == 0 @tia.tick @cpu.tick if color_clock % 3 == 2 end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/lib/ruby2600/tia.rb
lib/ruby2600/tia.rb
module Ruby2600 class TIA attr_accessor :cpu, :riot, :scanline_stage, :late_reset_hblank attr_reader :reg include Constants def initialize # Real 2600 starts with random values (and Stella comments warn # about games that crash if we start with all zeros) @reg = Array.new(64) { rand(256) } @p0 = Player.new(self, 0) @p1 = Player.new(self, 1) @m0 = Missile.new(self, 0) @m1 = Missile.new(self, 1) @bl = Ball.new(self) @pf = Playfield.new(self) @port_level = Array.new(6, false) @latch_level = Array.new(6, true) end def set_port_level(number, level) @port_level[number] = (level == :high) @latch_level[number] = false if level == :low end # Accessors for games (other classes should use :reg to avoid side effects) def [](position) case position when CXM0P..CXPPMM then @reg[position] when INPT0..INPT5 then value_for_port(position - INPT0) end end def []=(position, value) case position when RESP0 @p0.reset when RESP1 @p1.reset when RESM0 @m0.reset when RESM1 @m1.reset when RESBL @bl.reset when RESMP0 @m0.reset_to @p0 when RESMP1 @m1.reset_to @p1 when HMOVE @late_reset_hblank = true @p0.start_hmove @p1.start_hmove @m0.start_hmove @m1.start_hmove @bl.start_hmove when HMCLR @reg[HMP0] = @reg[HMP1] = @reg[HMM0] = @reg[HMM1] = @reg[HMBL] = 0 when CXCLR @reg[CXM0P] = @reg[CXM1P] = @reg[CXP0FB] = @reg[CXP1FB] = @reg[CXM0FB] = @reg[CXM1FB] = @reg[CXBLPF] = @reg[CXPPMM] = 0 when WSYNC @cpu.halted = true when NUSIZ0, NUSIZ1, CTRLPF @reg[position] = six_bit_value(value) when VSYNC..VDELBL @reg[position] = value end @p0.old_value = @reg[GRP0] if position == GRP1 @bl.old_value = @reg[ENABL] if position == GRP1 @p1.old_value = @reg[GRP1] if position == GRP0 @latch_level.fill(true) if position == VBLANK && value[6] == 1 end def tick @p0.tick @p1.tick @m0.tick @m1.tick @bl.tick @pf.tick end def vertical_blank? @reg[VBLANK][1] != 0 end def vertical_sync? @reg[VSYNC][1] != 0 end def topmost_pixel if @reg[CTRLPF][2].zero? @p0.pixel || @m0.pixel || @p1.pixel || @m1.pixel || @bl.pixel || @pf.pixel || @reg[COLUBK] else @pf.pixel || @bl.pixel || @p0.pixel || @m0.pixel || @p1.pixel || @m1.pixel || @reg[COLUBK] end end BIT_6 = 0b01000000 BIT_7 = 0b10000000 def update_collision_flags @reg[CXM0P] |= BIT_6 if @m0.pixel && @p0.pixel @reg[CXM0P] |= BIT_7 if @m0.pixel && @p1.pixel @reg[CXM1P] |= BIT_6 if @m1.pixel && @p1.pixel @reg[CXM1P] |= BIT_7 if @m1.pixel && @p0.pixel @reg[CXP0FB] |= BIT_6 if @p0.pixel && @bl.pixel @reg[CXP0FB] |= BIT_7 if @p0.pixel && @pf.pixel @reg[CXP1FB] |= BIT_6 if @p1.pixel && @bl.pixel @reg[CXP1FB] |= BIT_7 if @p1.pixel && @pf.pixel @reg[CXM0FB] |= BIT_6 if @m0.pixel && @bl.pixel @reg[CXM0FB] |= BIT_7 if @m0.pixel && @pf.pixel @reg[CXM1FB] |= BIT_6 if @m1.pixel && @bl.pixel @reg[CXM1FB] |= BIT_7 if @m1.pixel && @pf.pixel # c-c-c-combo breaker: bit 6 of CXLBPF is unused @reg[CXBLPF] |= BIT_7 if @bl.pixel && @pf.pixel @reg[CXPPMM] |= BIT_6 if @m0.pixel && @m1.pixel @reg[CXPPMM] |= BIT_7 if @p0.pixel && @p1.pixel end private # INPTx (I/O ports) helpers def value_for_port(number) return 0x00 if grounded_port?(number) level = @port_level[number] level &&= @latch_level[number] if latched_port?(number) level ? 0x80 : 0x00 end def grounded_port?(number) @reg[VBLANK][7] == 1 && number <= 3 end def latched_port?(number) @reg[VBLANK][6] == 1 && number >= 4 end def six_bit_value(number) number & 0b111111 end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/lib/ruby2600/graphic.rb
lib/ruby2600/graphic.rb
require 'forwardable' # JRuby needs this module Ruby2600 class Graphic include Constants extend Forwardable def_delegators :@counter, :reset, :value, :old_value, :old_value= # These parameters are specific to each type of graphic (player, missile, ball or playfield) class << self attr_accessor :graphic_delay, :graphic_size, :hmove_register, :color_register end def initialize(tia, graphic_number = 0) @tia = tia @graphic_number = graphic_number @counter = Counter.new @counter.on_change(self) end def tick if @tia.scanline_stage == :visible tick_graphic_circuit @counter.tick else apply_hmove end end def pixel reg(self.class.color_register) if @graphic_bit_value == 1 end def reset_to(other_graphic) @counter.reset_to other_graphic.instance_variable_get(:@counter) end def start_hmove @counter.start_hmove reg(self.class.hmove_register) tick_graphic_circuit end def on_counter_change if should_draw_graphic? || should_draw_copy? @graphic_bit = -self.class.graphic_delay @bit_copies_written = 0 end end private # Adjusts the Value of a register for the current object # Ex.: reg(GRP0) will read GRP0 for P0, but GRP1 for P1; # reg(HMM0) will read HMM0 for M0, but HMM1 for M1; def reg(register_name) @tia.reg[register_name + @graphic_number] end def apply_hmove applied = @counter.apply_hmove reg(self.class.hmove_register) tick_graphic_circuit if applied end def tick_graphic_circuit if @graphic_bit if (0..7).include?(@graphic_bit) @graphic_bit_value = pixel_bit @bit_copies_written += 1 if @bit_copies_written == size @bit_copies_written = 0 @graphic_bit += 1 end else @graphic_bit += 1 end @graphic_bit = nil if @graphic_bit == self.class.graphic_size else @graphic_bit_value = nil end end def should_draw_graphic? @counter.value == 39 end def should_draw_copy? count = @counter.value nusiz_bits = reg(NUSIZ0) % 8 (count == 3 && (nusiz_bits == 0b001 || nusiz_bits == 0b011)) || (count == 7 && (nusiz_bits == 0b010 || nusiz_bits == 0b011 || nusiz_bits == 0b110)) || (count == 15 && (nusiz_bits == 0b100 || nusiz_bits == 0b110)) end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/lib/ruby2600/cart.rb
lib/ruby2600/cart.rb
module Ruby2600 class Cart def initialize(rom_file) @bytes = File.open(rom_file, "rb") { |f| f.read }.unpack('C*') @bytes += @bytes if @bytes.count == 2048 end def [](address) @bytes[address] end def []=(address, value) end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/lib/ruby2600/constants.rb
lib/ruby2600/constants.rb
module Ruby2600 module Constants # TIA writable registers VSYNC = 0x00 VBLANK = 0x01 WSYNC = 0x02 RSYNC = 0x03 NUSIZ0 = 0x04 NUSIZ1 = 0x05 COLUP0 = 0x06 COLUP1 = 0x07 COLUPF = 0x08 COLUBK = 0x09 CTRLPF = 0x0A REFP0 = 0x0B REFP1 = 0x0C PF0 = 0x0D PF1 = 0x0E PF2 = 0x0F RESP0 = 0x10 RESP1 = 0x11 RESM0 = 0x12 RESM1 = 0x13 RESBL = 0x14 AUDC0 = 0x15 AUDC1 = 0x16 AUDF0 = 0x17 AUDF1 = 0x18 AUDV0 = 0x19 AUDV1 = 0x1A GRP0 = 0x1B GRP1 = 0x1C ENAM0 = 0x1D ENAM1 = 0x1E ENABL = 0x1F HMP0 = 0x20 HMP1 = 0x21 HMM0 = 0x22 HMM1 = 0x23 HMBL = 0x24 VDELP0 = 0x25 VDELP1 = 0x26 VDELBL = 0x27 RESMP0 = 0x28 RESMP1 = 0x29 HMOVE = 0x2A HMCLR = 0x2B CXCLR = 0x2C # TIA readable registers CXM0P = 0x30 CXM1P = 0x31 CXP0FB = 0x32 CXP1FB = 0x33 CXM0FB = 0x34 CXM1FB = 0x35 CXBLPF = 0x36 CXPPMM = 0x37 INPT0 = 0x38 INPT1 = 0x39 INPT2 = 0x3A INPT3 = 0x3B INPT4 = 0x3C INPT5 = 0x3D # RIOT SWCHA = 0x0280 SWACNT = 0x0281 SWCHB = 0x0282 SWBCNT = 0x0283 INTIM = 0x0284 INSTAT = 0x0285 TIM1T = 0x0294 TIM8T = 0x0295 TIM64T = 0x0296 T1024T = 0x0297 end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/lib/ruby2600/player.rb
lib/ruby2600/player.rb
module Ruby2600 class Player < Graphic @graphic_delay = 5 @graphic_size = 8 @hmove_register = HMP0 @color_register = COLUP0 private def pixel_bit grp[7 - @graphic_bit] end def size case reg(NUSIZ0) & 0b111 when 0b101 then 2 when 0b111 then 4 else 1 end end def grp result = reg(VDELP0)[0] == 1 ? @counter.old_value : reg(GRP0) reg(REFP0)[3] == 1 ? reflect(result) : result end def reflect(bits) (0..7).inject(0) { |value, n| value + (bits[n] << (7 - n)) } end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/lib/ruby2600/riot.rb
lib/ruby2600/riot.rb
module Ruby2600 class RIOT include Constants def initialize @ram = Array.new(128) self[T1024T] = rand(256) # FIXME Stella says H.E.R.O. hangs if it is zero, check it out @portA = @portB = @swcha = @swchb = @swacnt = @swbcnt = 0 end def [](address) case address when 0x00..0x7F then @ram[address] when INTIM then @timer when INSTAT then read_timer_flags when SWCHA then (@swcha & @swacnt) | (@portA & (@swacnt ^ 0xFF)) when SWCHB then (@swchb & @swbcnt) | (@portB & (@swbcnt ^ 0xFF)) end end def []=(address, value) case address when 0x00..0x7F then @ram[address] = value when TIM1T then initialize_timer(value, 1) when TIM8T then initialize_timer(value, 8) when TIM64T then initialize_timer(value, 64) when T1024T then initialize_timer(value, 1024) when SWCHA then @swcha = value when SWACNT then @swacnt = value when SWCHB then @swchb = value when SWBCNT then @swbcnt = value end end def tick @cycle_count -= 1 if @cycle_count == 0 decrement_timer end end def portA=(value) @portA = value end def portB=(value) @portB = value end private def initialize_timer(value, resolution) @timer_flags = 0 @timer = value @resolution = resolution decrement_timer end def decrement_timer @timer -= 1 underflow if @timer < 0 reset_cycle_count end def underflow @timer_flags = 0b11000000 @timer = 0xFF @resolution = 1 end def reset_cycle_count @cycle_count = @resolution end def read_timer_flags instat = @timer_flags @timer_flags &= 0b10111111 instat end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/lib/ruby2600/cpu.rb
lib/ruby2600/cpu.rb
module Ruby2600 class CPU attr_accessor :memory attr_accessor :pc, :a, :x, :y, :s attr_accessor :n, :v, :d, :i, :z, :c # Flags (P register): nv--dizc attr_accessor :halted # Simulates RDY (if true, clock is ignored) RESET_VECTOR = 0xFFFC BRK_VECTOR = 0xFFFE OPCODE_SIZES = [ 1, 2, 0, 2, 2, 2, 2, 2, 1, 2, 1, 2, 3, 3, 3, 3, 2, 2, 0, 2, 2, 2, 2, 2, 1, 3, 1, 3, 3, 3, 3, 3, 3, 2, 0, 2, 2, 2, 2, 2, 1, 2, 1, 2, 3, 3, 3, 3, 2, 2, 0, 2, 2, 2, 2, 2, 1, 3, 1, 3, 3, 3, 3, 3, 0, 2, 0, 2, 2, 2, 2, 2, 1, 2, 1, 2, 0, 3, 3, 3, 2, 2, 0, 2, 2, 2, 2, 2, 1, 3, 1, 3, 3, 3, 3, 3, 0, 2, 0, 2, 2, 2, 2, 2, 1, 2, 1, 2, 0, 3, 3, 3, 2, 2, 0, 2, 2, 2, 2, 2, 1, 3, 1, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 1, 2, 3, 3, 3, 3, 2, 2, 0, 2, 2, 2, 2, 2, 1, 3, 1, 0, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 1, 2, 3, 3, 3, 3, 2, 2, 0, 2, 2, 2, 2, 2, 1, 3, 1, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 1, 2, 3, 3, 3, 3, 2, 2, 0, 2, 2, 2, 2, 2, 1, 3, 1, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 1, 2, 3, 3, 3, 3, 2, 2, 0, 2, 2, 2, 2, 2, 1, 3, 1, 3, 3, 3, 3, 3 ] OPCODE_CYCLE_COUNTS = [ 7, 6, 0, 8, 3, 3, 5, 5, 3, 2, 2, 2, 4, 4, 6, 6, 2, 5, 0, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7, 6, 6, 0, 8, 3, 3, 5, 5, 4, 2, 2, 2, 4, 4, 6, 6, 2, 5, 0, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7, 6, 6, 0, 8, 3, 3, 5, 5, 3, 2, 2, 2, 3, 4, 6, 6, 2, 5, 0, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7, 6, 6, 0, 8, 3, 3, 5, 5, 4, 2, 2, 2, 5, 4, 6, 6, 2, 5, 0, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7, 2, 6, 2, 6, 3, 3, 3, 3, 2, 2, 2, 2, 4, 4, 4, 4, 2, 6, 0, 6, 4, 4, 4, 4, 2, 5, 2, 5, 5, 5, 5, 5, 2, 6, 2, 6, 3, 3, 3, 3, 2, 2, 2, 2, 4, 4, 4, 4, 2, 5, 0, 5, 4, 4, 4, 4, 2, 4, 2, 4, 4, 4, 4, 4, 2, 6, 2, 8, 3, 3, 5, 5, 2, 2, 2, 2, 4, 4, 6, 6, 2, 5, 0, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7, 2, 6, 2, 8, 3, 3, 5, 5, 2, 2, 2, 2, 4, 4, 6, 6, 2, 5, 0, 8, 4, 4, 6, 6, 2, 4, 2, 7, 4, 4, 7, 7 ] # The 6507 recognizes 151 different opcodes. These have implicit addressing, # (that is, map to a single logical instruction) and can be decoded directly: BRK = 0x00; PHP = 0x08; JSR = 0x20; PLP = 0x28; RTI = 0x40; PHA = 0x48; RTS = 0x60; PLA = 0x68; DEY = 0x88; TXA = 0x8A; TYA = 0x98; TXS = 0x9A; TAY = 0xA8; TAX = 0xAA; CLV = 0xB8; TSX = 0xBA; INY = 0xC8; DEX = 0xCA; INX = 0xE8; NOP = 0xEA # The remaining logical instructions map to different opcodes, depending on # the type of parameter they will be taking (a memory address, a value, etc.) # # We'll use info from from http://www.llx.com/~nparker/a2/opcodes.html) to build # bitmask constants that will ease decoding the opcodes into instructions: ADDRESSING_MODE_GROUPS = [ [ :immediate, :zero_page, nil, :absolute, nil, :zero_page_indexed_x, nil, :absolute_indexed_x ], [ :indexed_indirect_x, :zero_page, :immediate, :absolute, :indirect_indexed_y, :zero_page_indexed_x, :absolute_indexed_y, :absolute_indexed_x ], [ :immediate, :zero_page, :accumulator, :absolute, nil, :zero_page_indexed_x_or_y, nil, :absolute_indexed_x_or_y ] ] INSTRUCTION_GROUPS = [ %w'xxx BIT JMP JMPabs STY LDY CPY CPX', %w'ORA AND EOR ADC STA LDA CMP SBC', %w'ASL ROL LSR ROR STX LDX DEC INC' ] INSTRUCTION_GROUPS.each_with_index do |names, cc| names.each_with_index do |name, aaa| const_set name, (aaa << 5) + cc unless name == 'xxx' end end # Conditional branches (BPL, BMI, BVC, BVS, BCC, BCS, BNE, BEQ) and the symmetric # set/clear flag instructions (SEC, SEI, SED, CLD, CLI, CLD) also follow bit # patterns (for target flag and expected/set value) and will be generalized # as "BXX" and SCX": BXX = 0b00010000 SCX = 0b00011000 BXX_FLAGS = [:@n, :@v, :@c, :@z] SCX_FLAGS = [:@c, :@i, :@v, :@d] # @v not (officially) used # Instructions that index (non-zero-page) memory have a 1-cycle penality if # the resulting address crosses page boundaries (trivia: it is, in fact, an # optimization of the non-crossing cases: http://bit.ly/10JNkOR) INSTRUCTIONS_WITH_PAGE_PENALTY = [ORA, AND, EOR, ADC, LDA, CMP, SBC, LDX, LDY] def initialize @pc = @x = @y = @a = @s = 0 end def reset @pc = memory_word(RESET_VECTOR) end def step fetch decode execute @time_in_cycles end def tick return if @halted if !@time_in_cycles fetch decode end @time_in_cycles -= 1 if @time_in_cycles == 0 execute @time_in_cycles = nil end end private # 6507 has an internal "T-state" that gets incremented as each clock cycle # advances within an instruction (cf. http://www.pagetable.com/?p=39). # # For simplicity, let's stick to the fetch-decode-execute cycle and advance # the PC to the next instruction right on fetch. As a consequence, "@pc" will # be the PC for *NEXT* instruction throughout the decode and execute phases. def fetch @opcode = memory[@pc] || 0 @param_lo = memory[word(@pc + 1)] || 0 @param_hi = memory[word(@pc + 2)] || 0 @param = @param_hi * 0x100 + @param_lo @pc = word(@pc + OPCODE_SIZES[@opcode]) end def decode if (@opcode & 0b00011111) == BXX @instruction = BXX elsif (@opcode & 0b00011111) == SCX @instruction = SCX else @instruction_group = (@opcode & 0b00000011) mode_in_group = (@opcode & 0b00011100) >> 2 @addressing_mode = ADDRESSING_MODE_GROUPS[@instruction_group][mode_in_group] @instruction = (@opcode & 0b11100011) end @time_in_cycles = time_in_cycles end # These helpers allow us to "tag" operations with affected flags def flag_nz(value) @z = value.zero? @n = value[7] != 0 end def flag_nzc(value) flag_nz value @c = value >= 0 end # Core execution logic def execute case @opcode when NOP when INX flag_nz @x = byte(@x + 1) when INY flag_nz @y = byte(@y + 1) when DEX flag_nz @x = byte(@x - 1) when DEY flag_nz @y = byte(@y - 1) when TAX flag_nz @x = @a when TAY flag_nz @y = @a when TXA flag_nz @a = @x when TYA flag_nz @a = @y when TSX flag_nz @x = @s when TXS @s = @x when CLV @v = false when PHP push p when PLP self.p = pop when PHA push @a when PLA flag_nz @a = pop when JSR push_word @pc - 1 @pc = @param when RTS @pc = word(pop_word + 1) when BRK push_word @pc push p @i = true @pc = memory_word(BRK_VECTOR) when RTI self.p = pop @pc = pop_word else # Not an implicit addressing instruction execute_with_addressing_mode end end def execute_with_addressing_mode case @instruction when AND flag_nz @a = @a & load when ORA flag_nz @a = @a | load when EOR flag_nz @a = @a ^ load when BIT @z = (@a & load).zero? @v = load[6] != 0 @n = load[7] != 0 when LDA flag_nz @a = load when LDX flag_nz @x = load when LDY flag_nz @y = load when INC flag_nz store byte(load + 1) when DEC flag_nz store byte(load - 1) when ADC, SBC flag_nz @a = arithmetic when STA store @a when STX store @x when STY store @y when ASL, ROL, LSR, ROR flag_nz store shift when CMP flag_nzc @a - load when CPX flag_nzc @x - load when CPY flag_nzc @y - load when JMP @pc = @param when JMPabs @pc = memory_word(@param) when BXX @pc = branch when SCX instance_variable_set SCX_FLAGS[@opcode >> 6], @opcode[5] == 1 end end # Generalized instructions (branches, arithmetic, shift) def branch should_branch? ? branch_target_address : @pc end def branch_target_address return word(@pc + signed(@param_lo)) end def should_branch? flag = (@opcode & 0b11000000) >> 6 expected = (@opcode & 0b00100000) != 0 actual = instance_variable_get(BXX_FLAGS[flag]) !(expected ^ actual) end def arithmetic signal = @instruction == ADC ? 1 : -1 carry = @instruction == ADC ? bit(@c) : bit(@c) - 1 limit = @instruction == ADC ? bcd_to_value(255) : -1 k = signed(@a) + signal * signed(load) + carry t = bcd_to_value(@a) + signal * bcd_to_value(load) + carry @v = k > 127 || k < -128 @c = t > limit value_to_bcd(t) & 0xFF end def shift right = @instruction & 0b01000000 != 0 rotate = @instruction & 0b00100000 != 0 new_bit = rotate ? (bit(@c) << (right ? 7 : 0)) : 0 delta = right ? -1 : 1 _ = load @c = _[right ? 0 : 7] == 1 byte(_ << delta) | new_bit end # Memory (and A) read/write for the current opcode's access mode. # store() returns the written value, allowing it to be prefixed with flag_* def load case @addressing_mode when :immediate then @param_lo when :accumulator then @a else memory[self.send(@addressing_mode)] || 0 end end def store(value) case @addressing_mode when :immediate then memory[@param_lo] = value when :accumulator then @a = value else memory[self.send(@addressing_mode)] = value end value end def zero_page @param_lo end def zero_page_indexed_x byte @param_lo + @x end def zero_page_indexed_y byte @param_lo + @y end def zero_page_indexed_x_or_y [LDX, STX].include?(@instruction) ? zero_page_indexed_y : zero_page_indexed_x end def absolute @param end def absolute_indexed_x word @param + @x end def absolute_indexed_y word @param + @y end def absolute_indexed_x_or_y [LDX, STX].include?(@instruction) ? absolute_indexed_y : absolute_indexed_x end def indirect_indexed_y word(memory_word(@param_lo) + @y) end def indexed_indirect_x memory_word(byte(@param_lo + @x)) end # Stack def push(value) memory[0x100 + @s] = value @s = byte(@s - 1) end def pop @s = byte(@s + 1) memory[0x100 + @s] end def push_word(value) push value / 0x0100 push byte(value) end def pop_word pop + (0x100 * pop) end # Flags are stored as individual booleans, but sometimes we need # them as a flags register (P), which bit-maps to "NV_BDIZC" # # Notice that bit 5 (_) is always 1 and bit 4 (B) is only false # on non-software interrupts (IRQ/NMI), which we don't support. def p _ = 0b00110000 _ += 0b10000000 if @n _ += 0b01000000 if @v _ += 0b00001000 if @d _ += 0b00000100 if @i _ += 0b00000010 if @z _ += 0b00000001 if @c _ end def p=(value) @n = (value & 0b10000000) != 0 @v = (value & 0b01000000) != 0 @d = (value & 0b00001000) != 0 @i = (value & 0b00000100) != 0 @z = (value & 0b00000010) != 0 @c = (value & 0b00000001) != 0 end # Timing def time_in_cycles cycles = OPCODE_CYCLE_COUNTS[@opcode] cycles += 1 if penalize_for_page_boundary_cross? cycles += branch_cost end def penalize_for_page_boundary_cross? return false unless INSTRUCTIONS_WITH_PAGE_PENALTY.include? @instruction lo_addr = case @addressing_mode when :absolute_indexed_y then @param_lo + @y when :indirect_indexed_y then memory[@param_lo] + @y when :absolute_indexed_x then @param_lo + @x when :absolute_indexed_x_or_y then @param_lo + (@instruction == LDX ? @y : @x) else 0 end lo_addr > 0xFF end def branch_cost return 0 unless @instruction == BXX && should_branch? (@pc & 0xFF00) == (branch_target_address & 0xFF00) ? 1 : 2 end # BCD functions are inert unless we are in decimal mode. bcd will also # conveniently make 0xFF into 99, making carry-check decimal-mode-agnostic def bcd_to_value(value) return value unless @d ([value / 16, 9].min) * 10 + ([value % 16, 9].min) end def value_to_bcd(value) return value unless @d value = 100 + value if value < 0 value -= 100 if value > 99 (value / 10) * 16 + (value % 10) end # Convenience conversions (most due to the lack of byte/word & signed/unsigned types) def byte(value) (value || 0) & 0xFF end def word(value) (value || 0) & 0xFFFF end def bit(flag) flag ? 1 : 0 end def signed(signed_byte) signed_byte > 0x7F ? signed_byte - 0x100 : signed_byte end def memory_word(address) memory[word(address + 1)] * 0x100 + memory[address] end # Debug tools (should be expanded and moved into its own module) def to_s "PC=#{sprintf("$%04X", @pc)} A=#{sprintf("$%02X", @a)} X=#{sprintf("$%02X", @x)} Y=#{sprintf("$%02X", @y)} " + " opcode: #{sprintf("$%02X", @opcode)}" + (OPCODE_SIZES[@opcode] > 1 ? " @param_lo: #{sprintf("$%02X", @param_lo)}" : "") + (OPCODE_SIZES[@opcode] > 2 ? " @param_hi: #{sprintf("$%02X", @param_hi)}" : "") + " cycles: #{time_in_cycles}" end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/lib/ruby2600/counter.rb
lib/ruby2600/counter.rb
module Ruby2600 # Internal counters used by all TIA graphics to trigger drawing at appropriate time. # Horizontal position is implicitly tracked by the counter value, and movement is # implemented by making its cycle higher or lower than the current scanline. # # See: http://www.atarihq.com/danb/files/TIA_HW_Notes.txt class Counter attr_accessor :old_value, # Stored for vertical delay (VDELxx) modes :notify_change_on_reset # Allows ball to trigger immediately PERIOD = 40 # "Visible" counter value ranges from 0-39... DIVIDER = 4 # ...incrementing every 4 "ticks" from TIA (1/4 of TIA clock) # (shift left (<<) are equivalent to multiply by 2^<shift> # and shift right (>>) are equivalent to divide by 2^<shift>) RESET_VALUE = 39 # Value set when the TIA RESxx position is strobed INTERNAL_PERIOD = PERIOD * DIVIDER def initialize @old_value = @internal_value = rand(INTERNAL_PERIOD) @notify_change_on_reset = false end def value @internal_value / DIVIDER end def value=(x) @internal_value = x * DIVIDER end # TIA graphic circuits are triggered when the visible counter value changes, so # graphics should provide this listener. The ball will also trigger it on strobe # (and that is why it draws immediately and not on the next scanline) def on_change(object) @change_listener = object end def tick previous_value = value @internal_value = (@internal_value + 1) % INTERNAL_PERIOD @change_listener.on_counter_change if @change_listener && value != previous_value end def reset @internal_value = RESET_VALUE * DIVIDER @change_listener.on_counter_change if @notify_change_on_reset end def reset_to(other_counter) @internal_value = other_counter.instance_variable_get(:@internal_value) end # Horizontal movement (HMOV) is implemented by extending the horizontal blank # by 8 pixels. That shortens the visible scanline to 152 pixels (producing the # "comb effect" on the left side) and pushes all graphics 8 pixels to the right... def start_hmove(register_value) @ticks_added = 0 @movement_required = !ticks_to_add(register_value).zero? end # ...but then TIA stuffs each counter with an extra cycle, counting those until # it reaches the current value for the HMMxx register for that graphic). Each # extra tick means pushing the graphic 1 pixel to the left, so the final movement # ends up being something betwen 8 pixels to the right (0 extra ticks) and # 7 pixels to the left (15 extra ticks) def apply_hmove(register_value) return unless @movement_required tick @ticks_added += 1 @movement_required = false if @ticks_added == ticks_to_add(register_value) true end private def ticks_to_add(register_value) nibble = register_value >> 4 nibble < 8 ? nibble + 8 : nibble - 8 end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/lib/ruby2600/ball.rb
lib/ruby2600/ball.rb
module Ruby2600 class Ball < Graphic @graphic_delay = 4 @graphic_size = 1 @hmove_register = HMBL @color_register = COLUPF # Ball draws immediately when RESBL is strobed (other objects only do it # when their counter wraps around, i.e., on next scanline) def initialize(tia) super(tia) @counter.notify_change_on_reset = true end private def pixel_bit reg(VDELBL)[0] == 1 ? @counter.old_value[1] : reg(ENABL)[1] end def size 1 << (reg(CTRLPF) >> 4) end def should_draw_copy? false end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/lib/ruby2600/bus.rb
lib/ruby2600/bus.rb
module Ruby2600 class Bus include Constants def initialize(cpu, tia, cart, riot) @cpu = cpu @tia = tia @cart = cart @riot = riot @frame_generator = Ruby2600::FrameGenerator.new(cpu, tia, riot) @cpu.memory = self @tia.cpu = cpu @tia.riot = riot @riot_bit_states = { :portA => 0xFF, :portB => 0xFF } refresh_riot :portA refresh_riot :portB cpu.reset end def frame @frame_generator.frame end # FIXME dry def [](address) if address[12] == 1 return @cart[address & 0x0FFF] elsif address[7] == 1 if address[9] == 0 return @riot[address & 0x7F] else return @riot[address & 0x2FF] end else return @tia[(address & 0x0F) + 0x30] end end def []=(address, value) if address[12] == 1 @cart[address & 0x0FFF] = value elsif address[7] == 1 if address[9] == 0 @riot[address & 0x7F] = value else @riot[address & 0x2FF] = value end else @tia[address & 0x3F] = value end end def reset_switch=(state) set_riot :portB, 0, state end def select_switch=(state) set_riot :portB, 1, state end def color_bw_switch=(state) set_riot :portB, 3, state end def p0_difficulty_switch=(state) set_riot :portB, 6, state end def p1_difficulty_switch=(state) set_riot :portB, 7, state end def p0_joystick_up=(state) set_riot :portA, 4, state end def p0_joystick_down=(state) set_riot :portA, 5, state end def p0_joystick_left=(state) set_riot :portA, 6, state end def p0_joystick_right=(state) set_riot :portA, 7, state end def p0_joystick_fire=(state) @tia.set_port_level 4, (state ? :low : :high) end private def set_riot(port, n, state) # To press/enable something, we reset the bit, and vice-versa. # Why? Because TIA, that's why. if state @riot_bit_states[port] &= 0xFF - (1 << n) else @riot_bit_states[port] |= 1 << n end refresh_riot port end def refresh_riot(port) @riot.send("#{port}=", @riot_bit_states[port]) end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/lib/ruby2600/missile.rb
lib/ruby2600/missile.rb
module Ruby2600 class Missile < Graphic @graphic_delay = 4 @graphic_size = 1 @hmove_register = HMM0 @color_register = COLUP0 private def pixel_bit reg(ENAM0)[1] end def size 1 << (reg(NUSIZ0) >> 4) end end end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/metadata.rb
metadata.rb
name 'nagios' maintainer 'Sous Chefs' maintainer_email 'help@sous-chefs.org' license 'Apache-2.0' description 'Installs and configures Nagios server' version '12.1.4' issues_url 'https://github.com/sous-chefs/nagios/issues' source_url 'https://github.com/sous-chefs/nagios' chef_version '>= 15.3' depends 'apache2', '>= 9.0' depends 'nginx', '>= 11.2' depends 'nrpe' depends 'php', '>= 10.0' depends 'yum-epel' depends 'zap', '>= 0.6.0' suports 'centos', '>= 8.0' supports 'oracle', '>= 8.0' supports 'redhat', '>= 8.0' supports 'debian', '>= 11.0' supports 'ubuntu', '>= 20.04'
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/test/fixtures/cookbooks/nagios_test/metadata.rb
test/fixtures/cookbooks/nagios_test/metadata.rb
name 'nagios_test' maintainer 'Sander Botman' maintainer_email 'sbotman@schubergphilis.com' license 'Apache-2.0' description 'Contains Nagios configuration items' version '0.1.1' depends 'nagios'
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/test/fixtures/cookbooks/nagios_test/recipes/default.rb
test/fixtures/cookbooks/nagios_test/recipes/default.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios_test # Recipe:: default # # Copyright:: (C) 2015 Schuberg Philis. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. package 'wget' nagios_command 'system-load' do options 'command_line' => '$USER1$/check_load -w $ARG1$ -c $ARG2$' end nagios_service 'system-high-load' do options 'check_command' => 'system-load!20,15,10!40,35,30', 'use' => 'default-service', 'hostgroup_name' => 'high_load_servers' end nagios_service 'system-medium-load' do options 'check_command' => 'system-load!15,10,5!30,25,20', 'use' => 'default-service', 'hostgroup_name' => 'medium_load_servers' end nagios_contact 'sander botman' do options 'use' => 'default-contact', 'alias' => 'Nagios Noob', 'pager' => '+31651425985', 'email' => 'sbotman@schubergphilis.com', '_my_custom_key' => 'custom_value' end nagios_command 'my-event-handler-command' do options 'command_line' => 'ping localhost' end nagios_host 'generichosttemplate' do options 'use' => 'server', 'name' => 'generichosttemplate', 'register' => 0, 'check_interval' => 10, 'event_handler' => 'my-event-handler-command' end # bighost1 should have no event_handler, bithost2 should have my-event-handler-command nagios_host 'bighost1' do options 'use' => 'generichosttemplate', 'host_name' => 'bighost1', 'address' => '192.168.1.3', 'event_handler' => 'null' end nagios_host 'bighost2' do options 'use' => 'generichosttemplate', 'host_name' => 'bighost2', 'address' => '192.168.1.4', 'check_interval' => '20' end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/test/smoke/server_package/default_test.rb
test/smoke/server_package/default_test.rb
if os.redhat? apache_bin = 'httpd' config_cgi_path = 'nagios/cgi-bin/config.cgi' path_config_dir = '/etc/nagios/conf.d' path_conf_dir = '/etc/nagios' service_name = 'nagios' elsif os.suse? apache_bin = 'httpd-prefork' config_cgi_path = 'cgi-bin/nagios3/config.cgi' path_config_dir = '/etc/nagios3/conf.d' path_conf_dir = '/etc/nagios3' service_name = 'nagios' else apache_bin = 'apache2' config_cgi_path = 'cgi-bin/nagios3/config.cgi' path_config_dir = '/etc/nagios3/conf.d' path_conf_dir = '/etc/nagios3' service_name = 'nagios3' end # Test Nagios Config describe file("#{path_config_dir}/commands.cfg") do its(:content) { should match 'check_all_hostgroup_service' } its(:content) { should match 'check_host_alive' } its(:content) { should match 'check_load' } its(:content) { should match 'check_nagios' } its(:content) { should match 'check_nrpe' } its(:content) { should match 'check_nrpe_alive' } its(:content) { should match 'check_service_(a|b|c)' } its(:content) { should match 'host_notify_by_email' } its(:content) { should match 'host_notify_by_sms_email' } its(:content) { should match 'service_notify_by_email' } end describe file("#{path_conf_dir}/nagios.cfg") do its(:content) { should match 'host_perfdata_command=command_(a|b)' } its(:content) { should match 'use_syslog=0' } end describe file("#{path_conf_dir}/nagios.cfg") do its(:content) { should_not match 'query_socket=' } end describe file("#{path_config_dir}/services.cfg") do its(:content) { should match 'service_description.*all_hostgroup_service' } its(:content) { should match 'service_description.*load' } its(:content) { should match 'service_description.*service_(a|b|c)' } its(:content) { should match 'check_command.*system-load!15,10,5!30,25,20' } its(:content) { should match 'contact_groups.*\+[^ ]+non_admins' } its(:content) { should match 'contact_groups.*null' } its(:content) { should match 'host_name.*\*' } end describe file("#{path_config_dir}/hosts.cfg") do its(:content) { should match 'host_name[ \t]+host_a_alt' } its(:content) { should match 'host_name[ \t]+host_b' } its(:content) { should match 'host_name[ \t]+chefnode_a' } its(:content) { should match 'host_name[ \t]+chefnode_(b|c|d)_alt' } its(:content) { should match '_CUSTOM_HOST_OPTION[ \t]+custom_host_value.*\n}' } its(:content) { should match 'notes[ \t]+configured via chef node attributes' } end describe file("#{path_config_dir}/hosts.cfg") do its(:content) { should_not match 'chefnode_exclude_(arr|str)' } its(:content) { should_not match 'host_name.*\*' } end describe file("#{path_config_dir}/contacts.cfg") do its(:content) { should match 'contact.*(admin|devs|root)' } its(:content) { should match 'contactgroup_name.*admins' } its(:content) { should match 'contactgroup_name.*admins-sms' } end describe file("#{path_config_dir}/contacts.cfg") do its(:content) { should_not match 'contact_group.*\+non_admins' } its(:content) { should_not match 'contact_group.*null' } end describe file("#{path_config_dir}/hostgroups.cfg") do its(:content) { should match 'all' } its(:content) { should match 'linux' } its(:content) { should match '_default' } its(:content) { should match 'monitoring' } its(:content) { should match 'hostgroup_(a|b|c)' } end describe file("#{path_config_dir}/servicegroups.cfg") do its(:content) { should match "servicegroup_name.*servicegroup_a\n\s*members.*host_a_alt,service_a,host_a_alt,service_b,host_b_alt,service_b,host_b_alt,service_c" } its(:content) { should match "servicegroup_name.*servicegroup_b\n\s*members.*host_b_alt,service_c" } its(:content) { should match "servicegroup_name.*selective_services\n\s*members\s*host_a_alt,selective_service,host_b_alt,selective_service" } end describe file("#{path_config_dir}/templates.cfg") do its(:content) { should match 'define contact {\n\s*name\s*default-contact' } its(:content) { should match 'define host {\n\s*name\s*default-host' } its(:content) { should match 'define host {\n\s*name\s*server' } its(:content) { should match 'define service {\n\s*name\s*default-logfile' } its(:content) { should match 'define service {\n\s*name\s*default-service' } its(:content) { should match 'define service {\n\s*name\s*service-template' } end describe file("#{path_config_dir}/timeperiods.cfg") do its(:content) { should match "define timeperiod {\n\s\stimeperiod_name\s\s24x7" } its(:content) { should match "Joshua Skains\n sunday 09:00-17:00" } end # Test Nagios Daemon describe service(service_name) do it { should be_enabled } it { should be_running } end # Test Nagios Website describe port(80) do it { should be_listening } its('processes') { should include apache_bin } end describe command('wget -qO- --user=admin --password=admin localhost') do its(:stdout) { should match %r{(?i).*<h2>Nagios Core.*</h2>.*} } end # This looks wrong and can't make it work - perhaps someone can take a look or decide to remove this test entirely? # describe command('wget -qO- --user=admin --password=admin localhost`wget -qO- --user=admin --password=admin localhost/side.php | grep tac.cgi | awk -F \'"\' \'{print \$2}\'`') do # its(:stdout) { should match %r{(?i).*<TITLE>\s*Nagios Tactical Monitoring Overview\s*</TITLE>.*} } # end # Test Nagios Website Host Configuration describe command("wget -qO- --user=admin --password=admin \"http://localhost/#{config_cgi_path}?type=hosts&expand=bighost1\" | grep my-event-handler-command") do its(:stdout) { should_not match 'my-event-handler-command' } end describe command("wget -qO- --user=admin --password=admin \"http://localhost/#{config_cgi_path}?type=hosts&expand=bighost2\" | grep my-event-handler-command") do its(:stdout) { should match 'type=command.*my-event-handler-command' } end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/test/smoke/server_source/default_test.rb
test/smoke/server_source/default_test.rb
apache_bin = os.redhat? ? 'httpd' : 'apache2' config_cgi_path = 'nagios/cgi-bin/config.cgi' path_config_dir = '/etc/nagios/conf.d' path_conf_dir = '/etc/nagios' service_name = 'nagios' # Test Nagios Config describe file("#{path_config_dir}/commands.cfg") do its(:content) { should match 'check_all_hostgroup_service' } its(:content) { should match 'check_host_alive' } its(:content) { should match 'check_load' } its(:content) { should match 'check_nagios' } its(:content) { should match 'check_nrpe' } its(:content) { should match 'check_nrpe_alive' } its(:content) { should match 'check_service_(a|b|c)' } its(:content) { should match 'host_notify_by_email' } its(:content) { should match 'host_notify_by_sms_email' } its(:content) { should match 'service_notify_by_email' } end describe file("#{path_conf_dir}/nagios.cfg") do its(:content) { should match 'host_perfdata_command=command_(a|b)' } its(:content) { should match 'use_syslog=0' } end describe file("#{path_conf_dir}/nagios.cfg") do its(:content) { should_not match 'query_socket=' } end describe file("#{path_config_dir}/services.cfg") do its(:content) { should match 'service_description.*all_hostgroup_service' } its(:content) { should match 'service_description.*load' } its(:content) { should match 'service_description.*service_(a|b|c)' } its(:content) { should match 'check_command.*system-load!15,10,5!30,25,20' } its(:content) { should match 'contact_groups.*\+[^ ]+non_admins' } its(:content) { should match 'contact_groups.*null' } its(:content) { should match 'host_name.*\*' } end describe file("#{path_config_dir}/hosts.cfg") do its(:content) { should match 'host_name[ \t]+host_a_alt' } its(:content) { should match 'host_name[ \t]+host_b' } its(:content) { should match 'host_name[ \t]+chefnode_a' } its(:content) { should match 'host_name[ \t]+chefnode_(b|c|d)_alt' } its(:content) { should match '_CUSTOM_HOST_OPTION[ \t]+custom_host_value.*\n}' } its(:content) { should match 'notes[ \t]+configured via chef node attributes' } end describe file("#{path_config_dir}/hosts.cfg") do its(:content) { should_not match 'chefnode_exclude_(arr|str)' } its(:content) { should_not match 'host_name.*\*' } end describe file("#{path_config_dir}/contacts.cfg") do its(:content) { should match 'contact.*(admin|devs|root)' } its(:content) { should match 'contactgroup_name.*admins' } its(:content) { should match 'contactgroup_name.*admins-sms' } end describe file("#{path_config_dir}/contacts.cfg") do its(:content) { should_not match 'contact_group.*\+non_admins' } its(:content) { should_not match 'contact_group.*null' } end describe file("#{path_config_dir}/hostgroups.cfg") do its(:content) { should match 'all' } its(:content) { should match 'linux' } its(:content) { should match '_default' } its(:content) { should match 'monitoring' } its(:content) { should match 'hostgroup_(a|b|c)' } end describe file("#{path_config_dir}/servicegroups.cfg") do its(:content) { should match /servicegroup_name.*servicegroup_a\n\s*members\s+host_a_alt,service_a,host_a_alt,service_b,host_b,service_b,host_b,service_c+/ } its(:content) { should match /servicegroup_name.*servicegroup_b\n\s*members\s+host_b,service_c/ } its(:content) { should match /servicegroup_name.*selective_services\n\s*members\s+host_a_alt,selective_service,host_b,selective_service/ } end describe file("#{path_config_dir}/templates.cfg") do its(:content) { should match 'define contact {\n\s*name\s*default-contact' } its(:content) { should match 'define host {\n\s*name\s*default-host' } its(:content) { should match 'define host {\n\s*name\s*server' } its(:content) { should match 'define service {\n\s*name\s*default-logfile' } its(:content) { should match 'define service {\n\s*name\s*default-service' } its(:content) { should match 'define service {\n\s*name\s*service-template' } end describe file("#{path_config_dir}/timeperiods.cfg") do its(:content) { should match "define timeperiod {\n\s\stimeperiod_name\s\s24x7" } its(:content) { should match "Joshua Skains\n sunday 09:00-17:00" } end # Test Nagios Daemon describe service(service_name) do it { should be_enabled } it { should be_running } end # Test Nagios Website describe port(80) do it { should be_listening } its('processes') { should include apache_bin } end describe command('wget -qO- --user=admin --password=admin localhost') do its(:stdout) { should match %r{(?i).*<title>Nagios: localhost</title>.*} } end # This looks wrong and can't make it work - perhaps someone can take a look or decide to remove this test entirely? # describe command('wget -qO- --user=admin --password=admin localhost`wget -qO- --user=admin --password=admin localhost/side.php | grep tac.cgi | awk -F \'"\' \'{print \$2}\'`') do # its(:stdout) { should match %r{(?i).*<TITLE>\s*Nagios Tactical Monitoring Overview\s*</TITLE>.*} } # end # Test Nagios Website Host Configuration describe command("wget -qO- --user=admin --password=admin \"http://localhost/#{config_cgi_path}?type=hosts&expand=bighost1\" | grep my-event-handler-command") do its(:stdout) { should_not match 'my-event-handler-command' } end # This is broken and should be fixed # describe command("wget -qO- --user=admin --password=admin \"http://localhost/#{config_cgi_path}?type=hosts&expand=bighost2\" | grep my-event-handler-command") do # its(:stdout) { should match 'type=command.*my-event-handler-command' } # end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/test/smoke/default/nagios_website.rb
test/smoke/default/nagios_website.rb
title 'Nagios Website Checks' wget_cmd = 'wget -qO- --user=admin --password=admin http://localhost' install_method = input('install_method') ldap_auth = input('ldap_auth', value: false) cgi_cmd = if install_method == 'source' && os.family == 'debian' "#{wget_cmd}/cgi-bin/nagios" elsif os.family == 'redhat' "#{wget_cmd}/nagios/cgi-bin" elsif os.name == 'debian' "#{wget_cmd}/cgi-bin/nagios4" elsif os.name == 'ubuntu' "#{wget_cmd}/cgi-bin/nagios4" end control 'nagios-website-01' do impact 1.0 title 'should be listening on port 80' desc 'should be listening on port 80' describe port(80) do it { should be_listening } end end control 'nagios-website-02' do impact 1.0 title desc 'should be listening on port 80' only_if { !ldap_auth } describe command(wget_cmd) do its('exit_status') { should eq 0 } its('stdout') do should match(%r{<title>(Nagios: (localhost|nagios)|Nagios Core).*<\/title>}) end end end control 'nagios-website-03' do impact 1.0 title 'should have a CGI (sub) page' desc 'should have a CGI (sub) page' only_if { !ldap_auth } describe command("#{cgi_cmd}/tac.cgi") do its('exit_status') { should eq 0 } its('stdout') do should match(%r{<TITLE>\s*Nagios Tactical Monitoring Overview\s*</TITLE>}) end end end control 'nagios-website-04' do impact 1.0 title 'should not contain eventhandler for bighost1' desc 'should not contain eventhandler for bighost1' only_if { !ldap_auth } describe command("#{cgi_cmd}/config.cgi?'type=hosts&expand=bighost1'") do its('exit_status') { should eq 0 } its('stdout') { should_not match(/.*my-event-handler-command.*/i) } end end control 'nagios-website-05' do impact 1.0 title 'should contain eventhandler for bighost2' desc 'should contain eventhandler for bighost2' only_if { !ldap_auth } describe command("#{cgi_cmd}/config.cgi?'type=hosts&expand=bighost2'") do its('stdout') { should match(/.*my-event-handler-command.*/i) } its('exit_status') { should eq 0 } end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/test/smoke/default/server.rb
test/smoke/default/server.rb
# Inspec test for recipe nagios::server # The Inspec reference, with examples and extensive documentation, can be # found at http://inspec.io/docs/reference/resources/ title 'Nagios Server Checks' install_method = input('install_method') vname = if install_method == 'source' 'nagios' elsif os.name == 'debian' 'nagios4' elsif os.name == 'ubuntu' 'nagios4' end if %w(redhat).include?(os[:family]) path_config_dir = '/etc/nagios/conf.d' path_conf_dir = '/etc/nagios' svc = 'nagios' else path_config_dir = "/etc/#{vname}/conf.d" path_conf_dir = "/etc/#{vname}" svc = vname end control 'nagios-deamon-01' do impact 1.0 title 'nagios is running' desc 'Verify that the nagios service is running' describe service(svc) do it { should be_running } end only_if { !(os.redhat? && os[:release].start_with?('6')) } end control 'nagios-deamon-02' do impact 1.0 title 'nagios is enabled' desc 'Verify that the nagios service is enabled' only_if { %w(redhat ubuntu).include?(os[:family]) } describe service(svc) do it { should be_enabled } end end control 'nagios-config-01' do impact 1.0 title 'commands.cfg' desc 'Validate commands.cfg file' %w(check_all_hostgroup_service check_host_alive check_load check_nagios check_nrpe check_nrpe_alive check_service_a check_service_b check_service_c host_notify_by_email host_notify_by_sms_email service_notify_by_email).each do |line| describe file("#{path_config_dir}/commands.cfg") do its('content') { should match line } end end end control 'nagios-config-02' do impact 1.0 title 'nagios.cfg' desc 'Validate nagios.cfg file' file_nagios_config = [] file_nagios_config << 'host_perfdata_command=command_a' file_nagios_config << 'host_perfdata_command=command_b' file_nagios_config << 'use_syslog=0' file_nagios_config.each do |line| describe file("#{path_conf_dir}/nagios.cfg") do its('content') { should match line } end end end control 'nagios-config-03' do impact 1.0 title 'nagios.cfg' desc 'Validate nagios.cfg file' file_nagios_config = [] file_nagios_config << 'query_socket=' file_nagios_config.each do |line| describe file("#{path_conf_dir}/nagios.cfg") do its('content') { should_not match line } end end end control 'nagios-config-04' do impact 1.0 title 'service.cfg' desc 'Validate service.cfg file' file_services = [] file_services << 'service_description.*all_hostgroup_service' file_services << 'service_description.*load' file_services << 'service_description.*service_a' file_services << 'service_description.*service_b' file_services << 'service_description.*service_c' file_services << 'check_command.*system-load!15,10,5!30,25,20' file_services << 'contact_groups.*\+[^ ]+non_admins' file_services << 'contact_groups.*null' file_services << 'host_name.*\*' file_services.each do |line| describe file("#{path_config_dir}/services.cfg") do its('content') { should match line } end end end control 'nagios-config-05' do impact 1.0 title 'hosts.cfg' desc 'Validate hosts.cfg file' file_hosts = [] file_hosts << 'host_name[ \t]+host_a_alt' file_hosts << 'host_name[ \t]+host_b' ## file_hosts << 'host_name[ \t]+' + `hostname`.split('.').first file_hosts << 'host_name[ \t]+chefnode_a' file_hosts << '_CUSTOM_HOST_OPTION[ \t]+custom_host_value.*\n}' file_hosts << 'notes[ \t]+configured via chef node attributes' file_hosts << 'host_name[ \t]+chefnode_b_alt' file_hosts << 'host_name[ \t]+chefnode_c_alt' file_hosts << 'host_name[ \t]+chefnode_d_alt' file_hosts.each do |line| describe file("#{path_config_dir}/hosts.cfg") do its('content') { should match line } end end end control 'nagios-config-06' do impact 1.0 title 'hosts.cfg exclude' desc 'Validate hosts.cfg file' file_hosts_exclude = [] file_hosts_exclude << 'chefnode_exclude_arr' file_hosts_exclude << 'chefnode_exclude_str' file_hosts_exclude << 'host_name.*\*' file_hosts_exclude.each do |line| describe file("#{path_config_dir}/hosts.cfg") do its('content') { should_not match line } end end end control 'nagios-config-07' do impact 1.0 title 'contacts.cfg' desc 'Validate contacts.cfg file' file_contacts = [] file_contacts << 'contact.*devs' file_contacts << 'contact.*root' file_contacts << 'contact.*admin' file_contacts << 'contactgroup_name.*admins' file_contacts << 'contactgroup_name.*admins-sms' file_contacts.each do |line| describe file("#{path_config_dir}/contacts.cfg") do its('content') { should match line } end end end control 'nagios-config-08' do impact 1.0 title 'contacts.cfg exclude' desc 'Validate contacts.cfg file' file_contacts_exclude = [] file_contacts_exclude << 'contact_group.*\+non_admins' file_contacts_exclude << 'contact_group.*null' file_contacts_exclude.each do |line| describe file("#{path_config_dir}/contacts.cfg") do its('content') { should_not match line } end end end control 'nagios-config-09' do impact 1.0 title 'hostgroups.cfg' desc 'Validate hostgroups.cfg file' file_hostgroups = [] file_hostgroups << 'all' file_hostgroups << 'linux' file_hostgroups << '_default' file_hostgroups << 'monitoring' file_hostgroups << 'hostgroup_a' file_hostgroups << 'hostgroup_b' file_hostgroups << 'hostgroup_c' file_hostgroups.each do |line| describe file("#{path_config_dir}/hostgroups.cfg") do its('content') { should match line } end end end control 'nagios-config-10' do impact 1.0 title 'servicegroups.cfg' desc 'Validate servicegroups.cfg file' file_servicegroups = [] file_servicegroups << 'servicegroup_name.*servicegroup_a\n\s*members.*' \ 'host_a_alt,service_a,host_a_alt,service_b,host_b,service_b,host_b,' \ 'service_c' file_servicegroups << 'servicegroup_name.*servicegroup_b\n\s*members.*' \ 'host_b,service_c' file_servicegroups << 'servicegroup_name.*selective_services\n\s*members\s*' \ '.*host_b,selective_service' file_servicegroups.each do |line| describe file("#{path_config_dir}/servicegroups.cfg") do its('content') { should match line } end end end control 'nagios-config-11' do impact 1.0 title 'templates.cfg' desc 'Validate templates.cfg file' file_templates = [] file_templates << 'define contact {\n\s*name\s*default-contact' file_templates << 'define host {\n\s*name\s*default-host' file_templates << 'define host {\n\s*name\s*server' file_templates << 'define service {\n\s*name\s*default-logfile' file_templates << 'define service {\n\s*name\s*default-service' file_templates << 'define service {\n\s*name\s*service-template' file_templates.each do |line| describe file("#{path_config_dir}/templates.cfg") do its('content') { should match line } end end end control 'nagios-config-12' do impact 1.0 title 'timeperiods.cfg' desc 'Validate timeperiods.cfg file' file_timeperiods = [] file_timeperiods << 'define timeperiod {\n\s*timeperiod_name\s*24x7' file_timeperiods << 'Joshua Skains\n sunday 09:00-17:00' file_timeperiods.each do |line| describe file("#{path_config_dir}/timeperiods.cfg") do its('content') { should match line } end end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/test/smoke/swappable_config/default_test.rb
test/smoke/swappable_config/default_test.rb
path_conf_dir = if os.redhat? '/etc/nagios' else '/etc/nagios4' end describe file("#{path_conf_dir}/nagios.cfg") do it { should exist } its(:content) { should include '# Test that we can swap out config files via attributes' } end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/test/smoke/pagerduty/default_test.rb
test/smoke/pagerduty/default_test.rb
if os.redhat? apache_bin = 'httpd' config_cgi_path = 'nagios/cgi-bin/config.cgi' path_config_dir = '/etc/nagios/conf.d' path_conf_dir = '/etc/nagios' service_name = 'nagios' else apache_bin = 'apache2' config_cgi_path = 'cgi-bin/nagios4/config.cgi' path_config_dir = '/etc/nagios4/conf.d' path_conf_dir = '/etc/nagios4' service_name = 'nagios4' end # Test Nagios Config describe file("#{path_config_dir}/commands.cfg") do its(:content) { should match 'check_all_hostgroup_service' } its(:content) { should match 'check_host_alive' } its(:content) { should match 'check_load' } its(:content) { should match 'check_nagios' } its(:content) { should match 'check_nrpe' } its(:content) { should match 'check_nrpe_alive' } its(:content) { should match 'check_service_(a|b|c)' } its(:content) { should match 'host_notify_by_email' } its(:content) { should match 'host_notify_by_sms_email' } its(:content) { should match 'service_notify_by_email' } end describe file("#{path_conf_dir}/nagios.cfg") do its(:content) { should match 'host_perfdata_command=command_(a|b)' } its(:content) { should match 'use_syslog=0' } end describe file("#{path_conf_dir}/nagios.cfg") do its(:content) { should_not match 'query_socket=' } end describe file("#{path_config_dir}/services.cfg") do its(:content) { should match 'service_description.*all_hostgroup_service' } its(:content) { should match 'service_description.*load' } its(:content) { should match 'service_description.*service_(a|b|c)' } its(:content) { should match 'check_command.*system-load!15,10,5!30,25,20' } its(:content) { should match 'contact_groups.*\+[^ ]+non_admins' } its(:content) { should match 'contact_groups.*null' } its(:content) { should match 'host_name.*\*' } end describe file("#{path_config_dir}/hosts.cfg") do its(:content) { should match 'host_name[ \t]+host_a_alt' } its(:content) { should match 'host_name[ \t]+host_b' } its(:content) { should match 'host_name[ \t]+chefnode_a' } its(:content) { should match 'host_name[ \t]+chefnode_(b|c|d)_alt' } its(:content) { should match '_CUSTOM_HOST_OPTION[ \t]+custom_host_value.*\n}' } its(:content) { should match 'notes[ \t]+configured via chef node attributes' } end describe file("#{path_config_dir}/hosts.cfg") do its(:content) { should_not match 'chefnode_exclude_(arr|str)' } its(:content) { should_not match 'host_name.*\*' } end describe file("#{path_config_dir}/contacts.cfg") do its(:content) { should match 'contact.*(admin|devs|root)' } its(:content) { should match 'contactgroup_name.*admins' } its(:content) { should match 'contactgroup_name.*admins-sms' } end describe file("#{path_config_dir}/contacts.cfg") do its(:content) { should_not match 'contact_group.*\+non_admins' } its(:content) { should_not match 'contact_group.*null' } end describe file("#{path_config_dir}/hostgroups.cfg") do its(:content) { should match 'all' } its(:content) { should match 'linux' } its(:content) { should match '_default' } its(:content) { should match 'monitoring' } its(:content) { should match 'hostgroup_(a|b|c)' } end describe file("#{path_config_dir}/servicegroups.cfg") do its(:content) { should match "servicegroup_name.*servicegroup_a\n\s*members\s+host_a_alt,service_a,host_a_alt,service_b,host_b,service_b,host_b,service_c" } its(:content) { should match "servicegroup_name.*servicegroup_b\n\s*members\s+host_b,service_c" } its(:content) { should match "servicegroup_name.*selective_services\n\s*members\s+host_a_alt,selective_service,host_b,selective_service" } end describe file("#{path_config_dir}/templates.cfg") do its(:content) { should match 'define contact {\n\s*name\s*default-contact' } its(:content) { should match 'define host {\n\s*name\s*default-host' } its(:content) { should match 'define host {\n\s*name\s*server' } its(:content) { should match 'define service {\n\s*name\s*default-logfile' } its(:content) { should match 'define service {\n\s*name\s*default-service' } its(:content) { should match 'define service {\n\s*name\s*service-template' } end describe file("#{path_config_dir}/timeperiods.cfg") do its(:content) { should match "define timeperiod {\n\s\stimeperiod_name\s\s24x7" } its(:content) { should match "Joshua Skains\n sunday 09:00-17:00" } end # Test Nagios Daemon describe service(service_name) do it { should be_enabled } it { should be_running } end # Test Nagios Website describe port(80) do it { should be_listening } its('processes') { should include apache_bin } end describe command('wget -qO- --user=admin --password=admin localhost') do its(:stdout) { should match %r{(?i).*<title>(Nagios: localhost|Nagios Core).*</title>.*} } end # This looks wrong and can't make it work - perhaps someone can take a look or decide to remove this test entirely? # describe command('wget -qO- --user=admin --password=admin localhost`wget -qO- --user=admin --password=admin localhost/side.php | grep tac.cgi | awk -F \'"\' \'{print \$2}\'`') do # its(:stdout) { should match %r{(?i).*<TITLE>\s*Nagios Tactical Monitoring Overview\s*</TITLE>.*} } # end # Test Nagios Website Host Configuration describe command("wget -qO- --user=admin --password=admin \"http://localhost/#{config_cgi_path}?type=hosts&expand=bighost1\" | grep my-event-handler-command") do its(:stdout) { should_not match 'my-event-handler-command' } end describe command("wget -qO- --user=admin --password=admin \"http://localhost/#{config_cgi_path}?type=hosts&expand=bighost2\" | grep my-event-handler-command") do its(:stdout) { should match 'type=command.*my-event-handler-command' } end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/test/smoke/pagerduty/pagerduty_test.rb
test/smoke/pagerduty/pagerduty_test.rb
if os.redhat? command_file = '/var/log/nagios/rw/nagios.cmd' pagerduty_cgi_dir = '/usr/lib64/nagios/cgi-bin' path_config_dir = '/etc/nagios/conf.d' perl_cgi_package = 'perl-CGI' plugin_dir = '/usr/lib64/nagios/plugins' else command_file = '/var/lib/nagios4/rw/nagios.cmd' pagerduty_cgi_dir = '/usr/lib/cgi-bin/nagios4' path_config_dir = '/etc/nagios4/conf.d' perl_cgi_package = 'libcgi-pm-perl' plugin_dir = '/usr/lib/nagios/plugins' end # PagerDuty Configuration describe file("#{path_config_dir}/commands.cfg") do its(:content) { should match 'notify-(host|service)-by-pagerduty' } end describe file("#{path_config_dir}/contacts.cfg") do its(:content) { should match 'contact.*pagerduty' } end describe package(perl_cgi_package) do it { should be_installed } end # Test Pagerduty Integration Script describe command "perl #{plugin_dir}/notify_pagerduty.pl" do its('stderr') { should match /pagerduty_nagios enqueue/ } its('exit_status') { should eq 2 } end describe file("#{pagerduty_cgi_dir}/pagerduty.cgi") do its(:content) { should match "'command_file' => '#{command_file}'" } end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/recipes/default.rb
recipes/default.rb
# # Author:: Joshua Sierles <joshua@37signals.com> # Author:: Joshua Timberman <joshua@chef.io> # Author:: Nathan Haneysmith <nathan@chef.io> # Author:: Seth Chisamore <schisamo@chef.io> # Author:: Tim Smith <tsmith@chef.io> # Cookbook:: nagios # Recipe:: default # # Copyright:: 2009, 37signals # Copyright 2009-2016, Chef Software, Inc. # Copyright 2013-2014, Limelight Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # configure either Apache2 or NGINX case node['nagios']['server']['web_server'] when 'nginx' Chef::Log.info 'Setting up Nagios server via NGINX' include_recipe 'nagios::nginx' when 'apache' Chef::Log.info 'Setting up Nagios server via Apache2' include_recipe 'nagios::apache' when 'none' Chef::Log.info 'Setting up Nagios server without web server' include_recipe 'nagios::server' else Chef::Log.fatal('Unknown web server option provided for Nagios server: ' \ "#{node['nagios']['server']['web_server']} provided. Allowed:" \ "'nginx', 'apache', or 'none'") end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/recipes/_load_default_config.rb
recipes/_load_default_config.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Recipe:: _load_default_config # # Copyright:: 2014, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Find nodes to monitor. # Search in all environments if multi_environment_monitoring is enabled. Chef::Log.info('Beginning search for nodes. This may take some time depending on your node count') multi_env = node['nagios']['monitored_environments'] multi_env_search = multi_env.empty? ? '' : ' AND (chef_environment:' + multi_env.join(' OR chef_environment:') + ')' nodes = if node['nagios']['multi_environment_monitoring'] search(:node, "name:*#{multi_env_search}") else search(:node, "name:* AND chef_environment:#{node.chef_environment}") end if nodes.empty? Chef::Log.info('No nodes returned from search, using this node so hosts.cfg has data') nodes << node end # Pushing current node to prevent empty hosts.cfg Nagios.instance.push(node) # Pushing all nodes into the Nagios.instance model exclude_tag = nagios_array(node['nagios']['exclude_tag_host']) nodes.each do |n| if n.respond_to?('tags') Nagios.instance.push(n) unless nagios_array(n.tags).any? { |tag| exclude_tag.include?(tag) } else Nagios.instance.push(n) end end # 24x7 timeperiod nagios_timeperiod '24x7' do options 'alias' => '24 Hours A Day, 7 Days A Week', 'times' => { 'sunday' => '00:00-24:00', 'monday' => '00:00-24:00', 'tuesday' => '00:00-24:00', 'wednesday' => '00:00-24:00', 'thursday' => '00:00-24:00', 'friday' => '00:00-24:00', 'saturday' => '00:00-24:00' } end # Host checks nagios_command 'check_host_alive' do options 'command_line' => '$USER1$/check_ping -H $HOSTADDRESS$ -w 2000,80% -c 3000,100% -p 1' end # Service checks nagios_command 'check_nagios' do options 'command_line' => '$USER1$/check_nrpe -H $HOSTADDRESS$ -c check_nagios -t 20' end # nrpe remote host checks nagios_command 'check_nrpe_alive' do options 'command_line' => '$USER1$/check_nrpe -H $HOSTADDRESS$ -t 20' end nagios_command 'check_nrpe' do options 'command_line' => '$USER1$/check_nrpe -H $HOSTADDRESS$ -c $ARG1$ -t 20' end # host_notify_by_email command nagios_command 'host_notify_by_email' do options 'command_line' => '/usr/bin/printf "%b" "$LONGDATETIME$\n\n$HOSTALIAS$ $NOTIFICATIONTYPE$ $HOSTSTATE$\n\n$HOSTOUTPUT$\n\nLogin: ssh://$HOSTNAME$" | ' + node['nagios']['server']['mail_command'] + ' -s "$NOTIFICATIONTYPE$ - $HOSTALIAS$ $HOSTSTATE$!" $CONTACTEMAIL$' end # service_notify_by_email command nagios_command 'service_notify_by_email' do options 'command_line' => '/usr/bin/printf "%b" "$LONGDATETIME$ - $SERVICEDESC$ $SERVICESTATE$\n\n$HOSTALIAS$ $NOTIFICATIONTYPE$\n\n$SERVICEOUTPUT$\n\nLogin: ssh://$HOSTNAME$" | ' + node['nagios']['server']['mail_command'] + ' -s "** $NOTIFICATIONTYPE$ - $HOSTALIAS$ - $SERVICEDESC$ - $SERVICESTATE$" $CONTACTEMAIL$' end # host_notify_by_sms_email command nagios_command 'host_notify_by_sms_email' do options 'command_line' => '/usr/bin/printf "%b" "$HOSTALIAS$ $NOTIFICATIONTYPE$ $HOSTSTATE$\n\n$HOSTOUTPUT$" | ' + node['nagios']['server']['mail_command'] + ' -s "$HOSTALIAS$ $HOSTSTATE$!" $CONTACTPAGER$' end # service_notify_by_sms_email command nagios_command 'service_notify_by_sms_email' do options 'command_line' => '/usr/bin/printf "%b" "$SERVICEDESC$ $NOTIFICATIONTYPE$ $SERVICESTATE$\n\n$SERVICEOUTPUT$" | ' + node['nagios']['server']['mail_command'] + ' -s "$HOSTALIAS$ $SERVICEDESC$ $SERVICESTATE$!" $CONTACTPAGER$' end # root contact nagios_contact 'root' do options 'alias' => 'Root', 'service_notification_period' => '24x7', 'host_notification_period' => '24x7', 'service_notification_options' => 'w,u,c,r', 'host_notification_options' => 'd,r', 'service_notification_commands' => 'service_notify_by_email', 'host_notification_commands' => 'host_notify_by_email', 'email' => 'root@localhost' end # admin contact nagios_contact 'admin' do options 'alias' => 'Admin', 'service_notification_period' => '24x7', 'host_notification_period' => '24x7', 'service_notification_options' => 'w,u,c,r', 'host_notification_options' => 'd,r', 'service_notification_commands' => 'service_notify_by_email', 'host_notification_commands' => 'host_notify_by_email' end nagios_contact 'default-contact' do options 'name' => 'default-contact', 'service_notification_period' => '24x7', 'host_notification_period' => '24x7', 'service_notification_options' => 'w,u,c,r,f', 'host_notification_options' => 'd,u,r,f,s', 'service_notification_commands' => 'service_notify_by_email', 'host_notification_commands' => 'host_notify_by_email' end nagios_host 'default-host' do options 'name' => 'default-host', 'notifications_enabled' => 1, 'event_handler_enabled' => 1, 'flap_detection_enabled' => nagios_boolean(nagios_attr(:default_host)[:flap_detection]), 'process_perf_data' => nagios_boolean(nagios_attr(:default_host)[:process_perf_data]), 'retain_status_information' => 1, 'retain_nonstatus_information' => 1, 'notification_period' => '24x7', 'register' => 0, 'action_url' => nagios_attr(:default_host)[:action_url] end nagios_host 'server' do options 'name' => 'server', 'use' => 'default-host', 'check_period' => nagios_attr(:default_host)[:check_period], 'check_interval' => nagios_interval(nagios_attr(:default_host)[:check_interval]), 'retry_interval' => nagios_interval(nagios_attr(:default_host)[:retry_interval]), 'max_check_attempts' => nagios_attr(:default_host)[:max_check_attempts], 'check_command' => nagios_attr(:default_host)[:check_command], 'notification_interval' => nagios_interval(nagios_attr(:default_host)[:notification_interval]), 'notification_options' => nagios_attr(:default_host)[:notification_options], 'contact_groups' => nagios_attr(:default_contact_groups), 'register' => 0 end # Defaut host template Nagios.instance.default_host = node['nagios']['host_template'] # Users # use the users_helper.rb library to build arrays of users and contacts nagios_users = NagiosUsers.new(node) nagios_users.users.each do |item| o = Nagios::Contact.create(item['id']) o.import(item.to_hash) o.import(item['nagios'].to_hash) unless item['nagios'].nil? o.use = 'default-contact' end nagios_contactgroup 'admins' do options 'alias' => 'Nagios Administrators', 'members' => nagios_users.return_user_contacts end nagios_contactgroup 'admins-sms' do options 'alias' => 'Sysadmin SMS', 'members' => nagios_users.return_user_contacts end # Services nagios_service 'default-service' do options 'name' => 'default-service', 'active_checks_enabled' => 1, 'passive_checks_enabled' => 1, 'parallelize_check' => 1, 'obsess_over_service' => 1, 'check_freshness' => 0, 'notifications_enabled' => 1, 'event_handler_enabled' => 1, 'flap_detection_enabled' => nagios_boolean(nagios_attr(:default_service)[:flap_detection]), 'process_perf_data' => nagios_boolean(nagios_attr(:default_service)[:process_perf_data]), 'retain_status_information' => 1, 'retain_nonstatus_information' => 1, 'is_volatile' => 0, 'check_period' => '24x7', 'max_check_attempts' => nagios_attr(:default_service)[:max_check_attempts], 'check_interval' => nagios_interval(nagios_attr(:default_service)[:check_interval]), 'retry_interval' => nagios_interval(nagios_attr(:default_service)[:retry_interval]), 'contact_groups' => nagios_attr(:default_contact_groups), 'notification_options' => 'w,u,c,r', 'notification_interval' => nagios_interval(nagios_attr(:default_service)[:notification_interval]), 'notification_period' => '24x7', 'register' => 0, 'action_url' => nagios_attr(:default_service)[:action_url] end # Default service template Nagios.instance.default_service = 'default-service' # Define the log monitoring template (monitoring logs is very different) nagios_service 'default-logfile' do options 'name' => 'default-logfile', 'use' => 'default-service', 'check_period' => '24x7', 'max_check_attempts' => 1, 'check_interval' => nagios_interval(nagios_attr(:default_service)[:check_interval]), 'retry_interval' => nagios_interval(nagios_attr(:default_service)[:retry_interval]), 'contact_groups' => nagios_attr(:default_contact_groups), 'notification_options' => 'w,u,c,r', 'notification_period' => '24x7', 'register' => 0, 'is_volatile' => 1 end nagios_service 'service-template' do options 'name' => 'service-template', 'max_check_attempts' => nagios_attr(:default_service)[:max_check_attempts], 'check_interval' => nagios_interval(nagios_attr(:default_service)[:check_interval]), 'retry_interval' => nagios_interval(nagios_attr(:default_service)[:retry_interval]), 'notification_interval' => nagios_interval(nagios_attr(:default_service)[:notification_interval]), 'register' => 0 end nagios_resource 'USER1' do options 'value' => node['nagios']['plugin_dir'] end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/recipes/server_source.rb
recipes/server_source.rb
# # Author:: Seth Chisamore <schisamo@chef.io> # Author:: Tim Smith <tsmith@chef.io> # Cookbook:: nagios # Recipe:: server_source # # Copyright:: 2011-2016, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Package pre-reqs build_essential 'install compilation tools' php_install 'nagios' package node['nagios']['php_gd_package'] # the source install of nagios from this recipe does not include embedded perl support # so unless the user explicitly set the p1_file attribute, we want to clear it # Note: the cookbook now defaults to Nagios 4.X which doesn't support embedded perl anyways node.default['nagios']['conf']['p1_file'] = nil package node['nagios']['server']['dependencies'] user node['nagios']['user'] do action :create end web_srv = node['nagios']['server']['web_server'] group node['nagios']['group'] do members [ node['nagios']['user'], web_srv == 'nginx' ? nginx_user : default_apache_user, ] action :create end nagios_version = node['nagios']['server']['version'] node['nagios']['server']['patches'].each do |patch| remote_file "#{Chef::Config[:file_cache_path]}/#{patch}" do source "#{node['nagios']['server']['patch_url']}/#{patch}" end end remote_file 'nagios source file' do path ::File.join(Chef::Config[:file_cache_path], "nagios-#{nagios_version}.tar.gz") source node['nagios']['server']['source_url'] checksum node['nagios']['server']['checksum'] notifies :run, 'execute[compile-nagios]', :immediately end execute 'compile-nagios' do cwd Chef::Config[:file_cache_path] command <<-EOH tar xzf nagios-#{nagios_version}.tar.gz cd nagios-#{nagios_version} ./configure --prefix=/usr \ --mandir=/usr/share/man \ --bindir=/usr/sbin \ --sbindir=#{node['nagios']['cgi-bin']} \ --datadir=#{node['nagios']['docroot']} \ --sysconfdir=#{node['nagios']['conf_dir']} \ --infodir=/usr/share/info \ --libexecdir=#{node['nagios']['plugin_dir']} \ --localstatedir=#{node['nagios']['state_dir']} \ --with-cgibindir=#{node['nagios']['cgi-bin']} \ --enable-event-broker \ --with-nagios-user=#{node['nagios']['user']} \ --with-nagios-group=#{node['nagios']['group']} \ --with-command-user=#{node['nagios']['user']} \ --with-command-group=#{node['nagios']['group']} \ --with-init-dir=/etc/init.d \ --with-lockfile=#{node['nagios']['run_dir']}/#{node['nagios']['server']['vname']}.pid \ --with-mail=/usr/bin/mail \ --with-perlcache \ --with-htmurl=/ \ --with-cgiurl=#{node['nagios']['cgi-path']} make all make install make install-cgis make install-init make install-config make install-commandmode #{node['nagios']['source']['add_build_commands'].join("\n")} EOH action :nothing end directory node['nagios']['config_dir'] do owner 'root' group 'root' mode '0755' recursive true end directory node['nagios']['conf']['check_result_path'] do owner node['nagios']['user'] group node['nagios']['group'] mode '0755' recursive true end %w(cache_dir log_dir run_dir).each do |dir| directory node['nagios'][dir] do recursive true owner node['nagios']['user'] group node['nagios']['group'] mode '0755' end end directory ::File.join(node['nagios']['log_dir'], 'archives') do owner node['nagios']['user'] group node['nagios']['group'] mode '0755' end directory "/usr/lib/#{node['nagios']['server']['vname']}" do owner node['nagios']['user'] group node['nagios']['group'] mode '0755' end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/recipes/pagerduty.rb
recipes/pagerduty.rb
# # Author:: Jake Vanderdray <jvanderdray@customink.com> # Author:: Tim Smith <tsmith@chef.io> # Cookbook:: nagios # Recipe:: pagerduty # # Copyright:: 2011, CustomInk LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. include_recipe 'nagios::server_package' package nagios_pagerduty_packages remote_file "#{node['nagios']['plugin_dir']}/notify_pagerduty.pl" do owner 'root' group 'root' mode '0755' source node['nagios']['pagerduty']['script_url'] action :create_if_missing end template "#{node['nagios']['cgi-bin']}/pagerduty.cgi" do source 'pagerduty.cgi.erb' owner node['nagios']['user'] group node['nagios']['group'] mode '0755' variables( command_file: node['nagios']['conf']['command_file'] ) end nagios_bags = NagiosDataBags.new pagerduty_contacts = nagios_bags.get('nagios_pagerduty') nagios_command 'notify-service-by-pagerduty' do if node['nagios']['pagerduty']['proxy_url'].nil? options 'command_line' => ::File.join(node['nagios']['plugin_dir'], 'notify_pagerduty.pl') + ' enqueue -f pd_nagios_object=service -f pd_description="$HOSTNAME$ : $SERVICEDESC$"' else options 'command_line' => ::File.join(node['nagios']['plugin_dir'], 'notify_pagerduty.pl') + ' enqueue -f pd_nagios_object=service -f pd_description="$HOSTNAME$ : $SERVICEDESC$"' + " --proxy #{node['nagios']['pagerduty']['proxy_url']}" end end nagios_command 'notify-host-by-pagerduty' do if node['nagios']['pagerduty']['proxy_url'].nil? options 'command_line' => ::File.join(node['nagios']['plugin_dir'], 'notify_pagerduty.pl') + ' enqueue -f pd_nagios_object=host -f pd_description="$HOSTNAME$ : $SERVICEDESC$"' else options 'command_line' => ::File.join(node['nagios']['plugin_dir'], 'notify_pagerduty.pl') + ' enqueue -f pd_nagios_object=host -f pd_description="$HOSTNAME$ : $SERVICEDESC$"' + " --proxy #{node['nagios']['pagerduty']['proxy_url']}" end end unless node['nagios']['pagerduty']['key'].nil? || node['nagios']['pagerduty']['key'].empty? nagios_contact 'pagerduty' do options 'alias' => 'PagerDuty Pseudo-Contact', 'service_notification_period' => '24x7', 'host_notification_period' => '24x7', 'service_notification_options' => node['nagios']['pagerduty']['service_notification_options'], 'host_notification_options' => node['nagios']['pagerduty']['host_notification_options'], 'service_notification_commands' => 'notify-service-by-pagerduty', 'host_notification_commands' => 'notify-host-by-pagerduty', 'pager' => node['nagios']['pagerduty']['key'] end end pagerduty_contacts.each do |contact| name = contact['contact'] || contact['id'] nagios_contact name do options 'alias' => "PagerDuty Pseudo-Contact #{name}", 'service_notification_period' => contact['service_notification_period'] || '24x7', 'host_notification_period' => contact['host_notification_period'] || '24x7', 'service_notification_options' => contact['service_notification_options'] || 'w,u,c,r', 'host_notification_options' => contact['host_notification_options'] || 'd,r', 'service_notification_commands' => 'notify-service-by-pagerduty', 'host_notification_commands' => 'notify-host-by-pagerduty', 'pager' => contact['key'] || contact['pagerduty_key'], 'contactgroups' => contact['contactgroups'] end end cron 'Flush Pagerduty' do user node['nagios']['user'] mailto 'root@localhost' command "#{::File.join(node['nagios']['plugin_dir'], 'notify_pagerduty.pl')} flush" end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/recipes/apache.rb
recipes/apache.rb
# # Author:: Tim Smith <tsmith@chef.io> # Cookbook:: nagios # Recipe:: apache # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # node.default['nagios']['server']['web_server'] = 'apache' php_install 'php' apache2_install 'nagios' do listen node['nagios']['enable_ssl'] ? %w(80 443) : %w(80) mpm node['nagios']['apache_mpm'] end apache2_module 'cgi' apache2_module 'rewrite' if apache_mod_php_supported? apache2_mod_php 'nagios' apache_php_handler = 'application/x-httpd-php' else apache2_module 'proxy' apache2_module 'proxy_fcgi' apache2_mod_proxy 'proxy' php_fpm_pool 'nagios' do user default_apache_user group default_apache_group listen_user default_apache_user listen_group default_apache_group end apache_php_handler = "proxy:unix:#{php_fpm_socket}|fcgi://localhost" end apache2_module 'ssl' if node['nagios']['enable_ssl'] apache2_site '000-default' do action :disable notifies :reload, 'apache2_service[nagios]' end template "#{apache_dir}/sites-available/#{node['nagios']['server']['vname']}.conf" do source 'apache2.conf.erb' mode '0644' variables( nagios_url: node['nagios']['url'], https: node['nagios']['enable_ssl'], ssl_cert_file: node['nagios']['ssl_cert_file'], ssl_cert_key: node['nagios']['ssl_cert_key'], apache_log_dir: default_log_dir, apache_php_handler: apache_php_handler ) notifies :restart, 'apache2_service[nagios]' if File.symlink?("#{apache_dir}/sites-enabled/#{node['nagios']['server']['vname']}.conf") end file "#{apache_dir}/conf.d/#{node['nagios']['server']['vname']}.conf" do action :delete end apache2_site node['nagios']['server']['vname'] node.default['nagios']['web_user'] = default_apache_user node.default['nagios']['web_group'] = default_apache_group # configure the appropriate authentication method for the web server case node['nagios']['server_auth_method'] when 'openid' apache2_module 'auth_openid' do notifies :reload, 'apache2_service[nagios]' end when 'cas' apache2_module 'auth_cas' do notifies :reload, 'apache2_service[nagios]' end when 'ldap' package 'mod_ldap' if platform_family?('rhel') %w(ldap authnz_ldap).each do |m| apache2_module m do notifies :reload, 'apache2_service[nagios]' end end when 'htauth' Chef::Log.info('Authentication method htauth configured in server.rb') else Chef::Log.info('Default method htauth configured in server.rb') end apache2_service 'nagios' do action [:enable, :start] subscribes :restart, 'apache2_install[nagios]' subscribes :reload, 'apache2_module[cgi]' subscribes :reload, 'apache2_module[rewrite]' subscribes :reload, 'apache2_mod_php[nagios]' if apache_mod_php_supported? subscribes :reload, 'apache2_module[proxy]' unless apache_mod_php_supported? subscribes :reload, 'apache2_module[proxy_fcgi]' unless apache_mod_php_supported? subscribes :reload, 'apache2_mod_proxy[proxy]' unless apache_mod_php_supported? subscribes :reload, 'apache2_module[ssl]' if node['nagios']['enable_ssl'] end include_recipe 'nagios::server'
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/recipes/server.rb
recipes/server.rb
# # Author:: Joshua Sierles <joshua@37signals.com> # Author:: Joshua Timberman <joshua@chef.io> # Author:: Nathan Haneysmith <nathan@chef.io> # Author:: Seth Chisamore <schisamo@chef.io> # Author:: Tim Smith <tsmith@chef.io> # Cookbook:: nagios # Recipe:: server # # Copyright:: 2009, 37signals # Copyright 2009-2016, Chef Software, Inc. # Copyright 2013-2014, Limelight Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # (COOK-2350) workaround to allow for a nagios server install from source using # (COOK-2350) the override attribute on debian/ubuntu nagios_service_name = if platform_family?('debian') && node['nagios']['server']['install_method'] == 'source' node['nagios']['server']['name'] else node['nagios']['server']['service_name'] end # install nagios service either from source of package include_recipe "nagios::server_#{node['nagios']['server']['install_method']}" # use the users_helper.rb library to build arrays of users and contacts nagios_users = NagiosUsers.new(node) if nagios_users.users.empty? Chef::Log.fatal('Could not find users in the ' \ "\"#{node['nagios']['users_databag']}\"" \ "databag with the \"#{node['nagios']['users_databag_group']}\"" \ ' group. Users must be defined to allow for logins to the UI. ' \ 'Make sure the databag exists and, if you have set the ' \ '"users_databag_group", that users in that group exist.') end if node['nagios']['server_auth_method'] == 'htauth' # setup htpasswd auth directory node['nagios']['conf_dir'] template "#{node['nagios']['conf_dir']}/htpasswd.users" do cookbook node['nagios']['htauth']['template_cookbook'] source node['nagios']['htauth']['template_file'] owner node['nagios']['user'] group node['nagios']['web_group'] mode '0640' variables(nagios_users: nagios_users.users) end end # Setting all general options unless node['nagios'].nil? unless node['nagios']['server'].nil? Nagios.instance.normalize_hostname = node['nagios']['server']['normalize_hostname'] end end Nagios.instance.host_name_attribute = node['nagios']['host_name_attribute'] # loading default configuration data if node['nagios']['server']['load_default_config'] include_recipe 'nagios::_load_default_config' end # loading all databag configurations if node['nagios']['server']['load_databag_config'] include_recipe 'nagios::_load_databag_config' end directory "#{node['nagios']['conf_dir']}/dist" do owner node['nagios']['user'] group node['nagios']['group'] mode '0755' end # Don't run on RHEL since the state directory is the same as the log directory and causes idempotency issues directory node['nagios']['state_dir'] do owner node['nagios']['user'] group node['nagios']['group'] mode '0751' end unless platform_family?('rhel') directory "#{node['nagios']['state_dir']}/rw" do owner node['nagios']['user'] group node['nagios']['web_group'] mode '2710' end cfg_files = "#{node['nagios']['config_dir']}/*_#{node['nagios']['server']['name']}*.cfg" execute 'archive-default-nagios-object-definitions' do command "mv #{cfg_files} #{node['nagios']['conf_dir']}/dist" not_if { Dir.glob(cfg_files).empty? } end directory "#{node['nagios']['conf_dir']}/certificates" do owner node['nagios']['web_user'] group node['nagios']['web_group'] mode '0700' end ssl_code = "umask 077 openssl genrsa 2048 > nagios-server.key openssl req -subj #{node['nagios']['ssl_req']} -new -x509 -nodes -sha1 \ -days 3650 -key nagios-server.key > nagios-server.crt cat nagios-server.key nagios-server.crt > nagios-server.pem" bash 'Create SSL Certificates' do cwd "#{node['nagios']['conf_dir']}/certificates" code ssl_code not_if { ::File.exist?(node['nagios']['ssl_cert_file']) } end nagios_conf node['nagios']['server']['name'] do config_subdir false cookbook node['nagios']['nagios_config']['template_cookbook'] source node['nagios']['nagios_config']['template_file'] variables(nagios_config: node['nagios']['conf']) end nagios_conf 'cgi' do config_subdir false cookbook node['nagios']['cgi']['template_cookbook'] source node['nagios']['cgi']['template_file'] variables(nagios_service_name: nagios_service_name) end # resource.cfg differs on RPM and tarball based systems if platform_family?('rhel') template "#{node['nagios']['resource_dir']}/resource.cfg" do cookbook node['nagios']['resources']['template_cookbook'] source node['nagios']['resources']['template_file'] owner node['nagios']['user'] group node['nagios']['group'] mode '0600' end directory node['nagios']['resource_dir'] do owner 'root' group node['nagios']['group'] mode '0755' end end nagios_conf 'timeperiods' nagios_conf 'contacts' nagios_conf 'commands' nagios_conf 'hosts' nagios_conf 'hostgroups' nagios_conf 'templates' nagios_conf 'services' nagios_conf 'servicegroups' nagios_conf 'servicedependencies' service 'nagios' do service_name nagios_service_name if ::File.exist?("#{nagios_config_dir}/services.cfg") action [:enable, :start] else action :enable end end # Remove distribution included config files that aren't managed via this cookbook zap_directory nagios_distro_config_dir do pattern '*.cfg' end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/recipes/_load_databag_config.rb
recipes/_load_databag_config.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Recipe:: _load_databag_config # # Copyright:: 2014, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Loading all databag information nagios_bags = NagiosDataBags.new hostgroups = nagios_bags.get(node['nagios']['hostgroups_databag']) hostgroups.each do |group| next if group['search_query'].nil? if node['nagios']['multi_environment_monitoring'] query_environments = node['nagios']['monitored_environments'].map do |environment| "chef_environment:#{environment}" end.join(' OR ') result = search(:node, "(#{group['search_query']}) AND (#{query_environments})") else result = search(:node, "#{group['search_query']} AND chef_environment:#{node.chef_environment}") end result.each do |n| n.automatic_attrs['roles'] = [group['hostgroup_name']] Nagios.instance.push(n) end end services = nagios_bags.get(node['nagios']['services_databag']) services.each do |item| next unless item['activate_check_in_environment'].nil? || item['activate_check_in_environment'].include?(node.chef_environment) name = item['service_description'] || item['id'] check_command = name.downcase.start_with?('check_') ? name.downcase : 'check_' + name.downcase command_name = item['check_command'].nil? ? check_command : item['check_command'] service_name = name.downcase.start_with?('check_') ? name.gsub('check_', '') : name.downcase item['check_command'] = command_name nagios_command command_name do options item end nagios_service service_name do options item end end contactgroups = nagios_bags.get(node['nagios']['contactgroups_databag']) contactgroups.each do |item| name = item['contactgroup_name'] || item['id'] nagios_contactgroup name do options item end end eventhandlers = nagios_bags.get(node['nagios']['eventhandlers_databag']) eventhandlers.each do |item| name = item['command_name'] || item['id'] nagios_command name do options item end end contacts = nagios_bags.get(node['nagios']['contacts_databag']) contacts.each do |item| name = item['contact_name'] || item['id'] nagios_contact name do options item end end hostescalations = nagios_bags.get(node['nagios']['hostescalations_databag']) hostescalations.each do |item| name = item['host_description'] || item['id'] nagios_hostescalation name do options item end end hosttemplates = nagios_bags.get(node['nagios']['hosttemplates_databag']) hosttemplates.each do |item| name = item['host_name'] || item['id'] item['name'] = name if item['name'].nil? nagios_host name do options item end end servicedependencies = nagios_bags.get(node['nagios']['servicedependencies_databag']) servicedependencies.each do |item| name = item['service_description'] || item['id'] nagios_servicedependency name do options item end end serviceescalations = nagios_bags.get(node['nagios']['serviceescalations_databag']) serviceescalations.each do |item| name = item['service_description'] || item['id'] nagios_serviceescalation name do options item end end servicegroups = nagios_bags.get(node['nagios']['servicegroups_databag']) servicegroups.each do |item| name = item['servicegroup_name'] || item['id'] nagios_servicegroup name do options item end end templates = nagios_bags.get(node['nagios']['templates_databag']) templates.each do |item| name = item['name'] || item['id'] item['name'] = name nagios_service name do options item end end timeperiods = nagios_bags.get(node['nagios']['timeperiods_databag']) timeperiods.each do |item| name = item['timeperiod_name'] || item['id'] nagios_timeperiod name do options item end end unmanaged_hosts = nagios_bags.get(node['nagios']['unmanagedhosts_databag']) unmanaged_hosts.each do |item| if node['nagios']['multi_environment_monitoring'].nil? next if item['environment'].nil? || item['environment'] != node.chef_environment else envs = node['nagios']['monitored_environments'] next if item['environment'].nil? || !envs.include?(item['environment']) end name = item['host_name'] || item['id'] nagios_host name do options item end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/recipes/server_package.rb
recipes/server_package.rb
# # Author:: Seth Chisamore <schisamo@chef.io> # Author:: Tim Smith <tsmith@chef.io> # Cookbook:: nagios # Recipe:: server_package # # Copyright:: 2011-2016, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # case node['platform_family'] when 'rhel' include_recipe 'yum-epel' if node['nagios']['server']['install_yum-epel'] when 'debian' # Nagios package requires to enter the admin password # We generate it randomly as it's overwritten later in the config templates random_initial_password = rand(36**16).to_s(36) %w(adminpassword adminpassword-repeat).each do |setting| execute "debconf-set-selections::#{node['nagios']['server']['vname']}-cgi::#{node['nagios']['server']['vname']}/#{setting}" do command "echo #{node['nagios']['server']['vname']}-cgi #{node['nagios']['server']['vname']}/#{setting} password #{random_initial_password} | debconf-set-selections" sensitive true not_if "dpkg -l #{node['nagios']['server']['vname']}" end end end package node['nagios']['server']['packages'] # File typically exists on Debian file "#{apache_dir}/conf-enabled/#{node['nagios']['server']['vname']}-cgi.conf" do manage_symlink_source true action :delete end # File typically exists on RHEL file "#{apache_dir}/conf.d/nagios.conf" do action :delete end directory node['nagios']['config_dir'] do owner 'root' group 'root' mode '0755' recursive true end directory node['nagios']['conf']['check_result_path'] do owner node['nagios']['user'] group node['nagios']['group'] mode '0755' recursive true end %w( cache_dir log_dir run_dir ).each do |dir| directory node['nagios'][dir] do recursive true owner node['nagios']['user'] group node['nagios']['group'] mode '0755' end end directory ::File.join(node['nagios']['log_dir'], 'archives') do owner node['nagios']['user'] group node['nagios']['group'] mode '0755' end directory "/usr/lib/#{node['nagios']['server']['vname']}" do owner node['nagios']['user'] group node['nagios']['group'] mode '0755' end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/recipes/nginx.rb
recipes/nginx.rb
# # Author:: Tim Smith <tsmith@chef.io> # Cookbook:: nagios # Recipe:: nginx # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # node.default['nagios']['server']['web_server'] = 'nginx' nginx_install 'nagios' do source platform_family?('rhel') ? 'epel' : 'distro' ohai_plugin_enabled false end nginx_config 'nagios' do default_site_enabled false notifies :restart, 'nginx_service[nagios]', :delayed end php_install 'nagios' php_fpm_pool 'nagios' do user nagios_nginx_user group nagios_nginx_group listen_user nagios_nginx_user listen_group nagios_nginx_group end package nagios_array(node['nagios']['server']['nginx_dispatch']['packages']) if platform_family?('rhel') template '/etc/sysconfig/spawn-fcgi' do source 'spawn-fcgi.erb' notifies :start, 'service[spawn-fcgi]', :delayed variables( nginx_user: nagios_nginx_user ) end end nagios_array(node['nagios']['server']['nginx_dispatch']['services']).each do |svc| service svc do action [:enable, :start] end end dispatch_type = node['nagios']['server']['nginx_dispatch']['type'] nginx_site 'nagios' do template 'nginx.conf.erb' cookbook 'nagios' variables( allowed_ips: node['nagios']['allowed_ips'], cgi: %w(cgi both).include?(dispatch_type), cgi_bin_dir: platform_family?('rhel') ? '/usr/lib64' : '/usr/lib', chef_env: node.chef_environment == '_default' ? 'default' : node.chef_environment, docroot: node['nagios']['docroot'], fqdn: node['fqdn'], htpasswd_file: File.join(node['nagios']['conf_dir'], 'htpasswd.users'), https: node['nagios']['enable_ssl'], listen_port: node['nagios']['http_port'], log_dir: node['nagios']['log_dir'], nagios_url: node['nagios']['url'], nginx_dispatch_cgi_url: node['nagios']['server']['nginx_dispatch']['cgi_url'], nginx_dispatch_php_url: "unix:#{php_fpm_socket}", php: %w(php both).include?(dispatch_type), public_domain: node['public_domain'] || node['domain'], server_name: node['nagios']['server']['name'], server_vname: node['nagios']['server']['vname'], ssl_cert_file: node['nagios']['ssl_cert_file'], ssl_cert_key: node['nagios']['ssl_cert_key'] ) notifies :reload, 'nginx_service[nagios]', :delayed action [:create, :enable] end nginx_service 'nagios' do action :enable delayed_action :start end node.default['nagios']['web_user'] = nagios_nginx_user node.default['nagios']['web_group'] = nagios_nginx_user # configure the appropriate authentication method for the web server case node['nagios']['server_auth_method'] when 'openid' Chef::Log.fatal('OpenID authentication for Nagios is not supported on NGINX') Chef::Log.fatal("Set node['nagios']['server_auth_method'] attribute in your Nagios role") raise 'OpenID authentication not supported on NGINX' when 'cas' Chef::Log.fatal('CAS authentication for Nagios is not supported on NGINX') Chef::Log.fatal("Set node['nagios']['server_auth_method'] attribute in your Nagios role") raise 'CAS authentivation not supported on NGINX' when 'ldap' Chef::Log.fatal('LDAP authentication for Nagios is not supported on NGINX') Chef::Log.fatal("Set node['nagios']['server_auth_method'] attribute in your Nagios role") raise 'LDAP authentication not supported on NGINX' else # setup htpasswd auth Chef::Log.info('Default method htauth configured in server.rb') end include_recipe 'nagios::server'
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/attributes/default.rb
attributes/default.rb
# # Author:: Seth Chisamore <schisamo@chef.io> # Author:: Tim Smith <tsmith@chef.io> # Cookbook:: nagios # Attributes:: default # # Copyright:: 2011-2016, Chef Software, Inc. # Copyright:: 2013-2014, Limelight Networks, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Allow a Nagios server to monitor hosts in multiple environments. default['nagios']['multi_environment_monitoring'] = false default['nagios']['monitored_environments'] = [] default['nagios']['user'] = 'nagios' default['nagios']['group'] = 'nagios' # Default vaules guarantee to exist, override in webserer recipe default['nagios']['web_user'] = 'nagios' default['nagios']['web_group'] = 'nagios' # Allow specifying which interface on clients to monitor (which IP address to monitor) default['nagios']['monitoring_interface'] = nil default['nagios']['htauth']['template_cookbook'] = 'nagios' default['nagios']['htauth']['template_file'] = 'htpasswd.users.erb' default['nagios']['nagios_config']['template_cookbook'] = 'nagios' default['nagios']['nagios_config']['template_file'] = 'nagios.cfg.erb' default['nagios']['resources']['template_cookbook'] = 'nagios' default['nagios']['resources']['template_file'] = 'resource.cfg.erb' default['nagios']['cgi']['template_cookbook'] = 'nagios' default['nagios']['cgi']['template_file'] = 'cgi.cfg.erb' default['nagios']['plugin_dir'] = nagios_plugin_dir # platform specific directories default['nagios']['home'] = nagios_home default['nagios']['conf_dir'] = nagios_conf_dir default['nagios']['resource_dir'] = nagios_conf_dir default['nagios']['config_dir'] = nagios_config_dir default['nagios']['log_dir'] = nagios_log_dir default['nagios']['cache_dir'] = nagios_cache_dir default['nagios']['state_dir'] = nagios_state_dir default['nagios']['run_dir'] = nagios_run_dir default['nagios']['docroot'] = nagios_docroot default['nagios']['cgi-bin'] = nagios_cgi_bin default['nagios']['server']['install_method'] = nagios_install_method default['nagios']['server']['service_name'] = nagios_service_name default['nagios']['server']['mail_command'] = nagios_mail_command default['nagios']['cgi-path'] = nagios_cgi_path # webserver configuration default['nagios']['enable_ssl'] = false default['nagios']['http_port'] = node['nagios']['enable_ssl'] ? '443' : '80' default['nagios']['server_name'] = node['fqdn'] default['nagios']['server']['server_alias'] = nil default['nagios']['ssl_cert_file'] = "#{nagios_conf_dir}/certificates/nagios-server.pem" default['nagios']['ssl_cert_key'] = "#{nagios_conf_dir}/certificates/nagios-server.pem" default['nagios']['ssl_req'] = '/C=US/ST=Several/L=Locality/O=Example/OU=Operations/' \ "CN=#{node['nagios']['server_name']}/emailAddress=ops@#{node['nagios']['server_name']}" default['nagios']['ssl_protocols'] = 'all -SSLv3 -SSLv2' default['nagios']['ssl_ciphers'] = nil # nagios server name and webserver vname. this can be changed to allow for the installation of icinga default['nagios']['server']['name'] = 'nagios' default['nagios']['server']['vname'] = nagios_vname # for server from source installation default['nagios']['server']['version'] = '4.4.6' default['nagios']['server']['checksum'] = 'ab0d5a52caf01e6f4dcd84252c4eb5df5a24f90bb7f951f03875eef54f5ab0f4' default['nagios']['server']['source_url'] = "https://assets.nagios.com/downloads/nagioscore/releases/nagios-#{node['nagios']['server']['version']}.tar.gz" default['nagios']['server']['patches'] = [] default['nagios']['server']['patch_url'] = nil default['nagios']['server']['dependencies'] = nagios_server_dependencies default['nagios']['server']['packages'] = nagios_packages default['nagios']['server']['install_yum-epel'] = platform_family?('rhel') default['nagios']['check_external_commands'] = true default['nagios']['default_contact_groups'] = %w(admins) default['nagios']['default_user_name'] = nil default['nagios']['sysadmin_email'] = 'root@localhost' default['nagios']['sysadmin_sms_email'] = 'root@localhost' default['nagios']['server_auth_method'] = 'htauth' default['nagios']['server_auth_require'] = 'valid-user' default['nagios']['users_databag'] = 'users' default['nagios']['users_databag_group'] = 'sysadmin' default['nagios']['services_databag'] = 'nagios_services' default['nagios']['servicegroups_databag'] = 'nagios_servicegroups' default['nagios']['templates_databag'] = 'nagios_templates' default['nagios']['hosttemplates_databag'] = 'nagios_hosttemplates' default['nagios']['eventhandlers_databag'] = 'nagios_eventhandlers' default['nagios']['unmanagedhosts_databag'] = 'nagios_unmanagedhosts' default['nagios']['serviceescalations_databag'] = 'nagios_serviceescalations' default['nagios']['hostgroups_databag'] = 'nagios_hostgroups' default['nagios']['hostescalations_databag'] = 'nagios_hostescalations' default['nagios']['contacts_databag'] = 'nagios_contacts' default['nagios']['contactgroups_databag'] = 'nagios_contactgroups' default['nagios']['servicedependencies_databag'] = 'nagios_servicedependencies' default['nagios']['timeperiods_databag'] = 'nagios_timeperiods' default['nagios']['host_name_attribute'] = 'hostname' default['nagios']['regexp_matching'] = 0 default['nagios']['host_template'] = 'server' # for cas authentication default['nagios']['cas_login_url'] = 'https://example.com/cas/login' default['nagios']['cas_validate_url'] = 'https://example.com/cas/serviceValidate' default['nagios']['cas_validate_server'] = 'off' default['nagios']['cas_root_proxy_url'] = nil # for apache ldap authentication default['nagios']['ldap_bind_dn'] = nil default['nagios']['ldap_bind_password'] = nil default['nagios']['ldap_url'] = nil default['nagios']['ldap_authoritative'] = nil default['nagios']['ldap_group_attribute'] = nil default['nagios']['ldap_group_attribute_is_dn'] = nil default['nagios']['ldap_verify_cert'] = nil default['nagios']['ldap_trusted_mode'] = nil default['nagios']['ldap_trusted_global_cert'] = nil default['nagios']['templates'] = Mash.new default['nagios']['default_host']['flap_detection'] = true default['nagios']['default_host']['process_perf_data'] = false default['nagios']['default_host']['check_period'] = '24x7' # Provide all interval values in seconds default['nagios']['default_host']['check_interval'] = 15 default['nagios']['default_host']['retry_interval'] = 15 default['nagios']['default_host']['max_check_attempts'] = 1 default['nagios']['default_host']['check_command'] = 'check_host_alive' default['nagios']['default_host']['notification_interval'] = 300 default['nagios']['default_host']['notification_options'] = 'd,u,r' default['nagios']['default_host']['action_url'] = nil default['nagios']['default_service']['check_interval'] = 60 default['nagios']['default_service']['process_perf_data'] = false default['nagios']['default_service']['retry_interval'] = 15 default['nagios']['default_service']['max_check_attempts'] = 3 default['nagios']['default_service']['notification_interval'] = 1200 default['nagios']['default_service']['flap_detection'] = true default['nagios']['default_service']['action_url'] = nil default['nagios']['server']['web_server'] = 'apache' default['nagios']['server']['nginx_dispatch']['type'] = 'both' default['nagios']['server']['nginx_dispatch']['type'] = 'both' default['nagios']['server']['nginx_dispatch']['packages'] = nagios_nginx_dispatch_packages default['nagios']['server']['nginx_dispatch']['services'] = nagios_nginx_dispatch_services default['nagios']['server']['nginx_dispatch']['cgi_url'] = 'unix:/var/run/fcgiwrap.socket' default['nagios']['php_gd_package'] = nagios_php_gd_package default['nagios']['server']['stop_apache'] = false default['nagios']['server']['normalize_hostname'] = false default['nagios']['server']['load_default_config'] = true default['nagios']['server']['load_databag_config'] = true default['nagios']['server']['use_encrypted_data_bags'] = false default['nagios']['cgi']['show_context_help'] = 1 default['nagios']['cgi']['authorized_for_system_information'] = '*' default['nagios']['cgi']['authorized_for_configuration_information'] = '*' default['nagios']['cgi']['authorized_for_system_commands'] = '*' default['nagios']['cgi']['authorized_for_all_services'] = '*' default['nagios']['cgi']['authorized_for_all_hosts'] = '*' default['nagios']['cgi']['authorized_for_all_service_commands'] = '*' default['nagios']['cgi']['authorized_for_all_host_commands'] = '*' default['nagios']['cgi']['default_statusmap_layout'] = 5 default['nagios']['cgi']['default_statuswrl_layout'] = 4 default['nagios']['cgi']['result_limit'] = 100 default['nagios']['cgi']['escape_html_tags'] = 0 default['nagios']['cgi']['action_url_target'] = '_blank' default['nagios']['cgi']['notes_url_target'] = '_blank' default['nagios']['cgi']['lock_author_names'] = 1 default['nagios']['pagerduty']['script_url'] = 'https://raw.github.com/PagerDuty/pagerduty-nagios-pl/master/pagerduty_nagios.pl' default['nagios']['pagerduty']['service_notification_options'] = 'w,u,c,r' default['nagios']['pagerduty']['host_notification_options'] = 'd,r' default['nagios']['pagerduty']['proxy_url'] = nil # atrributes for setting broker lines default['nagios']['brokers'] = {} # attribute defining tag used to exclude hosts default['nagios']['exclude_tag_host'] = '' # Set the prefork module for Apache as PHP is not thread-safe default['nagios']['apache_mpm'] = 'prefork' # attribute to add commands to source build default['nagios']['source']['add_build_commands'] = ['make install-exfoliation'] default['nagios']['allowed_ips'] = []
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/attributes/config.rb
attributes/config.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Attributes:: config # # Copyright:: 2015, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # This class holds all nagios configuration options. # default['nagios']['conf']['log_file'] = "#{nagios_log_dir}/#{node['nagios']['server']['name']}.log" default['nagios']['conf']['cfg_dir'] = node['nagios']['config_dir'] default['nagios']['conf']['object_cache_file'] = "#{nagios_cache_dir}/objects.cache" default['nagios']['conf']['precached_object_file'] = "#{nagios_cache_dir}/objects.precache" default['nagios']['conf']['resource_file'] = "#{nagios_conf_dir}/resource.cfg" default['nagios']['conf']['temp_file'] = "#{nagios_cache_dir}/#{node['nagios']['server']['name']}.tmp" default['nagios']['conf']['temp_path'] = '/tmp' default['nagios']['conf']['status_file'] = "#{nagios_cache_dir}/status.dat" default['nagios']['conf']['status_update_interval'] = '10' default['nagios']['conf']['nagios_user'] = node['nagios']['user'] default['nagios']['conf']['nagios_group'] = node['nagios']['group'] default['nagios']['conf']['enable_notifications'] = '1' default['nagios']['conf']['execute_service_checks'] = '1' default['nagios']['conf']['accept_passive_service_checks'] = '1' default['nagios']['conf']['execute_host_checks'] = '1' default['nagios']['conf']['accept_passive_host_checks'] = '1' default['nagios']['conf']['enable_event_handlers'] = '1' default['nagios']['conf']['log_rotation_method'] = 'd' default['nagios']['conf']['log_archive_path'] = "#{nagios_log_dir}/archives" default['nagios']['conf']['check_external_commands'] = '1' default['nagios']['conf']['command_check_interval'] = '-1' default['nagios']['conf']['command_file'] = "#{nagios_state_dir}/rw/#{node['nagios']['server']['name']}.cmd" default['nagios']['conf']['external_command_buffer_slots'] = '4096' # Deprecated, Starting with Nagios Core 4, this variable has no effect. default['nagios']['conf']['check_for_updates'] = '0' default['nagios']['conf']['lock_file'] = "#{nagios_run_dir}/#{node['nagios']['server']['vname']}.pid" default['nagios']['conf']['retain_state_information'] = '1' default['nagios']['conf']['state_retention_file'] = "#{nagios_state_dir}/retention.dat" default['nagios']['conf']['retention_update_interval'] = '60' default['nagios']['conf']['use_retained_program_state'] = '1' default['nagios']['conf']['use_retained_scheduling_info'] = '1' default['nagios']['conf']['use_syslog'] = '1' default['nagios']['conf']['log_notifications'] = '1' default['nagios']['conf']['log_service_retries'] = '1' default['nagios']['conf']['log_host_retries'] = '1' default['nagios']['conf']['log_event_handlers'] = '1' default['nagios']['conf']['log_initial_states'] = '0' default['nagios']['conf']['log_external_commands'] = '1' default['nagios']['conf']['log_passive_checks'] = '1' default['nagios']['conf']['sleep_time'] = '1' # Deprecated, Starting with Nagios Core 4, this variable has no effect. default['nagios']['conf']['service_inter_check_delay_method'] = 's' default['nagios']['conf']['max_service_check_spread'] = '5' default['nagios']['conf']['service_interleave_factor'] = 's' default['nagios']['conf']['max_concurrent_checks'] = '0' default['nagios']['conf']['check_result_reaper_frequency'] = '10' default['nagios']['conf']['max_check_result_reaper_time'] = '30' default['nagios']['conf']['check_result_path'] = if platform?('centos') && node['platform_version'].to_i >= 7 "#{node['nagios']['home']}/checkresults" else "#{node['nagios']['state_dir']}/spool/checkresults" end default['nagios']['conf']['max_check_result_file_age'] = '3600' default['nagios']['conf']['host_inter_check_delay_method'] = 's' default['nagios']['conf']['max_host_check_spread'] = '5' default['nagios']['conf']['interval_length'] = '1' default['nagios']['conf']['auto_reschedule_checks'] = '0' default['nagios']['conf']['auto_rescheduling_interval'] = '30' default['nagios']['conf']['auto_rescheduling_window'] = '180' default['nagios']['conf']['use_aggressive_host_checking'] = '0' default['nagios']['conf']['translate_passive_host_checks'] = '0' default['nagios']['conf']['passive_host_checks_are_soft'] = '0' default['nagios']['conf']['enable_predictive_host_dependency_checks'] = '1' default['nagios']['conf']['enable_predictive_service_dependency_checks'] = '1' default['nagios']['conf']['cached_host_check_horizon'] = '15' default['nagios']['conf']['cached_service_check_horizon'] = '15' default['nagios']['conf']['use_large_installation_tweaks'] = '0' default['nagios']['conf']['enable_environment_macros'] = '1' default['nagios']['conf']['enable_flap_detection'] = '1' default['nagios']['conf']['low_service_flap_threshold'] = '5.0' default['nagios']['conf']['high_service_flap_threshold'] = '20.0' default['nagios']['conf']['low_host_flap_threshold'] = '5.0' default['nagios']['conf']['high_host_flap_threshold'] = '20.0' default['nagios']['conf']['soft_state_dependencies'] = '0' default['nagios']['conf']['service_check_timeout'] = '60' default['nagios']['conf']['host_check_timeout'] = '30' default['nagios']['conf']['event_handler_timeout'] = '30' default['nagios']['conf']['notification_timeout'] = '30' default['nagios']['conf']['ocsp_timeout'] = '5' default['nagios']['conf']['ochp_timeout'] = '5' default['nagios']['conf']['perfdata_timeout'] = '5' default['nagios']['conf']['obsess_over_services'] = '0' default['nagios']['conf']['obsess_over_hosts'] = '0' default['nagios']['conf']['process_performance_data'] = '0' default['nagios']['conf']['check_for_orphaned_services'] = '1' default['nagios']['conf']['check_for_orphaned_hosts'] = '1' default['nagios']['conf']['check_service_freshness'] = '1' default['nagios']['conf']['service_freshness_check_interval'] = '60' default['nagios']['conf']['check_host_freshness'] = '0' default['nagios']['conf']['host_freshness_check_interval'] = '60' default['nagios']['conf']['additional_freshness_latency'] = '15' default['nagios']['conf']['enable_embedded_perl'] = '1' default['nagios']['conf']['use_embedded_perl_implicitly'] = '1' default['nagios']['conf']['date_format'] = 'iso8601' default['nagios']['conf']['use_timezone'] = 'UTC' default['nagios']['conf']['illegal_object_name_chars'] = '`~!$%^&*|\'"<>?,()=' default['nagios']['conf']['illegal_macro_output_chars'] = '`~$&|\'"<>#' default['nagios']['conf']['use_regexp_matching'] = '0' default['nagios']['conf']['use_true_regexp_matching'] = '0' default['nagios']['conf']['admin_email'] = node['nagios']['sysadmin_email'] default['nagios']['conf']['admin_pager'] = node['nagios']['sysadmin_sms_email'] default['nagios']['conf']['event_broker_options'] = '-1' default['nagios']['conf']['retained_host_attribute_mask'] = '0' default['nagios']['conf']['retained_service_attribute_mask'] = '0' default['nagios']['conf']['retained_process_host_attribute_mask'] = '0' default['nagios']['conf']['retained_process_service_attribute_mask'] = '0' default['nagios']['conf']['retained_contact_host_attribute_mask'] = '0' default['nagios']['conf']['retained_contact_service_attribute_mask'] = '0' default['nagios']['conf']['daemon_dumps_core'] = '0' default['nagios']['conf']['debug_file'] = "#{nagios_state_dir}/#{node['nagios']['server']['name']}.debug" default['nagios']['conf']['debug_level'] = '0' default['nagios']['conf']['debug_verbosity'] = '1' default['nagios']['conf']['max_debug_file_size'] = '1000000' default['nagios']['conf']['cfg_file'] = nil default['nagios']['conf']['query_socket'] = nil default['nagios']['conf']['check_workers'] = nil default['nagios']['conf']['log_current_states'] = nil default['nagios']['conf']['bare_update_check'] = nil default['nagios']['conf']['global_host_event_handler'] = nil default['nagios']['conf']['global_service_event_handler'] = nil default['nagios']['conf']['free_child_process_memory'] = nil default['nagios']['conf']['ocsp_command'] = nil default['nagios']['conf']['ochp_command'] = nil default['nagios']['conf']['host_perfdata_command'] = nil default['nagios']['conf']['service_perfdata_command'] = nil default['nagios']['conf']['host_perfdata_file'] = nil default['nagios']['conf']['service_perfdata_file'] = nil default['nagios']['conf']['host_perfdata_file_template'] = nil default['nagios']['conf']['service_perfdata_file_template'] = nil default['nagios']['conf']['host_perfdata_file_mode'] = nil default['nagios']['conf']['service_perfdata_file_mode'] = nil default['nagios']['conf']['host_perfdata_file_processing_interval'] = nil default['nagios']['conf']['service_perfdata_file_processing_interval'] = nil default['nagios']['conf']['host_perfdata_file_processing_command'] = nil default['nagios']['conf']['service_perfdata_file_processing_command'] = nil default['nagios']['conf']['broker_module'] = nil default['nagios']['conf']['allow_empty_hostgroup_assignment'] = '1' default['nagios']['conf']['service_check_timeout_state'] = 'c' default['nagios']['conf']['p1_file'] = nagios_conf_p1_file
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/spec/source_spec.rb
spec/source_spec.rb
require 'spec_helper' describe 'nagios::default' do cached(:chef_run) do ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '20.04') do |node, server| node.normal['nagios']['server']['install_method'] = 'source' server.create_data_bag('users', 'user1' => { 'id' => 'tsmith', 'groups' => ['sysadmin'], 'nagios' => { 'pager' => 'nagiosadmin_pager@example.com', 'email' => 'nagiosadmin@example.com', }, }, 'user2' => { 'id' => 'bsmith', 'groups' => ['users'], }) end.converge(described_recipe) end before do stub_command('/usr/sbin/apache2 -t').and_return(true) end it 'should include the server_source recipe' do expect(chef_run).to include_recipe('nagios::server_source') end it { expect(chef_run).to install_php_install 'nagios' } it 'should install the php-gd package' do expect(chef_run).to install_package('php7.4-gd') end it 'should include source install dependency packages' do expect(chef_run).to install_package(%w(libssl-dev libgdchart-gd2-xpm-dev bsd-mailx tar unzip)) end it 'should create nagios user and group' do expect(chef_run).to create_user('nagios') expect(chef_run).to create_group('nagios') end it 'should create nagios directories' do expect(chef_run).to create_directory('/etc/nagios') expect(chef_run).to create_directory('/etc/nagios/conf.d') expect(chef_run).to create_directory('/var/cache/nagios') expect(chef_run).to create_directory('/var/log/nagios') expect(chef_run).to create_directory('/var/lib/nagios') expect(chef_run).to create_directory('/var/run/nagios') end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/spec/package_spec.rb
spec/package_spec.rb
require 'spec_helper' describe 'nagios::default' do cached(:chef_run) do ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '20.04') do |_node, server| server.create_data_bag('users', 'user1' => { 'id' => 'tsmith', 'groups' => ['sysadmin'], 'nagios' => { 'pager' => 'nagiosadmin_pager@example.com', 'email' => 'nagiosadmin@example.com', }, }, 'user2' => { 'id' => 'bsmith', 'groups' => ['users'], }) end.converge(described_recipe) end before do stub_command('dpkg -l nagios4').and_return(true) stub_command('/usr/sbin/apache2 -t').and_return(true) end it 'should include the server_package recipe' do expect(chef_run).to include_recipe('nagios::server_package') end it 'should install correction packages' do expect(chef_run).to install_package(%w(nagios4 nagios-nrpe-plugin nagios-images)) end it do expect(chef_run).to enable_service('nagios') end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/spec/default_spec.rb
spec/default_spec.rb
require 'spec_helper' describe 'nagios::default' do cached(:chef_run) do ChefSpec::ServerRunner.new( platform: 'ubuntu', version: '20.04', step_into: %w(nagios_conf nagios_timeperiod) ) do |_node, server| server.create_data_bag( 'users', 'user1' => { 'id' => 'tsmith', 'groups' => ['sysadmin'], 'nagios' => { 'pager' => 'nagiosadmin_pager@example.com', 'email' => 'nagiosadmin@example.com', }, }, 'user2' => { 'id' => 'bsmith', 'groups' => ['users'], }) end.converge(described_recipe) end before do stub_command('dpkg -l nagios4').and_return(true) stub_command('/usr/sbin/apache2 -t').and_return(true) end it 'should create conf_dir' do expect(chef_run).to create_directory('/etc/nagios4') end it 'should template apache2 htpassword file with only admins' do expect(chef_run).to render_file('/etc/nagios4/htpasswd.users') end it 'should template contacts config with valid users' do expect(chef_run).to render_file('/etc/nagios4/conf.d/contacts.cfg').with_content('tsmith') expect(chef_run).not_to render_file('/etc/nagios4/conf.d/contacts.cfg').with_content('bsmith') end it do expect(chef_run).to create_nagios_conf('commands') end it do expect(chef_run).to create_template('/etc/nagios4/conf.d/timeperiods.cfg').with( variables: {} ) end it 'should template nagios config files' do expect(chef_run).to render_file('/etc/nagios4/conf.d/timeperiods.cfg').with_content(/ define timeperiod { timeperiod_name 24x7 alias 24 Hours A Day, 7 Days A Week sunday 00:00-24:00 monday 00:00-24:00 tuesday 00:00-24:00 wednesday 00:00-24:00 thursday 00:00-24:00 friday 00:00-24:00 saturday 00:00-24:00 } /) expect(chef_run).to render_file('/etc/nagios4/conf.d/hosts.cfg').with_content(/ define host { use server host_name Fauxhai hostgroups _default,linux address 10.0.0.2 } /) expect(chef_run).to render_file('/etc/nagios4/conf.d/hostgroups.cfg').with_content(/ define hostgroup { hostgroup_name all alias all members \* } define hostgroup { hostgroup_name _default members Fauxhai } define hostgroup { hostgroup_name linux members Fauxhai } /) expect(chef_run).to render_file('/etc/nagios4/conf.d/servicegroups.cfg') expect(chef_run).to render_file('/etc/nagios4/conf.d/services.cfg') [ %r{^main_config_file=/etc/nagios4/nagios.cfg$}, %r{^physical_html_path=/usr/share/nagios4/htdocs$}, %r{^url_html_path=/nagios4$}, /^show_context_help=1$/, %r{^nagios_check_command=/usr/lib/nagios/plugins/check_nagios /var/cache/nagios4/status.dat 5 '/usr/sbin/nagios4'$}, /^use_authentication=1$/, /^#default_user_name=guest$/, /^authorized_for_system_information=\*$/, /^authorized_for_configuration_information=\*$/, /^authorized_for_system_commands=\*$/, /^authorized_for_all_services=\*$/, /^authorized_for_all_hosts=\*$/, /^authorized_for_all_service_commands=\*$/, /^authorized_for_all_host_commands=\*$/, /^default_statusmap_layout=5$/, /^default_statuswrl_layout=4$/, %r{^ping_syntax=/bin/ping -n -U -c 5 \$HOSTADDRESS\$$}, /^refresh_rate=90$/, /^result_limit=100$/, /^escape_html_tags=0$/, /^action_url_target=_blank$/, /^notes_url_target=_blank$/, /^lock_author_names=1$/, ].each do |line| expect(chef_run).to render_file('/etc/nagios4/cgi.cfg').with_content(line) end expect(chef_run).to render_file('/etc/nagios4/conf.d/templates.cfg') expect(chef_run).to render_file('/etc/nagios4/nagios.cfg').with_content(%r{ log_file=/var/log/nagios4/nagios.log cfg_dir=/etc/nagios4/conf.d object_cache_file=/var/cache/nagios4/objects.cache precached_object_file=/var/cache/nagios4/objects.precache resource_file=/etc/nagios4/resource.cfg temp_file=/var/cache/nagios4/nagios.tmp temp_path=/tmp status_file=/var/cache/nagios4/status.dat status_update_interval=10 nagios_user=nagios nagios_group=nagios enable_notifications=1 execute_service_checks=1 accept_passive_service_checks=1 execute_host_checks=1 accept_passive_host_checks=1 enable_event_handlers=1 log_rotation_method=d log_archive_path=/var/log/nagios4/archives check_external_commands=1 command_check_interval=-1 command_file=/var/lib/nagios4/rw/nagios.cmd external_command_buffer_slots=4096 check_for_updates=0 lock_file=/var/run/nagios4/nagios4.pid retain_state_information=1 state_retention_file=/var/lib/nagios4/retention.dat retention_update_interval=60 use_retained_program_state=1 use_retained_scheduling_info=1 use_syslog=1 log_notifications=1 log_service_retries=1 log_host_retries=1 log_event_handlers=1 log_initial_states=0 log_external_commands=1 log_passive_checks=1 sleep_time=1 service_inter_check_delay_method=s max_service_check_spread=5 service_interleave_factor=s max_concurrent_checks=0 check_result_reaper_frequency=10 max_check_result_reaper_time=30 check_result_path=/var/lib/nagios4/spool/checkresults max_check_result_file_age=3600 host_inter_check_delay_method=s max_host_check_spread=5 interval_length=1 auto_reschedule_checks=0 auto_rescheduling_interval=30 auto_rescheduling_window=180 use_aggressive_host_checking=0 translate_passive_host_checks=0 passive_host_checks_are_soft=0 enable_predictive_host_dependency_checks=1 enable_predictive_service_dependency_checks=1 cached_host_check_horizon=15 cached_service_check_horizon=15 use_large_installation_tweaks=0 enable_environment_macros=1 enable_flap_detection=1 low_service_flap_threshold=5.0 high_service_flap_threshold=20.0 low_host_flap_threshold=5.0 high_host_flap_threshold=20.0 soft_state_dependencies=0 service_check_timeout=60 host_check_timeout=30 event_handler_timeout=30 notification_timeout=30 ocsp_timeout=5 ochp_timeout=5 perfdata_timeout=5 obsess_over_services=0 obsess_over_hosts=0 process_performance_data=0 check_for_orphaned_services=1 check_for_orphaned_hosts=1 check_service_freshness=1 service_freshness_check_interval=60 check_host_freshness=0 host_freshness_check_interval=60 additional_freshness_latency=15 enable_embedded_perl=1 use_embedded_perl_implicitly=1 date_format=iso8601 use_timezone=UTC illegal_object_name_chars=`~!\$%\^&\*\|'"<>\?,\(\)= illegal_macro_output_chars=`~\$&\|'"<># use_regexp_matching=0 use_true_regexp_matching=0 admin_email=root@localhost admin_pager=root@localhost event_broker_options=-1 retained_host_attribute_mask=0 retained_service_attribute_mask=0 retained_process_host_attribute_mask=0 retained_process_service_attribute_mask=0 retained_contact_host_attribute_mask=0 retained_contact_service_attribute_mask=0 daemon_dumps_core=0 debug_file=/var/lib/nagios4/nagios.debug debug_level=0 debug_verbosity=1 max_debug_file_size=1000000 allow_empty_hostgroup_assignment=1 service_check_timeout_state=c p1_file=/usr/lib/nagios4/p1.pl }) expect(chef_run).to render_file('/etc/nagios4/conf.d/servicedependencies.cfg') expect(chef_run).to render_file('/etc/nagios4/conf.d/commands.cfg') end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/spec/spec_helper.rb
spec/spec_helper.rb
require 'chefspec' require 'chefspec/berkshelf' RSpec.configure do |config| config.color = true # Use color in STDOUT config.formatter = :documentation # Use the specified formatter config.log_level = :error # Avoid deprecation notice SPAM end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/libraries/hostdependency.rb
libraries/hostdependency.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Library:: hostdependency # # Copyright:: 2014, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative 'base' class Nagios # # This class holds all methods with regard to hostdependency options, # that are used within nagios configurations. # class Hostdependency < Nagios::Base attr_reader :dependent_name, :dependency_period, :dependent_host_name, :dependent_hostgroup_name, :host_name, :hostgroup_name attr_accessor :inherits_parent, :execution_failure_criteria, :notification_failure_criteria def initialize(name) @dependent_name = name @host_name = {} @hostgroup_name = {} @dependent_host_name = {} @dependent_hostgroup_name = {} super() end def definition get_definition(configured_options, 'hostdependency') end def dependent_host_name_list @dependent_host_name.values.map(&:to_s).sort.join(',') end def dependent_hostgroup_name_list @dependent_hostgroup_name.values.map(&:to_s).sort.join(',') end def host_name_list @host_name.values.map(&:to_s).sort.join(',') end def hostgroup_name_list @hostgroup_name.values.map(&:to_s).sort.join(',') end def import(hash) update_options(hash) update_members(hash, 'host_name', Nagios::Host) update_members(hash, 'hostgroup_name', Nagios::Hostgroup) update_dependency_members(hash, 'dependent_host_name', Nagios::Host) update_dependency_members(hash, 'dependent_hostgroup_name', Nagios::Hostgroup) end def push(obj) case obj when Nagios::Host push_object(obj, @host_name) when Nagios::Hostgroup push_object(obj, @hostgroup_name) when Nagios::Timeperiod @dependency_period = obj end end def push_dependency(obj) case obj when Nagios::Host push_object(obj, @dependent_host_name) when Nagios::Hostgroup push_object(obj, @dependent_hostgroup_name) end end def pop(obj) return if obj == self case obj when Nagios::Host if @host_name.key?(obj.to_s) pop_object(obj, @host_name) pop(self, obj) end when Nagios::Hostgroup if @hostgroup_name.key?(obj.to_s) pop_object(obj, @hostgroup_name) pop(self, obj) end when Nagios::Timeperiod @dependency_period = nil if @dependency_period == obj end end def pop_dependency(obj) return if obj == self case obj when Nagios::Host if @dependent_host_name.key?(obj.to_s) pop_object(obj, @dependent_host_name) pop(self, obj) end when Nagios::Hostgroup if @dependent_hostgroup_name.key?(obj.to_s) pop_object(obj, @dependent_hostgroup_name) pop(self, obj) end end end def self.create(name) Nagios.instance.find(Nagios::Hostdependency.new(name)) end def to_s dependent_name end # check the True/False options # default = nil def inherits_parent=(arg) @inherits_parent = check_bool(arg) end # check other options def execution_failure_criteria=(arg) @execution_failure_criteria = check_state_options(arg, %w(o d u p n), 'execution_failure_criteria') end def notification_failure_criteria=(arg) @notification_failure_criteria = check_state_options(arg, %w(o d u p n), 'notification_failure_criteria') end private def config_options { 'dependent_name' => nil, 'dependency_period' => 'dependency_period', 'dependent_host_name_list' => 'dependent_host_name', 'dependent_hostgroup_name_list' => 'dependent_hostgroup_name', 'host_name_list' => 'host_name', 'hostgroup_name_list' => 'hostgroup_name', 'inherits_parent' => 'inherits_parent', 'execution_failure_criteria' => 'execution_failure_criteria', 'notification_failure_criteria' => 'notification_failure_criteria', } end def merge_members(obj) obj.host_name.each { |m| push(m) } obj.hostgroup_name.each { |m| push(m) } obj.dependent_host_name.each { |m| push_dependency(m) } obj.dependent_hostgroup_name.each { |m| push_dependency(m) } end end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/libraries/command.rb
libraries/command.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Library:: command # # Copyright:: 2014, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative 'base' class Nagios # # This class holds all methods with regard to command options, # that are used within nagios configurations. # class Command < Nagios::Base attr_reader :command_name attr_accessor :command_line def initialize(command_name) cmd = command_name.split('!') @command_name = cmd.shift super() end def definition if blank?(command_line) "# Skipping #{command_name} because command_line is missing." else get_definition(configured_options, 'command') end end def self.create(name) Nagios.instance.find(Nagios::Command.new(name)) end def import(hash) @command_line = hash if hash.class == String hash['command_line'] == hash['command'] unless hash['command'].nil? update_options(hash) end def to_s command_name end private def config_options { 'command_name' => 'command_name', 'command_line' => 'command_line', } end end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/libraries/resource.rb
libraries/resource.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Library:: resource # # Copyright:: 2015, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative 'base' class Nagios # # This class holds all methods with regard to resource options, # that are used within nagios configurations. # class Resource < Nagios::Base attr_reader :key attr_accessor :value def initialize(key, value = nil) @key = key @value = value super() end def definition if blank?(value) "# Skipping #{key} because the value is missing." elsif key =~ /^USER([1-9]|[1-9][0-9]|[1-2][0-4][0-9]|25[0-6])$/ "$#{@key}$=#{@value}" else "# Skipping #{key} because the it's not valid. Use USER[1-256] as your key." end end def self.create(name) Nagios.instance.find(Nagios::Resource.new(name)) end def import(hash) update_options(hash) end def to_s key end end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/libraries/default.rb
libraries/default.rb
# # Author:: Joshua Sierles <joshua@37signals.com> # Author:: Tim Smith <tsmith@chef.io> # Cookbook:: nagios # Library:: default # # Copyright:: 2009, 37signals # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # def nagios_boolean(true_or_false) true_or_false ? '1' : '0' end def nagios_interval(seconds) if seconds.to_i == 0 raise ArgumentError, 'Specified nagios interval of 0 seconds is not allowed' end interval = seconds if node['nagios']['conf']['interval_length'].to_i != 1 interval = seconds.to_f / node['nagios']['conf']['interval_length'] end interval end def nagios_array(exp) return [] if exp.nil? case exp when String [exp] else exp end end def nagios_action_delete?(action) if action.is_a?(Symbol) true if action == :delete || action == :remove elsif action.is_a?(Array) true if action.include?(:delete) || action.include?(:remove) else false end end def nagios_action_create?(action) if action.is_a?(Symbol) true if action == :create || action == :add elsif action.is_a?(Array) true if action.include?(:create) || action.include?(:add) else false end end def nagios_attr(name) node['nagios'][name] end # decide whether to use internal or external IP addresses for this node # if the nagios server is not in the cloud, always use public IP addresses for cloud nodes. # if the nagios server is in the cloud, use private IP addresses for any # cloud servers in the same cloud, public IPs for servers in other clouds # (where other is defined by node['cloud']['provider']) # if the cloud IP is nil then use the standard IP address attribute. This is a work around # for OHAI incorrectly identifying systems on Cisco hardware as being in Rackspace def ip_to_monitor(monitored_host, server_host = node) # if interface to monitor is specified implicitly use that if node['nagios']['monitoring_interface'] && node['network']["ipaddress_#{node['nagios']['monitoring_interface']}"] node['network']["ipaddress_#{node['nagios']['monitoring_interface']}"] # if server is not in the cloud and the monitored host is elsif server_host['cloud'].nil? && monitored_host['cloud'] monitored_host['cloud']['public_ipv4'].include?('.') ? monitored_host['cloud']['public_ipv4'] : monitored_host['ipaddress'] # if server host is in the cloud and the monitored node is as well, but they are not on the same provider elsif server_host['cloud'] && monitored_host['cloud'] && monitored_host['cloud']['provider'] != server_host['cloud']['provider'] monitored_host['cloud']['public_ipv4'].include?('.') ? monitored_host['cloud']['public_ipv4'] : monitored_host['ipaddress'] else monitored_host['ipaddress'] end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/libraries/servicedependency.rb
libraries/servicedependency.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Library:: servicedependency # # Copyright:: 2014, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require_relative 'base' class Nagios # # This class holds all methods with regard to servicedependency options, # that are used within nagios configurations. # class Servicedependency < Nagios::Base attr_reader :service_description, :dependency_period, :dependent_host_name, :dependent_hostgroup_name, :dependent_servicegroup_name, :host_name, :hostgroup_name, :servicegroup_name attr_accessor :dependent_service_description, :inherits_parent, :execution_failure_criteria, :notification_failure_criteria def initialize(name) @service_description = name @host_name = {} @hostgroup_name = {} @servicegroup_name = {} @dependent_host_name = {} @dependent_hostgroup_name = {} @dependent_servicegroup_name = {} super() end def definition get_definition(configured_options, 'servicedependency') end def dependent_host_name_list @dependent_host_name.values.map(&:to_s).sort.join(',') end def dependent_hostgroup_name_list @dependent_hostgroup_name.values.map(&:to_s).sort.join(',') end def dependent_servicegroup_name_list @dependent_servicegroup_name.values.map(&:to_s).sort.join(',') end def host_name_list @host_name.values.map(&:to_s).sort.join(',') end def hostgroup_name_list @hostgroup_name.values.map(&:to_s).sort.join(',') end def servicegroup_name_list @servicegroup_name.values.map(&:to_s).sort.join(',') end def import(hash) update_options(hash) update_members(hash, 'host_name', Nagios::Host) update_members(hash, 'hostgroup_name', Nagios::Hostgroup) update_members(hash, 'servicegroup_name', Nagios::Servicegroup) update_dependency_members(hash, 'dependent_host_name', Nagios::Host) update_dependency_members(hash, 'dependent_hostgroup_name', Nagios::Hostgroup) update_dependency_members(hash, 'dependent_servicegroup_name', Nagios::Servicegroup) end def push(obj) case obj when Nagios::Host push_object(obj, @host_name) when Nagios::Hostgroup push_object(obj, @hostgroup_name) when Nagios::Servicegroup push_object(obj, @servicegroup_name) when Nagios::Timeperiod @dependency_period = obj end end def pop(obj) return if obj == self case obj when Nagios::Host if @host_name.key?(obj.to_s) pop_object(obj, @host_name) pop(self, obj) end when Nagios::Hostgroup if @host_name.key?(obj.to_s) pop_object(obj, @hostgroup_name) pop(self, obj) end when Nagios::Servicegroup if @host_name.key?(obj.to_s) pop_object(obj, @servicegroup_name) pop(self, obj) end when Nagios::Timeperiod @dependency_period = nil if @dependency_period == obj end end def pop_dependency(obj) return if obj == self case obj when Nagios::Host if @dependent_host_name.key?(obj.to_s) pop_object(obj, @dependent_host_name) obj.pop(self) end when Nagios::Hostgroup if @dependent_hostgroup_name.key?(obj.to_s) pop_object(obj, @dependent_hostgroup_name) obj.pop(self) end when Nagios::Servicegroup if @dependent_servicegroup_name.key?(obj.to_s) pop_object(obj, @dependent_servicegroup_name) obj.pop(self) end end end def push_dependency(obj) case obj when Nagios::Host push_object(obj, @dependent_host_name) when Nagios::Hostgroup push_object(obj, @dependent_hostgroup_name) when Nagios::Servicegroup push_object(obj, @dependent_servicegroup_name) end end def self.create(name) Nagios.instance.find(Nagios::Servicedependency.new(name)) end def to_s service_description end # check the True/False options # default = nil def inherits_parent=(arg) @inherits_parent = check_bool(arg) end # check other options def execution_failure_criteria=(arg) @execution_failure_criteria = check_state_options(arg, %w(o w u c p n), 'execution_failure_criteria') end def notification_failure_criteria=(arg) @notification_failure_criteria = check_state_options(arg, %w(o w u c p n), 'notification_failure_criteria') end private def config_options { 'dependency_period' => 'dependency_period', 'dependent_host_name_list' => 'dependent_host_name', 'dependent_hostgroup_name_list' => 'dependent_hostgroup_name', 'dependent_servicegroup_name_list' => 'dependent_servicegroup_name', 'service_description' => 'service_description', 'servicegroup_name_list' => 'servicegroup_name', 'dependent_service_description' => 'dependent_service_description', 'host_name_list' => 'host_name', 'hostgroup_name_list' => 'hostgroup_name', 'inherits_parent' => 'inherits_parent', 'execution_failure_criteria' => 'execution_failure_criteria', 'notification_failure_criteria' => 'notification_failure_criteria', } end def merge_members(obj) obj.host_name.each { |m| push(m) } obj.hostgroup_name.each { |m| push(m) } obj.servicegroup_name.each { |m| push(m) } obj.dependent_host_name.each { |m| push_dependency(m) } obj.dependent_hostgroup_name.each { |m| push_dependency(m) } obj.dependent_servicegroup_name.each { |m| dependent_servicegroup_name(m) } end end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/libraries/contactgroup.rb
libraries/contactgroup.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Library:: contactgroup # # Copyright:: 2014, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative 'nagios' class Nagios # # This class holds all methods with regard to contactgroup options, # that are used within nagios configurations. # class Contactgroup < Nagios::Base attr_reader :contactgroup_name, :members, :contactgroup_members attr_accessor :alias def initialize(contactgroup_name) @contactgroup_name = contactgroup_name @members = {} @contactgroup_members = {} super() end def contactgroup_members_list @contactgroup_members.values.map(&:to_s).sort.join(',') end def self.create(name) Nagios.instance.find(Nagios::Contactgroup.new(name)) end def definition get_definition(configured_options, 'contactgroup') end def import(hash) update_options(hash) update_members(hash, 'members', Nagios::Contact, true) update_members(hash, 'contactgroups_members', Nagios::Contactgroup, true) end def members_list @members.values.map(&:to_s).sort.join(',') end def push(obj) case obj when Nagios::Contact push_object(obj, @members) when Nagios::Contactgroup push_object(obj, @contactgroup_members) end end def pop(obj) return if obj == self case obj when Nagios::Contact if @members.key?(obj.to_s) pop_object(obj, @members) pop(self, obj) end when Nagios::Contactgroup if @contactgroups_members.key?(obj.to_s) pop_object(obj, @contactgroup_members) pop(self, obj) end end end def to_s contactgroup_name end private def config_options { 'name' => 'name', 'use' => 'use', 'contactgroup_name' => 'contactgroup_name', 'members_list' => 'members', 'contactgroup_members_list' => 'contactgroup_members', 'alias' => 'alias', 'register' => 'register', } end def merge_members(obj) obj.members.each { |m| push(m) } obj.contactgroup_members.each { |m| push(m) } end end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/libraries/host.rb
libraries/host.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Library:: host # # Copyright:: 2014, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require_relative 'base' class Nagios # # This class holds all methods with regard to host options, # that are used within nagios configurations. # class Host < Nagios::Base attr_reader :host_name, :parents, :hostgroups, :contacts, :contact_groups, :custom_options attr_accessor :alias, :display_name, :address, :check_command, :initial_state, :max_check_attempts, :check_interval, :retry_interval, :active_checks_enabled, :passive_checks_enabled, :check_period, :obsess_over_host, :check_freshness, :freshness_threshold, :event_handler, :event_handler_enabled, :low_flap_threshold, :high_flap_threshold, :flap_detection_enabled, :flap_detection_options, :process_perf_data, :retain_status_information, :retain_nonstatus_information, :notification_interval, :first_notification_delay, :notification_period, :notification_options, :notifications_enabled, :stalking_options, :notes, :notes_url, :action_url, :icon_image, :icon_image_alt, :vrml_image, :statusmap_image, :_2d_coords, :_3d_coords def initialize(host_name) @host_name = hostname(host_name) @hostgroups = {} @parents = {} @contacts = {} @contact_groups = {} @check_period = nil @notification_period = nil @custom_options = {} super() end def check_period get_timeperiod(@check_period) end # contacts # This is a list of the short names of the contacts that should be notified # whenever there are problems (or recoveries) with this host. # Multiple contacts should be separated by commas. # Useful if you want notifications to go to just a few people and don't want # to configure contact groups. # You must specify at least one contact or contact group in each host definition. def contacts_list @contacts.values.map(&:to_s).sort.join(',') end # contact_groups # This is a list of the short names of the contact groups that should be notified # whenever there are problems (or recoveries) with this host. # Multiple contact groups should be separated by commas. # You must specify at least one contact or contact group in each host definition. def contact_groups_list @contact_groups.values.map(&:to_s).sort.join(',') end def definition configured = configured_options custom_options.each_value { |v| configured[v.to_s] = v.value } get_definition(configured, 'host') end # hostgroups # This directive is used to identify the short name(s) of the hostgroup(s) # that the host belongs to. Multiple hostgroups should be separated by commas. # This directive may be used as an alternative to (or in addition to) # using the members directive in hostgroup definitions. def hostgroups_list @hostgroups.values.map(&:to_s).sort.join(',') end def import(hash) update_options(hash) update_members(hash, 'parents', Nagios::Host) update_members(hash, 'contacts', Nagios::Contact) update_members(hash, 'contact_groups', Nagios::Contactgroup) update_members(hash, 'hostgroups', Nagios::Hostgroup, true) end def notification_period get_timeperiod(@notification_period) end def notifications @notifications_enabled end def notifications=(arg) @notifications_enabled = check_bool(arg) end # parents # This directive is used to define a comma-delimited list of short names of # the "parent" hosts for this particular host. Parent hosts are typically routers, # switches, firewalls, etc. that lie between the monitoring host and a remote hosts. # A router, switch, etc. which is closest to the remote host is considered # to be that host's "parent". # If this host is on the same network segment as the host doing the monitoring # (without any intermediate routers, etc.) the host is considered to be on the local # network and will not have a parent host. def parents_list @parents.values.map(&:to_s).sort.join(',') end def push(obj) case obj when Nagios::Hostgroup push_object(obj, @hostgroups) when Nagios::Host push_object(obj, @parents) when Nagios::Contact push_object(obj, @contacts) when Nagios::Contactgroup push_object(obj, @contact_groups) when Nagios::Timeperiod @check_period = obj @notification_period = obj when Nagios::CustomOption push_object(obj, @custom_options) end end def pop(obj) return if obj == self case obj when Nagios::Hostgroup if @hostgroups.key?(obj.to_s) pop_object(obj, @hostgroups) obj.pop(self) end when Nagios::Host if @parents.key?(obj.to_s) pop_object(obj, @parents) obj.pop(self) end when Nagios::Contact if @contacts.key?(obj.to_s) pop_object(obj, @contacts) obj.pop(self) end when Nagios::Contactgroup if @contact_groups.key?(obj.to_s) pop_object(obj, @contact_groups) obj.pop(self) end when Nagios::Timeperiod @check_period = nil if @check_period == obj @notification_period = nil if @notification_period == obj when Nagios::CustomOption if @custom_options.key?(obj.to_s) pop_object(obj, @custom_options) obj.pop(self) end end end def self.create(name) Nagios.instance.find(Nagios::Host.new(name)) end def to_s host_name end # check the integer options # default = nil def max_check_attempts=(int) @max_check_attempts = check_integer(int) end def check_interval=(int) @check_interval = check_integer(int) end def retry_interval=(int) @retry_interval = check_integer(int) end def freshness_threshold=(int) @freshness_threshold = check_integer(int) end def low_flap_threshold=(int) @low_flap_threshold = check_integer(int) end def high_flap_threshold=(int) @high_flap_threshold = check_integer(int) end def notification_interval=(int) @notification_interval = check_integer(int) end def first_notification_delay=(int) @first_notification_delay = check_integer(int) end # check the True/False options # default = nil def active_checks_enabled=(arg) @active_checks_enabled = check_bool(arg) end def passive_checks_enabled=(arg) @passive_checks_enabled = check_bool(arg) end def obsess_over_host=(arg) @obsess_over_host = check_bool(arg) end def check_freshness=(arg) @check_freshness = check_bool(arg) end def event_handler_enabled=(arg) @event_handler_enabled = check_bool(arg) end def flap_detection_enabled=(arg) @flap_detection_enabled = check_bool(arg) end def process_perf_data=(arg) @process_perf_data = check_bool(arg) end def retain_status_information=(arg) @retain_status_information = check_bool(arg) end def retain_nonstatus_information=(arg) @retain_nonstatus_information = check_bool(arg) end def notifications_enabled=(arg) @notifications_enabled = check_bool(arg) end # check other options # initial_state # By default Nagios will assume that all hosts are in UP states when it starts. # You can override the initial state for a host by using this directive. # Valid options are: # o = UP, # d = DOWN, # u = UNREACHABLE. def initial_state=(arg) @initial_state = check_state_options(arg, %w(o d u), 'initail_state') end # flap_detection_options # This directive is used to determine what host states the flap detection logic will use for this host. # Valid options are a combination of one or more of the following: # o = UP states, # d = DOWN states, # u = UNREACHABLE states. def flap_detection_options=(arg) @flap_detection_options = check_state_options(arg, %w(o d u), 'flap_detection_options') end # stalking_options # This directive determines which host states "stalking" is enabled for. # Valid options are a combination of one or more of the following: # o = stalk on UP states, # d = stalk on DOWN states, # u = stalk on UNREACHABLE states. def stalking_options=(arg) @stalking_options = check_state_options(arg, %w(o d u), 'stalking_options') end # notification_options # This directive is used to determine when notifications for the host should be sent out. # Valid options are a combination of one or more of the following: # d = send notifications on a DOWN state, # u = send notifications on an UNREACHABLE state, # r = send notifications on recoveries (OK state), # f = send notifications when the host starts and stops flapping # s = send notifications when scheduled downtime starts and ends. # If you specify n (none) as an option, no host notifications will be sent out. # If you do not specify any notification options, Nagios will assume that you want notifications # to be sent out for all possible states. # Example: If you specify d,r in this field, notifications will only be sent out when the host # goes DOWN and when it recovers from a DOWN state. def notification_options=(arg) @notification_options = check_state_options(arg, %w(d u r f s n), 'notification_options') end private def config_options { 'name' => 'name', 'use' => 'use', 'host_name' => 'host_name', 'hostgroups_list' => 'hostgroups', 'alias' => 'alias', 'display_name' => 'display_name', 'address' => 'address', 'parents_list' => 'parents', 'check_command' => 'check_command', 'initial_state' => 'initial_state', 'max_check_attempts' => 'max_check_attempts', 'check_interval' => 'check_interval', 'retry_interval' => 'retry_interval', 'active_checks_enabled' => 'active_checks_enabled', 'passive_checks_enabled' => 'passive_checks_enabled', 'check_period' => 'check_period', 'obsess_over_host' => 'obsess_over_host', 'check_freshness' => 'check_freshness', 'freshness_threshold' => 'freshness_threshold', 'event_handler' => 'event_handler', 'event_handler_enabled' => 'event_handler_enabled', 'low_flap_threshold' => 'low_flap_threshold', 'high_flap_threshold' => 'high_flap_threshold', 'flap_detection_enabled' => 'flap_detection_enabled', 'flap_detection_options' => 'flap_detection_options', 'process_perf_data' => 'process_perf_data', 'retain_status_information' => 'retain_status_information', 'retain_nonstatus_information' => 'retain_nonstatus_information', 'contacts_list' => 'contacts', 'contact_groups_list' => 'contact_groups', 'notification_interval' => 'notification_interval', 'first_notification_delay' => 'first_notification_delay', 'notification_period' => 'notification_period', 'notification_options' => 'notification_options', 'notifications_enabled' => 'notifications_enabled', 'notifications' => nil, 'stalking_options' => 'stalking_options', 'notes' => 'notes', 'notes_url' => 'notes_url', 'action_url' => 'action_url', 'icon_image' => 'icon_image', 'icon_image_alt' => 'icon_image_alt', 'vrml_image' => 'vrml_image', 'statusmap_image' => 'statusmap_image', '_2d_coords' => '2d_coords', '_3d_coords' => '3d_coords', 'register' => 'register', } end def merge_members(obj) obj.parents.each { |m| push(m) } obj.contacts.each { |m| push(m) } obj.contact_groups.each { |m| push(m) } obj.hostgroups.each { |m| push(m) } obj.custom_options.each_value { |m| push(m) } end end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/libraries/hostescalation.rb
libraries/hostescalation.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Library:: hostescalation # # Copyright:: 2014, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative 'base' class Nagios # # This class holds all methods with regard to hostescalation options, # that are used within nagios configurations. # class Hostescalation < Nagios::Base attr_reader :host_description, :host_name, :hostgroup_name, :contacts, :contact_groups attr_accessor :first_notification, :last_notification, :notification_interval, :escalation_options, :escalation_period def initialize(name) @host_description = name @contacts = {} @contact_groups = {} @host_name = {} @hostgroup_name = {} super() end def definition get_definition(configured_options, 'hostescalation') end def contacts_list @contacts.values.map(&:to_s).sort.join(',') end def contact_groups_list @contact_groups.values.map(&:to_s).sort.join(',') end def host_name_list @host_name.values.map(&:to_s).sort.join(',') end def hostgroup_name_list @hostgroup_name.values.map(&:to_s).sort.join(',') end def import(hash) update_options(hash) update_members(hash, 'contacts', Nagios::Contact) update_members(hash, 'contact_groups', Nagios::Contactgroup) update_members(hash, 'host_name', Nagios::Host) update_members(hash, 'hostgroup_name', Nagios::Hostgroup) end def push(obj) case obj when Nagios::Host push_object(obj, @host_name) when Nagios::Hostgroup push_object(obj, @hostgroup_name) when Nagios::Contact push_object(obj, @contacts) when Nagios::Contactgroup push_object(obj, @contact_groups) when Nagios::Timeperiod @escalation_period = obj end end def pop(obj) return if obj == self case obj when Nagios::Host if @host_name.key?(obj.to_s) pop_object(obj, @host_name) pop(self, obj) end when Nagios::Hostgroup if @hostgroup_name.key?(obj.to_s) pop_object(obj, @hostgroup_name) pop(self, obj) end when Nagios::Contact if @contacts.key?(obj.to_s) pop_object(obj, @contacts) pop(self, obj) end when Nagios::Contactgroup if @contact_groups.key?(obj.to_s) pop_object(obj, @contact_groups) pop(self, obj) end when Nagios::Timeperiod @escalation_period = nil if @escalation_period == obj end end def to_s host_description end # check the integer options # default = nil def first_notification=(int) @first_notification = check_integer(int) end def last_notification=(int) @last_notification = check_integer(int) end def notification_interval=(int) @notification_interval = check_integer(int) end # check other options def escalation_options=(arg) @escalation_options = check_state_options(arg, %w(d u r), 'escalation_options') end private def config_options { 'name' => 'name', 'use' => 'use', 'host_description' => nil, 'contacts_list' => 'contacts', 'contact_groups_list' => 'contact_groups', 'escalation_period' => 'escalation_period', 'host_name_list' => 'host_name', 'hostgroup_name_list' => 'hostgroup_name', 'escalation_options' => 'escalation_options', 'first_notification' => 'first_notification', 'last_notification' => 'last_notification', 'notification_interval' => 'notification_interval', 'register' => 'register', } end def merge_members(obj) obj.contacts.each { |m| push(m) } obj.host_name.each { |m| push(m) } obj.contact_groups.each { |m| push(m) } obj.hostgroup_name.each { |m| push(m) } end end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/libraries/servicegroup.rb
libraries/servicegroup.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Library:: servicegroup # # Copyright:: 2014, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative 'base' class Nagios # # This class holds all methods with regard to servicegroup options, # that are used within nagios configurations. # class Servicegroup < Nagios::Base attr_reader :servicegroup_name, :members, :servicegroup_members attr_accessor :alias, :notes, :notes_url, :action_url def initialize(servicegroup_name) @servicegroup_name = servicegroup_name @members = {} @servicegroup_members = {} super() end def definition get_definition(configured_options, 'servicegroup') end def import(hash) update_options(hash) update_members(hash, 'members', Nagios::Service, true) update_members(hash, 'servicegroup_members', Nagios::Servicegroup, true) end def members_list result = lookup_hostgroup_members result.join(',') end def push(obj) case obj when Nagios::Service push_object(obj, @members) when Nagios::Servicegroup push_object(obj, @servicegroup_members) end end def pop(obj) return if obj == self case obj when Nagios::Service if @members.key?(obj.to_s) pop_object(obj, @members) pop(self, obj) end when Nagios::Servicegroup if @servicegroup_members.key?(obj.to_s) pop_object(obj, @servicegroup_members) pop(self, obj) end end end def self.create(name) Nagios.instance.find(Nagios::Servicegroup.new(name)) end def servicegroup_members_list @servicegroup_members.values.map(&:to_s).sort.join(',') end def to_s servicegroup_name end private def config_options { 'servicegroup_name' => 'servicegroup_name', 'members_list' => 'members', 'servicegroup_members_list' => 'servicegroup_members', 'alias' => 'alias', 'notes' => 'notes', 'notes_url' => 'notes_url', 'action_url' => 'action_url', } end def convert_hostgroup_hash(hash) result = [] hash.sort.to_h.each do |group_name, group_members| group_members.sort.each do |member| result << member result << group_name end end result end def lookup_hostgroup_members hostgroup_hash = {} @members.each do |service_name, service_obj| hostgroup_array = [] service_obj.hostgroups.each do |hostgroup_name, hostgroup_obj| if service_obj.not_modifiers['hostgroup_name'][hostgroup_name] != '!' hostgroup_array += hostgroup_obj.members.keys else hostgroup_array -= hostgroup_obj.members.keys end end hostgroup_hash[service_name] = hostgroup_array end convert_hostgroup_hash(hostgroup_hash) end def merge_members(obj) obj.members.each { |m| push(m) } obj.servicegroup_members.each { |m| push(m) } end end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/libraries/data_bag_helper.rb
libraries/data_bag_helper.rb
require 'chef/search/query' # simplified access to databags in the nagios cookbook class NagiosDataBags attr_accessor :bag_list def initialize(bag_list = Chef::DataBag.list) @bag_list = bag_list end # Returns an array of data bag items or an empty array # Avoids unecessary calls to search by checking against # the list of known data bags. def get(bag_name) results = [] if @bag_list.include?(bag_name) Chef::Search::Query.new.search(bag_name.to_s, '*:*') { |rows| results << rows } else Chef::Log.info "The #{bag_name} data bag does not exist." end results end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/libraries/users_helper.rb
libraries/users_helper.rb
require 'chef/log' require 'chef/search/query' # Simplify access to list of all valid Nagios users class NagiosUsers attr_accessor :users def initialize(node) @node = node @users = [] user_databag = node['nagios']['users_databag'].to_sym group = node['nagios']['users_databag_group'] if node['nagios']['server']['use_encrypted_data_bags'] load_encrypted_databag(user_databag) else search_databag(user_databag, group) end end def return_user_contacts # add base contacts from nagios_users data bag @users.map do |s| s['id'] end end private def fail_search(user_databag) Chef::Log.fatal("\"#{user_databag}\" databag could not be found.") raise "\"#{user_databag}\" databag could not be found." end def load_encrypted_databag(user_databag) data_bag(user_databag).each_key do |u| d = data_bag_item(user_databag, u) @users << d unless d['nagios'].nil? || d['nagios']['email'].nil? end rescue Net::HTTPClientException fail_search(user_databag) end def search_databag(user_databag, group) Chef::Search::Query.new.search(user_databag, "groups:#{group} NOT action:remove") do |d| @users << d unless d['nagios'].nil? || d['nagios']['email'].nil? end rescue Net::HTTPClientException fail_search(user_databag) end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/libraries/helpers.rb
libraries/helpers.rb
module NagiosCookbook module Helpers def nagios_vname if !node['nagios']['server'].nil? && node['nagios']['server']['install_method'] == 'source' 'nagios' elsif platform_family?('rhel') 'nagios' elsif platform?('debian') 'nagios4' elsif platform?('ubuntu') 'nagios4' end end def nagios_packages if platform_family?('rhel') %w(nagios nagios-plugins-nrpe) elsif platform?('debian') %w(nagios4 nagios-nrpe-plugin nagios-images) elsif platform?('ubuntu') %w(nagios4 nagios-nrpe-plugin nagios-images) end end def nagios_php_gd_package if platform_family?('rhel') 'php-gd' elsif platform?('debian') case node['platform_version'].to_i when 11 'php7.4-gd' else 'php8.2-gd' end elsif platform?('ubuntu') case node['platform_version'].to_f when 20.04 'php7.4-gd' when 22.04 'php8.1-gd' else 'php8.3-gd' end end end def nagios_server_dependencies if platform_family?('rhel') %w(openssl-devel gd-devel tar unzip) else %w(libssl-dev libgdchart-gd2-xpm-dev bsd-mailx tar unzip) end end def nagios_nginx_dispatch_packages if platform_family?('rhel') %w(spawn-fcgi fcgiwrap) else %w(fcgiwrap) end end def nagios_nginx_dispatch_services if platform_family?('rhel') %w(spawn-fcgi) else %w(fcgiwrap) end end def nagios_nginx_user if platform_family?('rhel') 'nginx' else 'www-data' end end def nagios_nginx_group if platform_family?('rhel') 'nginx' else 'www-data' end end def nagios_home if platform_family?('rhel') '/var/spool/nagios' else "/usr/lib/#{nagios_vname}" end end def nagios_plugin_dir case node['platform_family'] when 'debian' '/usr/lib/nagios/plugins' when 'rhel' node['kernel']['machine'] == 'i686' ? '/usr/lib/nagios/plugins' : '/usr/lib64/nagios/plugins' else '/usr/lib/nagios/plugins' end end def nagios_conf_dir "/etc/#{nagios_vname}" end def nagios_config_dir "#{nagios_conf_dir}/conf.d" end def nagios_distro_config_dir if platform_family?('rhel') "#{nagios_conf_dir}/objects" else "#{nagios_conf_dir}/dist" end end def nagios_log_dir "/var/log/#{nagios_vname}" end def nagios_cache_dir if platform_family?('rhel') '/var/log/nagios' else "/var/cache/#{nagios_vname}" end end def nagios_state_dir if platform_family?('rhel') '/var/log/nagios' else "/var/lib/#{nagios_vname}" end end def nagios_run_dir if platform_family?('rhel') if platform?('centos') && node['platform_version'].to_i < 7 '/var/run' else '/var/run/nagios' end else "/var/run/#{nagios_vname}" end end def nagios_docroot if platform_family?('rhel') '/usr/share/nagios/html' else "/usr/share/#{nagios_vname}/htdocs" end end def nagios_cgi_bin if platform_family?('rhel') '/usr/lib64/nagios/cgi-bin/' else "/usr/lib/cgi-bin/#{nagios_vname}" end end def nagios_service_name nagios_vname end def nagios_mail_command if platform_family?('rhel') '/bin/mail' else '/usr/bin/mail' end end def nagios_cgi_path if platform_family?('rhel') '/nagios/cgi-bin/' else "/cgi-bin/#{nagios_service_name}" end end def nagios_check_result_path if platform?('centos') && node['platform_version'].to_i >= 7 "#{nagios_home}/checkresults" else "#{nagios_state_dir}/spool/checkresults" end end def nagios_conf_p1_file case node['platform_family'] when 'debian' "#{nagios_home}/p1.pl" when 'rhel' '/usr/sbin/p1.pl' else "#{nagios_home}/p1.pl" end end def nagios_install_method if platform_family?('rhel', 'debian') 'package' else 'source' end end def nagios_pagerduty_packages case node['platform_family'] when 'rhel' %w(perl-CGI perl-JSON perl-libwww-perl perl-Sys-Syslog) when 'debian' %w(libcgi-pm-perl libjson-perl libwww-perl) end end end end Chef::DSL::Recipe.include ::NagiosCookbook::Helpers Chef::Resource.include ::NagiosCookbook::Helpers Chef::Node.include ::NagiosCookbook::Helpers
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/libraries/serviceescalation.rb
libraries/serviceescalation.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Library:: serviceescalation # # Copyright:: 2014, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative 'base' class Nagios # # This class holds all methods with regard to serviceescalation options, # that are used within nagios configurations. # class Serviceescalation < Nagios::Base attr_reader :service_description, :host_name, :hostgroup_name, :servicegroup_name, :contacts, :contact_groups attr_accessor :first_notification, :last_notification, :notification_interval, :escalation_options, :escalation_period def initialize(name) @service_description = name @contacts = {} @contact_groups = {} @host_name = {} @hostgroup_name = {} @servicegroup_name = {} super() end def definition configured = configured_options unless blank?(servicegroup_name) configured.delete('service_description') configured.delete('host_name') end get_definition(configured, 'serviceescalation') end def contacts_list @contacts.values.map(&:to_s).sort.join(',') end def contact_groups_list @contact_groups.values.map(&:to_s).sort.join(',') end def host_name_list @host_name.values.map(&:to_s).sort.join(',') end def hostgroup_name_list @hostgroup_name.values.map(&:to_s).sort.join(',') end def servicegroup_name_list @servicegroup_name.values.map(&:to_s).sort.join(',') end def import(hash) update_options(hash) update_members(hash, 'contacts', Nagios::Contact) update_members(hash, 'contact_groups', Nagios::Contactgroup) update_members(hash, 'host_name', Nagios::Host) update_members(hash, 'hostgroup_name', Nagios::Hostgroup) update_members(hash, 'servicegroup_name', Nagios::Servicegroup) end def push(obj) case obj when Nagios::Host push_object(obj, @host_name) when Nagios::Hostgroup push_object(obj, @hostgroup_name) when Nagios::Servicegroup push_object(obj, @servicegroup_name) when Nagios::Contact push_object(obj, @contacts) when Nagios::Contactgroup push_object(obj, @contact_groups) when Nagios::Timeperiod @escalation_period = obj end end def pop(obj) return if obj == self case obj when Nagios::Host if @host_name.key?(obj.to_s) pop_object(obj, @host_name) pop(self, obj) end when Nagios::Hostgroup if @hostgroup_name.key?(obj.to_s) pop_object(obj, @hostgroup_name) pop(self, obj) end when Nagios::Servicegroup if @servicegroup_name.key?(obj.to_s) pop_object(obj, @servicegroup_name) pop(self, obj) end when Nagios::Contact if @contacts.key?(obj.to_s) pop_object(obj, @contacts) pop(self, obj) end when Nagios::Contactgroup if @contact_groups.key?(obj.to_s) pop_object(obj, @contact_groups) pop(self, obj) end when Nagios::Timeperiod @escalation_period = nil if @escalation_period == obj end end def to_s service_description end # check the integer options # default = nil def first_notification=(int) @first_notification = check_integer(int) end def last_notification=(int) @last_notification = check_integer(int) end def notification_interval=(int) @notification_interval = check_integer(int) end # check other options def escalation_options=(arg) @escalation_options = check_state_options(arg, %w(w u c r), 'escalation_options') end private def config_options { 'name' => 'name', 'use' => 'use', 'service_description' => 'service_description', 'contacts_list' => 'contacts', 'contact_groups_list' => 'contact_groups', 'escalation_period' => 'escalation_period', 'host_name_list' => 'host_name', 'hostgroup_name_list' => 'hostgroup_name', 'servicegroup_name_list' => 'servicegroup_name', 'escalation_options' => 'escalation_options', 'first_notification' => 'first_notification', 'last_notification' => 'last_notification', 'notification_interval' => 'notification_interval', 'register' => 'register', } end def merge_members(obj) obj.contacts.each { |m| push(m) } obj.host_name.each { |m| push(m) } obj.contact_groups.each { |m| push(m) } obj.hostgroup_name.each { |m| push(m) } obj.servicegroup_name.each { |m| push(m) } end end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/libraries/base.rb
libraries/base.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Library:: base # # Copyright:: 2014, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # class Nagios # This class it the base for all other Nagios classes. # It provides common methods to prevent code duplication. class Base attr_accessor :register, :name, :use, :not_modifiers def initialize @add_modifiers = {} @not_modifiers = Hash.new { |h, k| h[k] = {} } end def merge!(obj) merge_members(obj) merge_attributes(obj) end def merge_members!(obj) merge_members(obj) end def register return @register if blank?(@name) 0 end def register=(arg) @register = check_bool(arg) end def use default_template end private def blank?(expr) return true if expr.nil? case expr when 'String', String return true if expr == '' when 'Array', 'Hash', Array, Hash return true if expr.empty? else false end false end def check_bool(arg) return 1 if arg.class == TrueClass return 1 if arg.to_s =~ /^y|yes|true|on|1$/i 0 end def check_integer(int) return int.to_i if int.class == String int end def check_state_option(arg, options, entry) if options.include?(arg) Chef::Log.debug("#{self.class} #{self} adding option #{arg} for entry #{entry}") else Chef::Log.fail("#{self.class} #{self} object error: Unknown option #{arg} for entry #{entry}") raise 'Unknown option' end end def check_state_options(arg, options, entry) if arg.class == String check_state_options(arg.split(','), options, entry) elsif arg.class == Array arg.each { |a| check_state_option(a.strip, options, entry) }.join(',') else arg end end def check_use_and_name(default) return if default.nil? return if to_s == default.to_s default end def default_template return @use unless @use.nil? return if @name case self when Nagios::Command check_use_and_name(Nagios.instance.default_command) when Nagios::Contactgroup check_use_and_name(Nagios.instance.default_contactgroup) when Nagios::Contact check_use_and_name(Nagios.instance.default_contact) when Nagios::Hostgroup check_use_and_name(Nagios.instance.default_hostgroup) when Nagios::Host check_use_and_name(Nagios.instance.default_host) when Nagios::Servicegroup check_use_and_name(Nagios.instance.default_servicegroup) when Nagios::Service check_use_and_name(Nagios.instance.default_service) when Nagios::Timeperiod check_use_and_name(Nagios.instance.default_timeperiod) end end def get_commands(obj) obj.map(&:to_s).join(',') end def configured_option(method, option) value = send(method) return if blank?(value) value = value.split(',') if value.is_a? String value = value.map do |e| (@not_modifiers[option][e] || '') + e end.join(',') if value.is_a? Array value end def configured_options configured = {} config_options.each do |m, o| next if o.nil? value = configured_option(m, o) next if value.nil? configured[o] = value end configured end def get_definition(options, group) return if to_s == '*' return if to_s == 'null' return if to_s.start_with? '!' d = ["define #{group} {"] d += get_definition_options(options) d += ['}'] d.join("\n") end def get_definition_options(options) r = [] longest = get_longest_option(options) options.each do |k, v| k = k.to_s v = (@add_modifiers[k] || '') + v.to_s diff = longest - k.length r.push(k.rjust(k.length + 2) + v.rjust(v.length + diff + 2)) end r end def get_longest_option(options) longest = 0 options.each_key do |k| longest = k.length if longest < k.length end longest end def get_members(option, object) members = [] case option when String members = object == Nagios::Command ? [option] : option.split(',') members.map(&:strip!) when Array members = option else Chef::Log.fail("Nagios fail: Use an Array or comma seperated String for option: #{option} within #{self.class}") raise 'Use an Array or comma seperated String for option' end members end def get_timeperiod(obj) return if obj.nil? return obj.to_s if obj.class == Nagios::Timeperiod obj end def merge_attributes(obj) config_options.each_key do |m| n = obj.send(m) next if n.nil? m += '=' send(m, n) if respond_to?(m) end end def merge_members(obj) Chef::Log.debug("Nagios debug: The method merge_members is not supported by #{obj.class}") end def push(obj) Chef::Log.debug("Nagios debug: Cannot push #{obj} into #{self.class}") end def push_object(obj, hash) return if hash.key?('null') if obj.to_s == 'null' hash.clear hash[obj.to_s] = obj elsif hash[obj.to_s].nil? hash[obj.to_s] = obj else Chef::Log.debug("Nagios debug: #{self.class} already contains #{obj.class} with name: #{obj}") end end def pop_object(obj, hash) if hash.key?(obj.to_s) hash.delete(obj.to_s) else Chef::Log.debug("Nagios debug: #{self.class} does not contain #{obj.class} with name: #{obj}") end end def notification_commands(obj) commands = [] case obj when Nagios::Command commands.push(obj) when Array obj.each { |o| commands += notification_commands(o) } when String obj.split(',').each do |o| c = Nagios::Command.new(o.strip) n = Nagios.instance.find(c) if c == n Chef::Log.fail("#{self.class} fail: Cannot find command #{o} please define it first.") raise "#{self.class} fail: Cannot find command #{o} please define it first." else commands.push(n) end end end commands end def hostname(name) if Nagios.instance.normalize_hostname name.downcase else name end end def update_options(hash) return if blank?(hash) update_hash_options(hash) if hash.respond_to?('each_pair') end def update_hash_options(hash) hash.each do |k, v| push(Nagios::CustomOption.new(k.upcase, v)) if k.to_s.start_with?('_') m = k.to_s + '=' send(m, v) if respond_to?(m) end end def update_members(hash, option, object, remote = false) return if blank?(hash) || hash[option].nil? if hash[option].is_a?(String) && hash[option].to_s.start_with?('+') @add_modifiers[option] = '+' hash[option] = hash[option][1..-1] end get_members(hash[option], object).each do |member| if member.start_with?('!') member = member[1..-1] @not_modifiers[option][member] = '!' end n = Nagios.instance.find(object.new(member)) push(n) n.push(self) if remote end end def update_dependency_members(hash, option, object) return if blank?(hash) || hash[option].nil? get_members(hash[option], object).each do |member| push_dependency(Nagios.instance.find(object.new(member))) end end end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/libraries/timeperiod.rb
libraries/timeperiod.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Library:: timeperiod # # Copyright:: 2014, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative 'base' class Nagios # # This class holds all methods with regard to timeperiodentries, # that are used within the timeperiod nagios configurations. # class Timeperiodentry attr_reader :moment, :period def initialize(moment, period) @moment = moment @period = check_period(period) end def to_s moment end private def check_period(period) return period if period =~ /^(([01]?[0-9]|2[0-3])\:[0-5][0-9]-([01]?[0-9]|2[0-4])\:[0-5][0-9],?)*$/ nil end end # # This class holds all methods with regard to timeperiod options, # that are used within nagios configurations. # class Timeperiod < Nagios::Base attr_reader :timeperiod_name attr_accessor :alias, :periods, :exclude def initialize(timeperiod_name) @timeperiod_name = timeperiod_name @periods = {} @exclude = {} super() end def self.create(name) Nagios.instance.find(Nagios::Timeperiod.new(name)) end def definition configured = configured_options periods.each_value { |v| configured[v.moment] = v.period } get_definition(configured, 'timeperiod') end # exclude # This directive is used to specify the short names of other timeperiod definitions # whose time ranges should be excluded from this timeperiod. # Multiple timeperiod names should be separated with a comma. def exclude @exclude.values.map(&:to_s).sort.join(',') end def import(hash) update_options(hash) if hash['times'].respond_to?('each_pair') hash['times'].each { |k, v| push(Nagios::Timeperiodentry.new(k, v)) } end update_members(hash, 'exclude', Nagios::Timeperiod) end def push(obj) case obj when Nagios::Timeperiod push_object(obj, @exclude) when Nagios::Timeperiodentry push_object(obj, @periods) unless obj.period.nil? end end def pop(obj) return if obj == self case obj when Nagios::Timeperiod if @exclude.key?(obj.to_s) pop_object(obj, @exclude) pop(self, obj) end when Nagios::Timeperiodentry if @periods.key?(obj.to_s) pop_object(obj, @periods) pop(self, obj) end end end def to_s timeperiod_name end # [weekday] # The weekday directives ("sunday" through "saturday")are comma-delimited # lists of time ranges that are "valid" times for a particular day of the week. # Notice that there are seven different days for which you can define time # ranges (Sunday through Saturday). Each time range is in the form of # HH:MM-HH:MM, where hours are specified on a 24 hour clock. # For example, 00:15-24:00 means 12:15am in the morning for this day until # 12:00am midnight (a 23 hour, 45 minute total time range). # If you wish to exclude an entire day from the timeperiod, simply do not include # it in the timeperiod definition. # [exception] # You can specify several different types of exceptions to the standard rotating # weekday schedule. Exceptions can take a number of different forms including single # days of a specific or generic month, single weekdays in a month, or single calendar # dates. You can also specify a range of days/dates and even specify skip intervals # to obtain functionality described by "every 3 days between these dates". # Rather than list all the possible formats for exception strings, I'll let you look # at the example timeperiod definitions above to see what's possible. # Weekdays and different types of exceptions all have different levels of precedence, # so its important to understand how they can affect each other. private def config_options { 'timeperiod_name' => 'timeperiod_name', 'alias' => 'alias', 'exclude' => 'exclude', } end def merge_members(obj) obj.periods.each { |m| push(m) } obj.exclude.each { |m| push(m) } end end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/libraries/hostgroup.rb
libraries/hostgroup.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Library:: hostgroup # # Copyright:: 2014, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative 'base' class Nagios # # This class holds all methods with regard to hostgroup options, # that are used within nagios configurations. # class Hostgroup < Nagios::Base attr_reader :hostgroup_name, :members, :hostgroup_members attr_accessor :alias, :notes, :notes_url, :action_url def initialize(hostgroup_name) @hostgroup_name = hostgroup_name @members = {} @hostgroup_members = {} super() end def definition get_definition(configured_options, 'hostgroup') end def hostgroup_members_list @hostgroup_members.values.map(&:to_s).sort.join(',') end def import(hash) update_options(hash) update_members(hash, 'members', Nagios::Host, true) update_members(hash, 'hostgroups_members', Nagios::Hostgroup, true) end def members_list @members.values.map(&:to_s).sort.join(',') end def push(obj) case obj when Nagios::Host push_object(obj, @members) when Nagios::Hostgroup push_object(obj, @hostgroup_members) end end def pop(obj) return if obj == self case obj when Nagios::Host if @members.key?(obj.to_s) pop_object(obj, @members) obj.pop(obj) end when Nagios::Hostgroup if @hostgroups_members.key?(obj.to_s) pop_object(obj, @hostgroup_members) obj.pop(obj) end end end def self.create(name) Nagios.instance.find(Nagios::Hostgroup.new(name)) end def to_s hostgroup_name end private def config_options { 'name' => 'name', 'use' => 'use', 'hostgroup_name' => 'hostgroup_name', 'members_list' => 'members', 'hostgroup_members_list' => 'hostgroup_members', 'alias' => 'alias', 'notes' => 'notes', 'notes_url' => 'notes_url', 'action_url' => 'action_url', 'register' => 'register', } end def merge_members(obj) obj.members.each { |m| push(m) } obj.hostgroup_members.each { |m| push(m) } end end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/libraries/service.rb
libraries/service.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Library:: service # # Copyright:: 2014, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require_relative 'base' class Nagios # # This class holds all methods with regard to servicedependency options, # that are used within nagios configurations. # class Service < Nagios::Base attr_reader :service_description, :host_name, :hostgroup_name, :contacts, :contact_groups, :check_command, :servicegroups, :hostgroups, :custom_options attr_accessor :display_name, :is_volatile, :initial_state, :max_check_attempts, :check_interval, :retry_interval, :active_checks_enabled, :passive_checks_enabled, :check_period, :obsess_over_service, :check_freshness, :freshness_threshold, :event_handler, :event_handler_enabled, :low_flap_threshold, :high_flap_threshold, :flap_detection_enabled, :flap_detection_options, :process_perf_data, :retain_status_information, :retain_nonstatus_information, :notification_interval, :first_notification_delay, :notification_period, :notification_options, :notifications_enabled, :parallelize_check, :stalking_options, :notes, :notes_url, :action_url, :icon_image, :icon_image_alt def initialize(service_description) @service_description = service_description srv = service_description.split('!') @check_command = srv.shift @arguments = srv @servicegroups = {} @contacts = {} @contact_groups = {} @hostgroups = {} @hosts = {} @custom_options = {} super() end def check_command if blank?(@arguments) @check_command.to_s else @check_command.to_s + '!' + @arguments.join('!') end end def check_command=(cmd) cmd = cmd.split('!') cmd.shift @arguments = cmd end def check_period get_timeperiod(@check_period) end # contacts # This is a list of the short names of the contacts that should be notified # whenever there are problems (or recoveries) with this host. # Multiple contacts should be separated by commas. # Useful if you want notifications to go to just a few people and don't want # to configure contact groups. # You must specify at least one contact or contact group in each host definition. def contacts_list @contacts.values.map(&:to_s).sort.join(',') end # contact_groups # This is a list of the short names of the contact groups that should be notified # whenever there are problems (or recoveries) with this host. # Multiple contact groups should be separated by commas. # You must specify at least one contact or contact group in each host definition. def contact_groups_list @contact_groups.values.map(&:to_s).sort.join(',') end def definition if blank?(hostgroup_name_list) && blank?(host_name_list) && name.nil? "# Skipping #{service_description} because host_name and hostgroup_name are missing." else configured = configured_options custom_options.each_value { |v| configured[v.to_s] = v.value } get_definition(configured, 'service') end end # host_name # This directive is used to return all host objects def host_name @hosts end # host_name_list # This directive is used to specify the short name(s) of the host(s) that the service # "runs" on or is associated with. Multiple hosts should be separated by commas. def host_name_list @hosts.values.map(&:to_s).sort.join(',') end # hostgroup_name # This directive is used to return all hostgroup objects def hostgroup_name @hostgroups end # hostgroup_name_list # This directive is used to specify the short name(s) of the hostgroup(s) that the # service "runs" on or is associated with. Multiple hostgroups should be separated by commas. # The hostgroup_name may be used instead of, or in addition to, the host_name directive. def hostgroup_name_list @hostgroups.values.map(&:to_s).sort.join(',') end def import(hash) update_options(hash) update_members(hash, 'contacts', Nagios::Contact) update_members(hash, 'contact_groups', Nagios::Contactgroup) update_members(hash, 'host_name', Nagios::Host) update_members(hash, 'hostgroup_name', Nagios::Hostgroup) update_members(hash, 'servicegroups', Nagios::Servicegroup, true) update_members(hash, 'check_command', Nagios::Command) end def notification_period get_timeperiod(@notification_period) end def push(obj) case obj when Nagios::Servicegroup push_object(obj, @servicegroups) when Nagios::Hostgroup push_object(obj, @hostgroups) when Nagios::Host push_object(obj, @hosts) when Nagios::Contact push_object(obj, @contacts) when Nagios::Contactgroup push_object(obj, @contact_groups) when Nagios::Command @check_command = obj when Nagios::Timeperiod @check_period = obj @notification_period = obj when Nagios::CustomOption push_object(obj, @custom_options) end end def pop(obj) return if obj == self case obj when Nagios::Servicegroup if @servicegroups.key?(obj.to_s) pop_object(obj, @servicegroups) pop(self, obj) end when Nagios::Hostgroup if @hostgroups.key?(obj.to_s) pop_object(obj, @hostgroups) pop(self, obj) end when Nagios::Host if @hosts.key?(obj.to_s) pop_object(obj, @hosts) pop(self, obj) end when Nagios::Contact if @contacts.key?(obj.to_s) pop_object(obj, @contacts) pop(self, obj) end when Nagios::Contactgroup if @contact_groups.key?(obj.to_s) pop_object(obj, @contact_groups) pop(self, obj) end when Nagios::Command @check_command = nil if @check_command == obj when Nagios::Timeperiod @check_period = nil if @check_command == obj @notification_period = nil if @check_command == obj when Nagios::CustomOption if @custom_options.key?(obj.to_s) pop_object(obj, @custom_options) pop(self, obj) end end end # servicegroups # This directive is used to define the description of the service, which may contain spaces, # dashes, and colons (semicolons, apostrophes, and quotation marks should be avoided). # No two services associated with the same host can have the same description. # Services are uniquely identified with their host_name and service_description directives. def servicegroups_list @servicegroups.values.map(&:to_s).sort.join(',') end def self.create(name) Nagios.instance.find(Nagios::Service.new(name)) end def to_s service_description end # check the integer options # default = nil def max_check_attempts=(int) @max_check_attempts = check_integer(int) end def check_interval=(int) @check_interval = check_integer(int) end def retry_interval=(int) @retry_interval = check_integer(int) end def freshness_threshold=(int) @freshness_threshold = check_integer(int) end def low_flap_threshold=(int) @low_flap_threshold = check_integer(int) end def high_flap_threshold=(int) @high_flap_threshold = check_integer(int) end def notification_interval=(int) @notification_interval = check_integer(int) end def first_notification_delay=(int) @first_notification_delay = check_integer(int) end # check the True/False options # default = nil def is_volatile=(arg) @is_volatile = check_bool(arg) end def active_checks_enabled=(arg) @active_checks_enabled = check_bool(arg) end def passive_checks_enabled=(arg) @passive_checks_enabled = check_bool(arg) end def obsess_over_service=(arg) @obsess_over_service = check_bool(arg) end def check_freshness=(arg) @check_freshness = check_bool(arg) end def event_handler_enabled=(arg) @event_handler_enabled = check_bool(arg) end def flap_detection_enabled=(arg) @flap_detection_enabled = check_bool(arg) end def process_perf_data=(arg) @process_perf_data = check_bool(arg) end def retain_status_information=(arg) @retain_status_information = check_bool(arg) end def retain_nonstatus_information=(arg) @retain_nonstatus_information = check_bool(arg) end def notifications_enabled=(arg) @notifications_enabled = check_bool(arg) end def parallelize_check=(arg) @parallelize_check = check_bool(arg) end # check other options # flap_detection_options # This directive is used to determine what service states the flap detection logic will use for this service. # Valid options are a combination of one or more of the following: # o = OK states, # w = WARNING states, # c = CRITICAL states, # u = UNKNOWN states. def flap_detection_options=(arg) @flap_detection_options = check_state_options(arg, %w(o w u c), 'flap_detection_options') end # notification_options # This directive is used to determine when notifications for the service should be sent out. # Valid options are a combination of one or more of the following: # w = send notifications on a WARNING state, # u = send notifications on an UNKNOWN state, # c = send notifications on a CRITICAL state, # r = send notifications on recoveries (OK state), # f = send notifications when the service starts and stops flapping, # s = send notifications when scheduled downtime starts and ends. # # If you specify n (none) as an option, no service notifications will be sent out. # If you do not specify any notification options, Nagios will assume that you want # notifications to be sent out for all possible states. # # Example: If you specify w,r in this field, notifications will only be sent out when # the service goes into a WARNING state and when it recovers from a WARNING state. def notification_options=(arg) @notification_options = check_state_options(arg, %w(w u c r f s n), 'notification_options') end # stalking_options # This directive determines which service states "stalking" is enabled for. # Valid options are a combination of one or more of the following: # o = stalk on OK states, # w = stalk on WARNING states, # u = stalk on UNKNOWN states, # c = stalk on CRITICAL states. # # More information on state stalking can be found here. def stalking_options=(arg) @stalking_options = check_state_options(arg, %w(o w u c), 'stalking_options') end private def config_options { 'name' => 'name', 'use' => 'use', 'service_description' => 'service_description', 'host_name_list' => 'host_name', 'hostgroup_name_list' => 'hostgroup_name', 'servicegroups_list' => 'servicegroups', 'display_name' => 'display_name', 'is_volatile' => 'is_volatile', 'check_command' => 'check_command', 'initial_state' => 'initial_state', 'max_check_attempts' => 'max_check_attempts', 'check_interval' => 'check_interval', 'retry_interval' => 'retry_interval', 'active_checks_enabled' => 'active_checks_enabled', 'passive_checks_enabled' => 'passive_checks_enabled', 'check_period' => 'check_period', 'obsess_over_service' => 'obsess_over_service', 'check_freshness' => 'check_freshness', 'freshness_threshold' => 'freshness_threshold', 'event_handler' => 'event_handler', 'event_handler_enabled' => 'event_handler_enabled', 'low_flap_threshold' => 'low_flap_threshold', 'high_flap_threshold' => 'high_flap_threshold', 'flap_detection_enabled' => 'flap_detection_enabled', 'flap_detection_options' => 'flap_detection_options', 'process_perf_data' => 'process_perf_data', 'retain_status_information' => 'retain_status_information', 'retain_nonstatus_information' => 'retain_nonstatus_information', 'notification_interval' => 'notification_interval', 'first_notification_delay' => 'first_notification_delay', 'notification_period' => 'notification_period', 'notification_options' => 'notification_options', 'notifications_enabled' => 'notifications_enabled', 'parallelize_check' => 'parallelize_check', 'contacts_list' => 'contacts', 'contact_groups_list' => 'contact_groups', 'stalking_options' => 'stalking_options', 'notes' => 'notes', 'notes_url' => 'notes_url', 'action_url' => 'action_url', 'icon_image' => 'icon_image', 'icon_image_alt' => 'icon_image_alt', 'register' => 'register', } end def merge_members(obj) obj.contacts.each { |m| push(m) } obj.host_name.each { |m| push(m) } obj.servicegroups.each { |m| push(m) } obj.hostgroup_name.each { |m| push(m) } obj.contact_groups.each { |m| push(m) } obj.custom_options.each_value { |m| push(m) } end end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/libraries/nagios.rb
libraries/nagios.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Library:: nagios # # Copyright:: 2014, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # This class holds all methods with regard to the nagios model. # class Nagios attr_reader :commands, :contactgroups, :contacts, :hostgroups, :hosts, :servicegroups, :services, :timeperiods, :hostdependencies, :hostescalations, :servicedependencies, :serviceescalations, :resources attr_accessor :host_name_attribute, :normalize_hostname, :default_command, :default_contactgroup, :default_contact, :default_hostgroup, :default_host, :default_servicegroup, :default_service, :default_timeperiod def initialize @commands = {} @contactgroups = {} @contacts = {} @hostgroups = {} @hosts = {} @servicegroups = {} @services = {} @timeperiods = {} @hostdependencies = {} @hostescalations = [] @servicedependencies = {} @serviceescalations = [] @resources = {} @host_name_attribute = 'hostname' @normalize_hostname = false end def commands Hash[@commands.sort] end def contactgroups Hash[@contactgroups.sort] end def contacts Hash[@contacts.sort] end def delete(hash, key) case hash when 'command' @commands.delete(key) when 'contactgroup' @contactgroups.delete(key) when 'contact' @contacts.delete(key) when 'hostgroup' @hostgroups.delete(key) when 'host' @hosts.delete(key) when 'servicegroup' @servicegroups.delete(key) when 'service' @services.delete(key) when 'timeperiod' @timeperiods.delete(key) when 'hostdependency' @hostdependencies.delete(key) when 'hostescalation' @hostescalations.delete(key) when 'servicedependency' @servicedependencies.delete(key) when 'serviceescalation' @serviceescalations.delete(key) when 'resource' @resources.delete(key) end end def find(obj) case obj when Nagios::Command find_object(obj, @commands) when Nagios::Contact find_object(obj, @contacts) when Nagios::Contactgroup find_object(obj, @contactgroups) when Nagios::Host find_object(obj, @hosts) when Nagios::Hostgroup find_object(obj, @hostgroups) when Nagios::Service find_object(obj, @services) when Nagios::Servicegroup find_object(obj, @servicegroups) when Nagios::Timeperiod find_object(obj, @timeperiods) when Nagios::Hostdependency find_object(obj, @hostdependencies) when Nagios::Servicedependency find_object(obj, @servicedependencies) when Nagios::Resource find_object(obj, @resources) end end def hosts Hash[@hosts.sort] end def hostdependencies Hash[@hostdependencies.sort] end def hostgroups Hash[@hostgroups.sort] end def normalize_hostname=(expr) @normalize_hostname = expr == true || !(expr =~ /y|yes|true|1/).nil? end def push(obj) case obj when Chef::Node push_node(obj) when Nagios::Command push_object(obj) when Nagios::Contact push_object(obj) when Nagios::Contactgroup push_object(obj) when Nagios::Host push_object(obj) when Nagios::Hostgroup push_object(obj) when Nagios::Service push_object(obj) when Nagios::Servicegroup push_object(obj) when Nagios::Timeperiod push_object(obj) when Nagios::Hostdependency push_object(obj) when Nagios::Hostescalation @hostescalations.push(obj) when Nagios::Servicedependency push_object(obj) when Nagios::Serviceescalation @serviceescalations.push(obj) when Nagios::Resource push_object(obj) else Chef::Log.fail("Nagios error: Pushing unknown object: #{obj.class} into Nagios.instance") raise end end def timeperiods Hash[@timeperiods.sort] end def resources Hash[@resources.sort] end def self.instance @instance ||= Nagios.new end def services Hash[@services.sort] end def servicedependencies Hash[@servicedependencies.sort] end def servicegroups Hash[@servicegroups.sort] end private def blank?(expr) return true if expr.nil? case expr when 'String', String return true if expr == '' when 'Array', 'Hash', Array, Hash return true if expr.empty? else return false end false end def find_object(obj, hash) current = hash[obj.to_s] if current.nil? Chef::Log.debug("Nagios debug: Creating entry for #{obj.class} with name: #{obj}") hash[obj.to_s] = obj obj else Chef::Log.debug("Nagios debug: Found entry for #{obj.class} with name: #{obj}") current end end def get_groups(obj) groups = obj['roles'].nil? ? [] : obj['roles'].dup groups += [obj['os']] unless blank?(obj['os']) groups + [obj.chef_environment] end def get_hostname(obj) return obj.name if @host_name_attribute == 'name' return obj['nagios']['host_name'] unless blank?(obj['nagios']) || blank?(obj['nagios']['host_name']) return obj[@host_name_attribute] unless blank?(obj[@host_name_attribute]) return obj['hostname'] unless blank?(obj['hostname']) return obj.name unless blank?(obj.name) nil end def push_node(obj) groups = get_groups(obj) hostname = get_hostname(obj) return if hostname.nil? host = find(Nagios::Host.new(hostname)) # TODO: merge the ip_to_monitor funtion into this logic here host.address = obj['ipaddress'] host.import(obj['nagios']) unless obj['nagios'].nil? groups.each do |r| hg = find(Nagios::Hostgroup.new(r)) hg.push(host) host.push(hg) end end def push_object(obj) object = find(obj.class.new(obj.to_s)) object.merge!(obj) end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/libraries/contact.rb
libraries/contact.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Library:: contact # # Copyright:: 2014, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative 'base' class Nagios # # This class holds all methods with regard to contact options, # that are used within nagios configurations. # class Contact < Nagios::Base attr_reader :contact_name, :contactgroups, :custom_options attr_accessor :alias, :host_notifications_enabled, :service_notifications_enabled, :host_notification_period, :service_notification_period, :host_notification_options, :service_notification_options, :host_notification_commands, :service_notification_commands, :email, :pager, :addressx, :can_submit_commands, :retain_status_information, :retain_nonstatus_information def initialize(contact_name) @contact_name = contact_name @contactgroups = {} @host_notification_commands = [] @service_notification_commands = [] @custom_options = {} super() end def contactgroups_list @contactgroups.values.map(&:to_s).sort.join(',') end def definition if email.nil? && name.nil? && pager.nil? "# Skipping #{contact_name} because missing email/pager." else configured = configured_options custom_options.each_value { |v| configured[v.to_s] = v.value } get_definition(configured, 'contact') end end def self.create(name) Nagios.instance.find(Nagios::Contact.new(name)) end def host_notification_commands get_commands(@host_notification_commands) end def host_notification_commands=(obj) @host_notification_commands = notification_commands(obj) end def host_notification_period get_timeperiod(@host_notification_period) end def import(hash) update_options(hash) update_members(hash, 'contactgroups', Nagios::Contactgroup, true) end def push(obj) case obj when Nagios::Contactgroup push_object(obj, @contactgroups) when Nagios::Timeperiod @host_notification_period = obj @service_notification_period = obj when Nagios::CustomOption push_object(obj, @custom_options) end end def pop(obj) return if obj == self case obj when Nagios::Contactgroup if @contactgroups.key?(obj.to_s) pop_object(obj, @contactgroups) pop(self, obj) end when Nagios::Timeperiod @host_notification_period = nil if obj == @host_notification_period @service_notification_period = nil if obj == @service_notification_period when Nagios::CustomOption if @custom_options.key?(obj.to_s) pop_object(obj, @custom_options) pop(self, obj) end end end def service_notification_commands get_commands(@service_notification_commands) end def service_notification_commands=(obj) @service_notification_commands = notification_commands(obj) end def service_notification_period get_timeperiod(@service_notification_period) end def to_s contact_name end # check the True/False options # default = nil def host_notifications_enabled=(arg) @host_notifications_enabled = check_bool(arg) end def service_notifications_enabled=(arg) @service_notifications_enabled = check_bool(arg) end def can_submit_commands=(arg) @can_submit_commands = check_bool(arg) end def retain_status_information=(arg) @retain_status_information = check_bool(arg) end def retain_nonstatus_information=(arg) @retain_nonstatus_information = check_bool(arg) end # check other options # # host_notification_options # This directive is used to define the host states for which notifications # can be sent out to this contact. # Valid options are a combination of one or more of the following: # d = notify on DOWN host states, # u = notify on UNREACHABLE host states, # r = notify on host recoveries (UP states), # f = notify when the host starts and stops flapping, # s = send notifications when host or service scheduled downtime starts and ends. # # If you specify n (none) as an option, the contact will not receive any type of # host notifications. def host_notification_options=(arg) @host_notification_options = check_state_options( arg, %w(d u r f s n), 'host_notification_options') end # service_notification_options # This directive is used to define the service states for which notifications # can be sent out to this contact. # Valid options are a combination of one or more of the following: # w = notify on WARNING service states, # u = notify on UNKNOWN service states, # c = notify on CRITICAL service states, # r = notify on service recoveries (OK states), # f = notify when the service starts and stops flapping. # # If you specify n (none) as an option, the contact will not receive any type of # service notifications. def service_notification_options=(arg) @service_notification_options = check_state_options( arg, %w(w u c r f n), 'service_notification_options') end private def config_options { 'name' => 'name', 'use' => 'use', 'contact_name' => 'contact_name', 'contactgroups_list' => 'contactgroups', 'alias' => 'alias', 'host_notifications_enabled' => 'host_notifications_enabled', 'service_notifications_enabled' => 'service_notifications_enabled', 'host_notification_period' => 'host_notification_period', 'service_notification_period' => 'service_notification_period', 'host_notification_options' => 'host_notification_options', 'service_notification_options' => 'service_notification_options', 'host_notification_commands' => 'host_notification_commands', 'service_notification_commands' => 'service_notification_commands', 'email' => 'email', 'pager' => 'pager', 'addressx' => 'addressx', 'can_submit_commands' => 'can_submit_commands', 'retain_status_information' => 'retain_status_information', 'retain_nonstatus_information' => 'retain_nonstatus_information', 'register' => 'register', } end def merge_members(obj) obj.contactgroups.each { |m| push(m) } obj.custom_options.each_value { |m| push(m) } end end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/libraries/custom_option.rb
libraries/custom_option.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Library:: custom_option # # Copyright:: 2015, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class Nagios # # This class holds all methods with regard to custom_options # class CustomOption attr_reader :value def initialize(option, value) @option = option @value = value end def to_s @option end end end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/resources/hostdependency.rb
resources/hostdependency.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Resource:: hostdependency # # Copyright:: 2015, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # property :options, [Hash, Chef::DataBagItem], default: {} unified_mode true action :create do o = Nagios::Hostdependency.create(new_resource.name) o.import(new_resource.options) end action :delete do Nagios.instance.delete('hostdependency', new_resource.name) end action_class do require_relative '../libraries/hostdependency' end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/resources/command.rb
resources/command.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: : nagios # Resource:: : command # # Copyright:: 2015, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # property :options, [Hash, Chef::DataBagItem], default: {} unified_mode true action :create do o = Nagios::Command.create(new_resource.name) o.import(new_resource.options) end action :delete do Nagios.instance.delete('command', new_resource.name) end action_class do require_relative '../libraries/command' end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/resources/resource.rb
resources/resource.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Resource:: resource # # Copyright:: 2015, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # property :options, [Hash, Chef::DataBagItem], default: {} unified_mode true action :create do o = Nagios::Resource.create(new_resource.name) o.import(new_resource.options) end action :delete do Nagios.instance.delete('resource', new_resource.name) end action_class do require_relative '../libraries/resource' end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/resources/servicedependency.rb
resources/servicedependency.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Resource:: servicedependency # # Copyright:: 2015, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # property :options, [Hash, Chef::DataBagItem], default: {} unified_mode true action :create do o = Nagios::Servicedependency.create(new_resource.name) o.import(new_resource.options) end action :delete do Nagios.instance.delete('servicedependency', new_resource.name) end action_class do require_relative '../libraries/servicedependency' end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/resources/contactgroup.rb
resources/contactgroup.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Resource:: contactgroup # # Copyright:: 2015, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # property :options, [Hash, Chef::DataBagItem], default: {} unified_mode true action :create do o = Nagios::Contactgroup.create(new_resource.name) o.import(new_resource.options) end action :delete do Nagios.instance.delete('contactgroup', new_resource.name) end action_class do require_relative '../libraries/contactgroup' end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/resources/host.rb
resources/host.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Resource:: host # # Copyright:: 2015, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # property :options, [Hash, Chef::DataBagItem], default: {} unified_mode true action :create do o = Nagios::Host.create(new_resource.name) o.import(new_resource.options) end action :delete do Nagios.instance.delete('host', new_resource.name) end action_class do require_relative '../libraries/host' end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/resources/hostescalation.rb
resources/hostescalation.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Resource:: hostescalation # # Copyright:: 2015, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # property :options, [Hash, Chef::DataBagItem], default: {} unified_mode true action :create do o = Nagios::Hostescalation.new(new_resource.name) o.import(new_resource.options) Nagios.instance.push(o) end action :delete do Nagios.instance.delete('hostescalation', new_resource.name) end action_class do require_relative '../libraries/hostescalation' end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/resources/servicegroup.rb
resources/servicegroup.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Resource:: servicegroup # # Copyright:: 2015, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # property :options, [Hash, Chef::DataBagItem], default: {} unified_mode true action :create do o = Nagios::Servicegroup.create(new_resource.name) o.import(new_resource.options) end action :delete do Nagios.instance.delete('servicegroup', new_resource.name) end action_class do require_relative '../libraries/servicegroup' end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/resources/serviceescalation.rb
resources/serviceescalation.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Resource:: serviceescalation # # Copyright:: 2015, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # property :options, [Hash, Chef::DataBagItem], default: {} unified_mode true action :create do o = Nagios::Serviceescalation.new(new_resource.name) o.import(new_resource.options) Nagios.instance.push(o) end action :delete do Nagios.instance.delete('serviceescalation', new_resource.name) end action_class do require_relative '../libraries/serviceescalation' end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/resources/timeperiod.rb
resources/timeperiod.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: : nagios # Resource:: : timeperiod # # Copyright:: 2015, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # property :options, [Hash, Chef::DataBagItem], default: {} unified_mode true action :create do o = Nagios::Timeperiod.create(new_resource.name) o.import(new_resource.options) end action :delete do Nagios.instance.delete('timeperiod', new_resource.name) end action_class do require_relative '../libraries/timeperiod' end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/resources/hostgroup.rb
resources/hostgroup.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Resource:: hostgroup # # Copyright:: 2015, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # property :options, [Hash, Chef::DataBagItem], default: {} unified_mode true action :create do o = Nagios::Hostgroup.create(new_resource.name) o.import(new_resource.options) end action :delete do Nagios.instance.delete('hostgroup', new_resource.name) end action_class do require_relative '../libraries/hostgroup' end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/resources/conf.rb
resources/conf.rb
# # Author:: Joshua Sierles <joshua@37signals.com> # Author:: Joshua Timberman <joshua@chef.io> # Author:: Nathan Haneysmith <nathan@chef.io> # Author:: Seth Chisamore <schisamo@chef.io> # Cookbook:: nagios # Resource:: nagios_conf # # Copyright:: 2009, 37signals # Copyright:: 2009-2016, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # property :variables, Hash, default: {} property :config_subdir, [true, false], default: true property :source, String property :cookbook, String, default: 'nagios' unified_mode true action :create do conf_dir = new_resource.config_subdir ? node['nagios']['config_dir'] : node['nagios']['conf_dir'] source ||= "#{new_resource.name}.cfg.erb" with_run_context(:root) do template "#{conf_dir}/#{new_resource.name}.cfg" do cookbook new_resource.cookbook if new_resource.cookbook owner 'nagios' group 'nagios' source source mode '0644' variables new_resource.variables notifies :restart, 'service[nagios]' backup 0 action :nothing delayed_action :create end end end action_class do require_relative '../libraries/nagios' end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/resources/service.rb
resources/service.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: nagios # Resource:: service # # Copyright:: 2015, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # property :options, [Hash, Chef::DataBagItem], default: {} unified_mode true action :create do o = Nagios::Service.create(new_resource.name) o.import(new_resource.options) end action :delete do Nagios.instance.delete('service', new_resource.name) end action_class do require_relative '../libraries/service' end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
sous-chefs/nagios
https://github.com/sous-chefs/nagios/blob/9f5601ca67c5e847078c20a2956556eab892a75d/resources/contact.rb
resources/contact.rb
# # Author:: Sander Botman <sbotman@schubergphilis.com> # Cookbook:: : nagios # Resource:: : contact # # Copyright:: 2015, Sander Botman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # property :options, [Hash, Chef::DataBagItem], default: {} unified_mode true action :create do o = Nagios::Contact.create(new_resource.name) o.import(new_resource.options) end action :delete do Nagios.instance.delete('contact', new_resource.name) end action_class do require_relative '../libraries/contact' end
ruby
Apache-2.0
9f5601ca67c5e847078c20a2956556eab892a75d
2026-01-04T17:54:34.235002Z
false
devalot/ror-example
https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/app/helpers/sessions_helper.rb
app/helpers/sessions_helper.rb
module SessionsHelper end
ruby
Unlicense
2acf777ef9939b6f53c0387f9b2620f76016ae0c
2026-01-04T17:54:41.674960Z
false
devalot/ror-example
https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/app/helpers/application_helper.rb
app/helpers/application_helper.rb
module ApplicationHelper end
ruby
Unlicense
2acf777ef9939b6f53c0387f9b2620f76016ae0c
2026-01-04T17:54:41.674960Z
false
devalot/ror-example
https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/app/helpers/cars_helper.rb
app/helpers/cars_helper.rb
module CarsHelper end
ruby
Unlicense
2acf777ef9939b6f53c0387f9b2620f76016ae0c
2026-01-04T17:54:41.674960Z
false
devalot/ror-example
https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/app/helpers/refuels_helper.rb
app/helpers/refuels_helper.rb
module RefuelsHelper end
ruby
Unlicense
2acf777ef9939b6f53c0387f9b2620f76016ae0c
2026-01-04T17:54:41.674960Z
false
devalot/ror-example
https://github.com/devalot/ror-example/blob/2acf777ef9939b6f53c0387f9b2620f76016ae0c/app/controllers/refuels_controller.rb
app/controllers/refuels_controller.rb
class RefuelsController < ApplicationController ############################################################################## # Establish a filter that will run before any of the actions in this # controller run. Its job will be to create a `@car` instance # variable that we can use to access refuel objects. The # `fetch_car` method can be found at the bottom of this file. before_filter(:fetch_car) ############################################################################## # See the note in cars_controller.rb respond_to(:html, :xml, :json) ############################################################################## def index @refuels = @car.refuels.order('refueled_at DESC') respond_with(@car, @refuels) # need @car because this is a nested resource end ############################################################################## def show @refuel = @car.refuels.find(params[:id]) respond_with(@car, @refuel) end ############################################################################## def new @refuel = @car.refuels.new respond_with(@car, @refuel) end ############################################################################## def create @refuel = @car.refuels.create(params[:refuel]) respond_with(@car, @refuel) end ############################################################################## def edit @refuel = @car.refuels.find(params[:id]) respond_with(@car, @refuel) end ############################################################################## def update @refuel = @car.refuels.find(params[:id]) @refuel.update_attributes(params[:refuel]) respond_with(@car, @refuel) end ############################################################################## def destroy @refuel = @car.refuels.find(params[:id]) @refuel.destroy respond_with(@car, @refuel) end ############################################################################## private ############################################################################## # Since this controller is a nested resource under the cars # resource, all invocations will include a `:car_id` parameter to # tell us which car we are working with. def fetch_car @car = current_user.cars.find(params[:car_id]) end end
ruby
Unlicense
2acf777ef9939b6f53c0387f9b2620f76016ae0c
2026-01-04T17:54:41.674960Z
false