#!/usr/bin/env ruby # frozen_string_literal: true lib = File.join(File.dirname(File.realpath(__FILE__)), '..'.freeze, 'lib'.freeze) $LOAD_PATH.unshift File.expand_path(lib) require 'netsoul/client' require 'optparse' require 'yaml' process_name_string = "#{__FILE__} #{ARGV.join(' '.freeze)}".freeze Process.respond_to?(:setproctitle) ? Process.setproctitle(process_name_string) : $PROGRAM_NAME = process_name_string options = {} OptionParser.new do |opts| opts.banner = 'Usage: netsoul-ruby [options]'.freeze opts.separator ''.freeze opts.separator 'Netsoul-Ruby options:'.freeze opts.on('-c'.freeze, '--config FILE'.freeze, 'Configuration file in YAML'.freeze) do |file| options[:user_opts] = YAML.load_file(file) if File.file?(file) end opts.on('-h'.freeze, '--help'.freeze, 'Display this screen'.freeze) do puts opts exit 42 end end.parse! if options.empty? || options[:user_opts].size == 0 unless ENV.to_a.count { |k, _v| %w(NETSOUL_LOGIN NETSOUL_SOCKS_PASSWORD NETSOUL_LOGIN NETSOUL_UNIX_PASSWORD NETSOUL_AUTH_METHOD).include?(k) } >= 2 puts '[ERROR] You have to specify a configuration file or environment variables'.freeze exit 42 end end def trap_interrupt(client) Signal.trap('INT'.freeze) do exit 42 unless client.started begin client.disconnect; end puts '!!! [SIGINT] !!!'.freeze exit 42 end end retry_count = 10 retry_wait_time = 1.0 RETRY_WAIT_FACTOR = 2.0 # Each time retry is called in Exception block, current 'retry_wait_time' is increased with this factor include Netsoul::Logging begin c = Netsoul::Client.new options[:user_opts] c.connect if c.started log :info, '[connection:ok] successfully connected to the Netsoul server' trap_interrupt c retry_count = 10 retry_wait_time = 1.0 loop do res = c.get res != 'nothing'.freeze ? log(:info, "[get ] #{res}") : log(:warn, '[get ] ()'.freeze) if res.to_s.match(/^ping.*/) c.send res log :info, "[send] #{res}" end end end rescue => e log :error, "[EXCEPTION!!]: #{e}" log :error, "[RETRY_COUNT]: #{retry_count}" begin c.disconnect; end if retry_count > 0 retry_count -= 1 retry_wait_time *= RETRY_WAIT_FACTOR sleep(retry_wait_time) retry end exit 42 end