nsqcd 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 1a0175d472d600b1770280abe897991420bd53b6
4
+ data.tar.gz: 296e8563548df2a8a2fc2b0952bbd829cdad3230
5
+ SHA512:
6
+ metadata.gz: 3e488184bdad4f77bf958c52b5d2747ba6744a3522fa034b0a4ce65308f108263e4b2d201ce4a7907827c701aadb44f7fb9684811463f562bdf2c7273244be5f
7
+ data.tar.gz: 279ed5ab4cabb65fd1b850b8b9a28aedc3b61689d02492b44ea05933d75218585db512b92294b63c78ee3dd6326975d8a0105527264902cbadaa78a135977e59
data/.gitignore ADDED
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
12
+ Gemfile.lock
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.6.3
7
+ before_install: gem install bundler -v 1.17.2
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at shmimy-w@163.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,8 @@
1
+ #source "https://rubygems.org"
2
+
3
+ source 'https://gems.ruby-china.com'
4
+
5
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
6
+
7
+ # Specify your gem's dependencies in nsqcd.gemspec
8
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 jetspeed
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,41 @@
1
+ # Nsqcd
2
+ A nsq consumer daemon ripped off from sneakers
3
+
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'nsqcd'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install nsqcd
20
+
21
+ ## Usage
22
+
23
+ TODO: Write usage instructions here
24
+
25
+ ## Development
26
+
27
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
28
+
29
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
30
+
31
+ ## Contributing
32
+
33
+ Bug reports and pull requests are welcome on GitHub at https://github.com/jetspeed/nsqcd. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
34
+
35
+ ## License
36
+
37
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
38
+
39
+ ## Code of Conduct
40
+
41
+ Everyone interacting in the Nsqcd project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/jetspeed/nsqcd/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "nsqcd"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/lib/nsqcd.rb ADDED
@@ -0,0 +1,93 @@
1
+ require 'nsqcd/version'
2
+ require 'logger'
3
+ require 'serverengine'
4
+
5
+ module Nsqcd
6
+ module Handlers
7
+ end
8
+ module Concerns
9
+ end
10
+ end
11
+
12
+ require 'nsqcd/configuration'
13
+ require 'nsqcd/errors'
14
+ require 'nsqcd/support/production_formatter'
15
+ require 'nsqcd/concerns/logging'
16
+ require 'nsqcd/worker'
17
+
18
+ module Nsqcd
19
+ extend self
20
+
21
+ CONFIG = Configuration.new
22
+
23
+ def configure(opts={})
24
+ # worker > userland > defaults
25
+ CONFIG.merge!(opts)
26
+ setup_general_logger!
27
+ setup_worker_concerns!
28
+ @configured = true
29
+ end
30
+
31
+ def clear!
32
+ CONFIG.clear
33
+ @logger = nil
34
+ @configured = false
35
+ end
36
+
37
+ def daemonize!(loglevel=Logger::INFO)
38
+ CONFIG[:log] = 'nsqcd.log'
39
+ CONFIG[:daemonize] = true
40
+ setup_general_logger!
41
+ logger.level = loglevel
42
+ end
43
+
44
+ def logger=(logger)
45
+ @logger = logger
46
+ end
47
+
48
+ def logger
49
+ @logger
50
+ end
51
+
52
+ def configured?
53
+ @configured
54
+ end
55
+
56
+ def server=(server)
57
+ @server = server
58
+ end
59
+
60
+ def server?
61
+ @server
62
+ end
63
+
64
+ def configure_server
65
+ yield self if server?
66
+ end
67
+
68
+ # Register a proc to handle any error which occurs within the Nsqcd process.
69
+ #
70
+ # Nsqcd.error_reporters << proc { |exception, worker, context_hash| MyErrorService.notify(exception, context_hash) }
71
+ #
72
+ # The default error handler logs errors to Nsqcd.logger.
73
+ # Ripped off from https://github.com/mperham/sidekiq/blob/6ad6a3aa330deebd76c6cf0d353f66abd3bef93b/lib/sidekiq.rb#L165-L174
74
+ def error_reporters
75
+ CONFIG[:error_reporters]
76
+ end
77
+
78
+ private
79
+
80
+ def setup_general_logger!
81
+ if [:info, :debug, :error, :warn].all?{ |meth| CONFIG[:log].respond_to?(meth) }
82
+ @logger = CONFIG[:log]
83
+ else
84
+ @logger = ServerEngine::DaemonLogger.new(CONFIG[:log])
85
+ @logger.formatter = Nsqcd::Support::ProductionFormatter
86
+ end
87
+ end
88
+
89
+ def setup_worker_concerns!
90
+ Worker.configure_logger(Nsqcd::logger)
91
+ end
92
+ end
93
+
@@ -0,0 +1,34 @@
1
+ module Nsqcd
2
+ module Concerns
3
+ module Logging
4
+ def self.included(base)
5
+ base.extend ClassMethods
6
+ base.send :define_method, :logger do
7
+ base.logger
8
+ end
9
+ end
10
+
11
+ module ClassMethods
12
+ def logger
13
+ @logger
14
+ end
15
+
16
+ def logger=(logger)
17
+ @logger = logger
18
+ end
19
+
20
+ def configure_logger(log=nil)
21
+ if log
22
+ @logger = log
23
+ else
24
+ @logger = Logger.new(STDOUT)
25
+ @logger.level = Logger::INFO
26
+ @logger.formatter = Nsqcd::Support::ProductionFormatter
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
32
+ end
33
+
34
+
@@ -0,0 +1,34 @@
1
+ require 'nsqcd/metrics/null_metrics'
2
+
3
+ module Nsqcd
4
+ module Concerns
5
+ module Metrics
6
+ def self.included(base)
7
+ base.extend ClassMethods
8
+ base.send :define_method, :metrics do
9
+ base.metrics
10
+ end
11
+ end
12
+
13
+ module ClassMethods
14
+ def metrics
15
+ @metrics
16
+ end
17
+
18
+ def metrics=(metrics)
19
+ @metrics = metrics
20
+ end
21
+
22
+ def configure_metrics(metrics=nil)
23
+ if metrics
24
+ @metrics = metrics
25
+ else
26
+ @metrics = Nsqcd::Metrics::NullMetrics.new
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
32
+ end
33
+
34
+
@@ -0,0 +1,70 @@
1
+ require 'nsqcd/error_reporter'
2
+ require 'forwardable'
3
+
4
+ module Nsqcd
5
+ class Configuration
6
+
7
+ extend Forwardable
8
+ def_delegators :@hash, :to_hash, :[], :[]=, :==, :fetch, :delete, :has_key?
9
+
10
+ QUEUE_OPTION_DEFAULTS = {
11
+ topic: 'the-topic',
12
+ channel: 'my-channel',
13
+ nsqlookupd: ['127.0.0.1:4161', '4.5.6.7:4161'],
14
+ max_in_flight: 100,
15
+ discovery_interval: 30,
16
+ msg_timeout: 120_000,
17
+ max_attempts: 10
18
+ }.freeze
19
+
20
+ DEFAULTS = {
21
+ # Set up default handler which just logs the error.
22
+ # Remove this in production if you don't want sensitive data logged.
23
+ :error_reporters => [Nsqcd::ErrorReporter::DefaultLogger.new],
24
+
25
+ # runner
26
+ :runner_config_file => nil,
27
+ :metrics => nil,
28
+ :daemonize => false,
29
+ :start_worker_delay => 0.2,
30
+ :workers => 2,
31
+ :heartbeat => 300,
32
+ :log => STDOUT,
33
+ :pid_path => 'nsqcd.pid',
34
+
35
+ # workers
36
+ :prefetch => 10,
37
+ :threads => 10,
38
+ :share_threads => true,
39
+ :ack => true,
40
+ :hooks => {},
41
+ :queue_options => QUEUE_OPTION_DEFAULTS
42
+ }.freeze
43
+
44
+
45
+ def initialize
46
+ clear
47
+ end
48
+
49
+ def clear
50
+ @hash = DEFAULTS.dup
51
+ end
52
+
53
+ def merge!(hash)
54
+ hash = hash.dup
55
+ @hash = deep_merge(@hash, hash)
56
+ end
57
+
58
+ def merge(hash)
59
+ instance = self.class.new
60
+ instance.merge! to_hash
61
+ instance.merge! hash
62
+ instance
63
+ end
64
+
65
+ def deep_merge(first, second)
66
+ merger = proc { |_, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 }
67
+ first.merge(second, &merger)
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,26 @@
1
+ module Nsqcd
2
+ module ErrorReporter
3
+ class DefaultLogger
4
+ def call(exception, worker, context_hash)
5
+ Nsqcd.logger.warn(context_hash) unless context_hash.empty?
6
+ log_string = ''
7
+ log_string += "[Exception error=#{exception.message.inspect} error_class=#{exception.class} worker_class=#{worker.class}" unless exception.nil?
8
+ log_string += " backtrace=#{exception.backtrace.take(50).join(',')}" unless exception.nil? || exception.backtrace.nil?
9
+ log_string += ']'
10
+ Nsqcd.logger.error log_string
11
+ end
12
+ end
13
+
14
+ def worker_error(exception, context_hash = {})
15
+ Nsqcd.error_reporters.each do |handler|
16
+ begin
17
+ handler.call(exception, self, context_hash)
18
+ rescue => inner_exception
19
+ Nsqcd.logger.error '!!! ERROR REPORTER THREW AN ERROR !!!'
20
+ Nsqcd.logger.error inner_exception
21
+ Nsqcd.logger.error inner_exception.backtrace.join("\n") unless inner_exception.backtrace.nil?
22
+ end
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,2 @@
1
+ module Nsqcd
2
+ end
@@ -0,0 +1,14 @@
1
+ class Nsqcd::Queue
2
+ attr_reader :name, :opts, :topic
3
+
4
+ def initialize(name, opts)
5
+ @name = name
6
+ @opts = opts
7
+ @handler_klass = Nsqcd::CONFIG[:handler]
8
+ end
9
+
10
+ def publish(topic, msg)
11
+ producer = Nsq::Producer.new(@opts[:nsqlookupd], topic)
12
+ producer.write(msg)
13
+ end
14
+ end
@@ -0,0 +1,91 @@
1
+ require 'serverengine'
2
+ require 'nsqcd/workergroup'
3
+
4
+ module Nsqcd
5
+ class Runner
6
+ def initialize(worker_classes, opts={})
7
+ @runnerconfig = RunnerConfig.new(worker_classes, opts)
8
+ end
9
+
10
+ def run
11
+ @se = ServerEngine.create(nil, WorkerGroup) { @runnerconfig.reload_config! }
12
+ @se.run
13
+ end
14
+
15
+ def stop
16
+ @se.stop
17
+ end
18
+ end
19
+
20
+
21
+ class RunnerConfig
22
+ def method_missing(meth, *args, &block)
23
+ if %w{ before_fork after_fork }.include? meth.to_s
24
+ @conf[meth] = block
25
+ elsif %w{ workers start_worker_delay amqp }.include? meth.to_s
26
+ @conf[meth] = args.first
27
+ else
28
+ super
29
+ end
30
+ end
31
+
32
+ def initialize(worker_classes, opts)
33
+ @worker_classes = worker_classes
34
+ @conf = opts
35
+ end
36
+
37
+ def to_h
38
+ @conf
39
+ end
40
+
41
+
42
+ def reload_config!
43
+ Nsqcd.logger.info("Loading runner configuration...")
44
+ config_file = Nsqcd::CONFIG[:runner_config_file]
45
+
46
+ if config_file
47
+ begin
48
+ instance_eval(File.read(config_file), config_file)
49
+ Nsqcd.logger.info("Loading config with file: #{config_file}")
50
+ rescue
51
+ Nsqcd.logger.error("Cannot load from file '#{config_file}', #{$!}")
52
+ end
53
+ end
54
+
55
+ config = make_serverengine_config
56
+
57
+ [:before_fork, :after_fork].each do | hook |
58
+ Nsqcd::CONFIG[:hooks][hook] = config.delete(hook) if config[hook]
59
+ end
60
+
61
+ Nsqcd.logger.debug("New configuration: #{config.inspect}")
62
+ config
63
+ end
64
+
65
+ private
66
+
67
+ def make_serverengine_config
68
+ # From Nsqcd#setup_general_logger, there's support for a Logger object
69
+ # in CONFIG[:log]. However, serverengine takes an object in :logger.
70
+ # Pass our logger object so there's no issue about sometimes passing a
71
+ # file and sometimes an object.
72
+ serverengine_config = Nsqcd::CONFIG.merge(@conf)
73
+ serverengine_config.merge!(
74
+ :logger => Nsqcd.logger,
75
+ :log_level => Nsqcd.logger.level,
76
+ :worker_type => 'process',
77
+ :worker_classes => @worker_classes,
78
+
79
+ # Turning off serverengine internal logging infra, causes
80
+ # livelock and hang.
81
+ # see https://github.com/jondot/nsqcd/issues/153
82
+ :log_stdout => false,
83
+ :log_stderr => false
84
+ )
85
+ serverengine_config.delete(:log)
86
+
87
+ serverengine_config
88
+ end
89
+ end
90
+
91
+ end
@@ -0,0 +1,11 @@
1
+ require 'time'
2
+ module Nsqcd
3
+ module Support
4
+ class ProductionFormatter < Logger::Formatter
5
+ def self.call(severity, time, program_name, message)
6
+ "#{time.utc.iso8601} p-#{Process.pid} t-#{Thread.current.object_id.to_s(36)} #{severity}: #{message}\n"
7
+ end
8
+ end
9
+ end
10
+ end
11
+
@@ -0,0 +1,18 @@
1
+ class Nsqcd::Utils
2
+ def self.make_worker_id(namespace)
3
+ "worker-#{namespace}:#{'1'}:#{rand(36**6).floor.to_s(36)}" # jid, worker id. include date.
4
+ end
5
+ def self.parse_workers(workerstring)
6
+ missing_workers = []
7
+ workers = (workerstring || '').split(',').map do |k|
8
+ begin
9
+ w = Kernel.const_get(k)
10
+ rescue
11
+ missing_workers << k
12
+ end
13
+ w
14
+ end.compact
15
+
16
+ [workers, missing_workers]
17
+ end
18
+ end
@@ -0,0 +1,45 @@
1
+ require 'nsqcd'
2
+ require 'nsqcd/runner'
3
+
4
+ task :environment
5
+
6
+ namespace :nsqcd do
7
+ desc "Start work (set $WORKERS=Klass1,Klass2)"
8
+ task :run do
9
+ Nsqcd.server = true
10
+ Rake::Task['environment'].invoke
11
+
12
+ if defined?(::Rails)
13
+ ::Rails.application.eager_load!
14
+ end
15
+
16
+ if ENV["WORKERS"].nil?
17
+ workers = Nsqcd::Worker::Classes
18
+ else
19
+ workers, missing_workers = Nsqcd::Utils.parse_workers(ENV['WORKERS'])
20
+ end
21
+
22
+ unless missing_workers.nil? || missing_workers.empty?
23
+ puts "Missing workers: #{missing_workers.join(', ')}" if missing_workers
24
+ puts "Did you `require` properly?"
25
+ exit(1)
26
+ end
27
+
28
+ if workers.empty?
29
+ puts <<EOF
30
+ Error: No workers found.
31
+ Please set the classes of the workers you want to run like so:
32
+
33
+ $ export WORKERS=MyWorker,FooWorker
34
+ $ rake nsqcd:run
35
+
36
+ EOF
37
+ exit(1)
38
+ end
39
+ opts = (!ENV['WORKER_COUNT'].nil? ? {:workers => ENV['WORKER_COUNT'].to_i} : {})
40
+ puts workers.inspect
41
+ r = Nsqcd::Runner.new(workers, opts)
42
+
43
+ r.run
44
+ end
45
+ end
@@ -0,0 +1,3 @@
1
+ module Nsqcd
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,99 @@
1
+ require 'nsqcd/support/utils'
2
+ require 'nsq'
3
+
4
+ module Nsqcd
5
+ module Worker
6
+ attr_reader :topic, :channel, :id, :opts
7
+
8
+ include Concerns::Logging
9
+ include Nsqcd::ErrorReporter
10
+
11
+ def initialize(pool = nil, opts = {})
12
+ worker_opts = opts.merge(self.class.opts || {})
13
+ worker_opts = Nsqcd::CONFIG.merge(worker_opts)
14
+
15
+ @pool = pool || Concurrent::FixedThreadPool.new(worker_opts[:threads] || Nsqcd::Configuration::DEFAULTS[:threads])
16
+ @call_with_params = respond_to?(:work_with_params)
17
+
18
+ @opts = worker_opts
19
+ puts '=================='
20
+ puts "#{self.class.name} #{@opts.inspect}"
21
+ puts '=================='
22
+
23
+ @id = Utils.make_worker_id(self.class.name)
24
+ end
25
+
26
+ def reject!; :reject; end
27
+ def requeue!; :requeue; end
28
+
29
+ def run
30
+ worker_trace "New worker: #{self.class} running."
31
+ consumer = Nsq::Consumer.new(@opts)
32
+ @pool.post do
33
+ loop do
34
+ msg = consumer.pop
35
+
36
+ worker_trace "Working off: #{msg.data.inspect} #{msg.body}"
37
+ process_work(msg)
38
+ msg.finish
39
+ end
40
+ end
41
+ end
42
+
43
+ def publish(msg, opts)
44
+ topic = opts.delete(:topic)
45
+ producer = Nsq::Producer.new(opts[:nsqlookupd], topic)
46
+ producer.write(msg)
47
+ end
48
+
49
+ def process_work(msg)
50
+ begin
51
+ work(msg)
52
+ rescue StandardError, ScriptError => ex
53
+ worker_error(ex, log_msg: log_msg(msg), class: self.class.name, message: msg)
54
+ end
55
+ end
56
+
57
+ def stop
58
+ worker_trace "Stopping worker: shutting down thread pool."
59
+ @pool.shutdown
60
+ @pool.wait_for_termination
61
+ worker_trace "Stopping worker: I'm gone."
62
+ end
63
+ # Construct a log message with some standard prefix for this worker
64
+ #
65
+ def log_msg(msg)
66
+ "[#{@id}][#{Thread.current}][#{self.class.name}] #{msg}"
67
+ end
68
+
69
+ def worker_trace(msg)
70
+ logger.debug(log_msg(msg))
71
+ end
72
+
73
+ Classes = []
74
+
75
+ def self.included(base)
76
+ base.extend ClassMethods
77
+ Classes << base if base.is_a? Class
78
+ end
79
+
80
+ module ClassMethods
81
+ attr_reader :topic, :channel, :opts
82
+
83
+ def from(o ={})
84
+ @opts = o
85
+ end
86
+
87
+ def enqueue(msg, o={})
88
+ @opts[:to_queue] ||= @topic
89
+ publisher.publish(msg, o)
90
+ end
91
+
92
+ private
93
+
94
+ def publisher
95
+ @publisher ||= Nsqcd::Publisher.new(queue_opts)
96
+ end
97
+ end
98
+ end
99
+ end
@@ -0,0 +1,60 @@
1
+ module Nsqcd
2
+ module WorkerGroup
3
+ @workers = []
4
+
5
+ def initialize
6
+ @stop_flag = ServerEngine::BlockingFlag.new
7
+ end
8
+
9
+ def before_fork
10
+ fbefore = Nsqcd::CONFIG[:hooks][:before_fork]
11
+ fbefore.call if fbefore
12
+ end
13
+
14
+ def after_fork # note! this is not Serverengine#after_start, this is ours!
15
+ fafter = Nsqcd::CONFIG[:hooks][:after_fork]
16
+ fafter.call if fafter
17
+ end
18
+
19
+ def run
20
+ after_fork
21
+
22
+ # Allocate single thread pool if share_threads is set. This improves load balancing
23
+ # when used with many workers.
24
+ pool = config[:share_threads] ? Concurrent::FixedThreadPool.new(config[:threads]) : nil
25
+
26
+ worker_classes = config[:worker_classes]
27
+
28
+ if worker_classes.respond_to? :call
29
+ worker_classes = worker_classes.call
30
+ end
31
+
32
+ # If we don't provide a connection to a worker,
33
+ # the queue used in the worker will create a new one
34
+
35
+ @workers = worker_classes.map do |worker_class|
36
+ worker_class.new( pool, { connection: config[:connection] })
37
+ end
38
+
39
+ # if more than one worker this should be per worker
40
+ # accumulate clients and consumers as well
41
+ @workers.each do |worker|
42
+ worker.run
43
+ end
44
+ # end per worker
45
+ #
46
+ until @stop_flag.wait_for_set(Nsqcd::CONFIG[:heartbeat])
47
+ Nsqcd.logger.debug("Heartbeat: running threads [#{Thread.list.count}]")
48
+ # report aggregated stats?
49
+ end
50
+ end
51
+
52
+ def stop
53
+ Nsqcd.logger.info("Shutting down workers")
54
+ @workers.each do |worker|
55
+ worker.stop
56
+ end
57
+ @stop_flag.set!
58
+ end
59
+ end
60
+ end
data/nsqcd.gemspec ADDED
@@ -0,0 +1,46 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "nsqcd/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "nsqcd"
8
+ spec.version = Nsqcd::VERSION
9
+ spec.authors = ["jetspeed"]
10
+ spec.email = ["shmimy-w@163.com"]
11
+
12
+ spec.summary = %q{nsq consumer daemon}
13
+ spec.description = %q{nsq consumer daemon, using serverengin and nsq_ruby.}
14
+ spec.homepage = "https://rubygems.org/gems/nsqcd"
15
+ srcpage = "https://github.com/jetspeed/nsqcd"
16
+ spec.license = "MIT"
17
+
18
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
19
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
20
+ if spec.respond_to?(:metadata)
21
+ spec.metadata["allowed_push_host"] = spec.homepage
22
+ spec.metadata["homepage_uri"] = srcpage
23
+ spec.metadata["source_code_uri"] = srcpage
24
+ spec.metadata["changelog_uri"] = srcpage
25
+ else
26
+ raise "RubyGems 2.0 or newer is required to protect against " \
27
+ "public gem pushes."
28
+ end
29
+
30
+ # Specify which files should be added to the gem when it is released.
31
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
32
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
33
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
34
+ end
35
+ spec.bindir = "exe"
36
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
37
+ spec.require_paths = ["lib"]
38
+
39
+ spec.add_dependency 'serverengine', '~> 2.1.0'
40
+ spec.add_dependency 'nsq-ruby', '~> 2.3.1'
41
+
42
+
43
+ spec.add_development_dependency "bundler", "~> 1.17"
44
+ spec.add_development_dependency "rake", "~> 10.0"
45
+ spec.add_development_dependency "rspec", "~> 3.0"
46
+ end
metadata ADDED
@@ -0,0 +1,143 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: nsqcd
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - jetspeed
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2019-09-30 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: serverengine
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 2.1.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 2.1.0
27
+ - !ruby/object:Gem::Dependency
28
+ name: nsq-ruby
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: 2.3.1
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: 2.3.1
41
+ - !ruby/object:Gem::Dependency
42
+ name: bundler
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.17'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1.17'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '10.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '10.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rspec
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.0'
83
+ description: nsq consumer daemon, using serverengin and nsq_ruby.
84
+ email:
85
+ - shmimy-w@163.com
86
+ executables: []
87
+ extensions: []
88
+ extra_rdoc_files: []
89
+ files:
90
+ - ".gitignore"
91
+ - ".rspec"
92
+ - ".travis.yml"
93
+ - CODE_OF_CONDUCT.md
94
+ - Gemfile
95
+ - LICENSE.txt
96
+ - README.md
97
+ - Rakefile
98
+ - bin/console
99
+ - bin/setup
100
+ - lib/nsqcd.rb
101
+ - lib/nsqcd/concerns/logging.rb
102
+ - lib/nsqcd/concerns/metrics.rb
103
+ - lib/nsqcd/configuration.rb
104
+ - lib/nsqcd/error_reporter.rb
105
+ - lib/nsqcd/errors.rb
106
+ - lib/nsqcd/queue.rb
107
+ - lib/nsqcd/runner.rb
108
+ - lib/nsqcd/support/production_formatter.rb
109
+ - lib/nsqcd/support/utils.rb
110
+ - lib/nsqcd/tasks.rb
111
+ - lib/nsqcd/version.rb
112
+ - lib/nsqcd/worker.rb
113
+ - lib/nsqcd/workergroup.rb
114
+ - nsqcd.gemspec
115
+ homepage: https://rubygems.org/gems/nsqcd
116
+ licenses:
117
+ - MIT
118
+ metadata:
119
+ allowed_push_host: https://rubygems.org/gems/nsqcd
120
+ homepage_uri: https://github.com/jetspeed/nsqcd
121
+ source_code_uri: https://github.com/jetspeed/nsqcd
122
+ changelog_uri: https://github.com/jetspeed/nsqcd
123
+ post_install_message:
124
+ rdoc_options: []
125
+ require_paths:
126
+ - lib
127
+ required_ruby_version: !ruby/object:Gem::Requirement
128
+ requirements:
129
+ - - ">="
130
+ - !ruby/object:Gem::Version
131
+ version: '0'
132
+ required_rubygems_version: !ruby/object:Gem::Requirement
133
+ requirements:
134
+ - - ">="
135
+ - !ruby/object:Gem::Version
136
+ version: '0'
137
+ requirements: []
138
+ rubyforge_project:
139
+ rubygems_version: 2.6.14
140
+ signing_key:
141
+ specification_version: 4
142
+ summary: nsq consumer daemon
143
+ test_files: []