Class: Zold::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/zold/commands/node.rb

Overview

NODE command

Defined Under Namespace

Classes: NohupLog, WebrickLog

Instance Method Summary collapse

Constructor Details

#initialize(wallets:, remotes:, copies:, log: Log::Quiet.new) ⇒ Node

Returns a new instance of Node.



55
56
57
58
59
60
# File 'lib/zold/commands/node.rb', line 55

def initialize(wallets:, remotes:, copies:, log: Log::Quiet.new)
  @remotes = remotes
  @copies = copies
  @log = log
  @wallets = wallets
end

Instance Method Details

#run(args = []) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/zold/commands/node.rb', line 62

def run(args = [])
  opts = Slop.parse(args, help: true, suppress_errors: true) do |o|
    o.banner = 'Usage: zold node [options]'
    o.string '--invoice',
      'The invoice you want to collect money to or the wallet ID',
      required: true
    o.integer '--port',
      "TCP port to open for the Net (default: #{Remotes::PORT})",
      default: Remotes::PORT
    o.integer '--bind-port',
      "TCP port to listen on (default: #{Remotes::PORT})",
      default: Remotes::PORT
    o.string '--host',
      'Host name (will attempt to auto-detect it, if not specified)'
    o.integer '--strength',
      "The strength of the score (default: #{Score::STRENGTH})",
      default: Score::STRENGTH
    o.integer '--threads',
      'How many threads to use for scores finding (default: 2)',
      default: 2
    o.bool '--dump-errors',
      'Make HTTP front-end errors visible in the log (false by default)',
      default: false
    o.bool '--standalone',
      'Never communicate with other nodes (mostly for testing)',
      default: false
    o.bool '--ignore-score-weakness',
      'Ignore score weakness of incoming requests and register those nodes anyway',
      default: false
    o.boolean '--nohup',
      'Run it in background, rebooting when a higher version is available in the network',
      default: false
    o.string '--nohup-command',
      'The command to run in server "nohup" mode (default: "gem install zold")',
      default: 'gem install zold'
    o.string '--nohup-log',
      'The file to log output into (default: zold.log)',
      default: 'zold.log'
    o.integer '--nohup-log-truncate',
      'The maximum amount of bytes to keep in the file, and truncate it in half if it grows bigger',
      default: 1024 * 1024
    o.string '--halt-code',
      'The value of HTTP query parameter "halt," which will cause the front-end immediate termination',
      default: ''
    o.integer '--trace-length',
      'Maximum length of the trace to keep in memory (default: 4096)',
      default: 4096
    o.string '--save-pid',
      'The file to save process ID into right after start (only in NOHUP mode)'
    o.bool '--never-reboot',
      'Don\'t reboot when a new version shows up in the network',
      default: false
    o.bool '--routine-immediately',
      'Run all routines immediately, without waiting between executions (for testing mostly)',
      default: false
    o.string '--expose-version',
      "The version of the software to expose in JSON (default: #{VERSION})",
      default: VERSION
    o.string '--private-key',
      'The location of RSA private key (default: ~/.ssh/id_rsa)',
      default: '~/.ssh/id_rsa'
    o.string '--network',
      "The name of the network (default: #{Wallet::MAIN_NETWORK})",
      require: true,
      default: Wallet::MAIN_NETWORK
    o.integer '--nohup-max-cycles',
      'Maximum amount of nohup re-starts (-1 by default, which means forever)',
      require: true,
      default: -1
    o.string '--home',
      "Home directory (default: #{Dir.pwd})",
      default: Dir.pwd
    o.bool '--no-metronome',
      'Don\'t run the metronome',
      required: true,
      default: false
    o.bool '--disable-push',
      'Prohibit all PUSH requests',
      default: false
    o.bool '--disable-fetch',
      'Prohibit all FETCH requests',
      default: false
    o.string '--alias',
      'The alias of the node (default: host:port)',
      require: false
    o.bool '--help', 'Print instructions'
  end
  if opts.help?
    @log.info(opts.to_s)
    return
  end
  raise '--invoice is mandatory' unless opts['invoice']
  if opts['nohup']
    pid = nohup(opts)
    IO.write(opts['save-pid'], pid) if opts['save-pid']
    @log.debug("Process ID #{pid} saved into \"#{opts['save-pid']}\"")
    @log.info(pid)
    return
  end
  @log = Trace.new(@log, opts['trace-length'])
  Front.set(:log, @log)
  Front.set(:logger, @log)
  Front.set(:trace, @log)
  Front.set(:nohup_log, opts['nohup-log']) if opts['nohup-log']
  Front.set(:version, opts['expose-version'])
  Front.set(:protocol, Zold::PROTOCOL)
  Front.set(:logging, @log.debug?)
  Front.set(:halt, opts['halt-code'])
  Front.set(:disable_push, opts['disable-push'])
  Front.set(:disable_fetch, opts['disable-fetch'])
  home = File.expand_path(opts['home'])
  Front.set(:home, home)
  @log.info("Time: #{Time.now.utc.iso8601}")
  @log.info("Home directory: #{home}")
  @log.info("Ruby version: #{RUBY_VERSION}")
  @log.info("Zold gem version: #{Zold::VERSION}")
  @log.info("Zold protocol version: #{Zold::PROTOCOL}")
  @log.info("Network ID: #{opts['network']}")
  host = opts[:host] || ip
  port = opts[:port]
  address = "#{host}:#{port}".downcase
  @log.info("Node location: #{address}")
  @log.info("Local address: http://localhost:#{opts['bind-port']}/")
  @log.info("Remote nodes (#{@remotes.all.count}): \
#{@remotes.all.map { |r| "#{r[:host]}:#{r[:port]}" }.join(', ')}")
  @log.info("Wallets at: #{@wallets.path}")
  Front.set(
    :server_settings,
    Logger: WebrickLog.new(@log),
    AccessLog: []
  )
  if opts['standalone']
    @remotes = Zold::Remotes::Empty.new
    @log.info('Running in standalone mode! (will never talk to other remotes)')
  elsif @remotes.exists?(host, port)
    Zold::Remote.new(remotes: @remotes).run(['remote', 'remove', host, port.to_s])
    @log.info("Removed current node (#{address}) from list of remotes")
  end
  Front.set(:ignore_score_weakness, opts['ignore-score-weakness'])
  Front.set(:network, opts['network'])
  Front.set(:wallets, @wallets)
  Front.set(:remotes, @remotes)
  Front.set(:copies, @copies)
  Front.set(:address, address)
  Front.set(:root, home)
  Front.set(:dump_errors, opts['dump-errors'])
  Front.set(:port, opts['bind-port'])
  Front.set(:reboot, !opts['never-reboot'])
  node_alias = opts[:alias] || address
  unless node_alias.eql?(address) || node_alias =~ /^[A-Za-z0-9]{4,16}$/
    raise "Alias should be a 4 to 16 char long alphanumeric string: #{node_alias}"
  end
  Front.set(:node_alias, node_alias)
  invoice = opts[:invoice]
  unless invoice.include?('@')
    require_relative 'invoice'
    invoice = Invoice.new(
      wallets: @wallets, remotes: @remotes, copies: @copies, log: @log
    ).run(['invoice', invoice, "--network=#{opts['network']}"])
  end
  SafeEntrance.new(
    NoDupEntrance.new(
      AsyncEntrance.new(
        SpreadEntrance.new(
          SyncEntrance.new(
            Entrance.new(
              @wallets,
              @remotes, @copies, address,
              log: @log, network: opts['network']
            ),
            File.join(home, '.zoldata/sync-entrance'),
            log: @log
          ),
          @wallets, @remotes, address,
          log: @log,
          ignore_score_weakeness: opts['ignore-score-weakness']
        ),
        File.join(home, '.zoldata/async-entrance'), log: @log
      ),
      @wallets
    ),
    network: opts['network']
  ).start do |entrance|
    Front.set(:entrance, entrance)
    Farm.new(invoice, File.join(home, 'farm'), log: @log)
      .start(host, opts[:port], threads: opts[:threads], strength: opts[:strength]) do |farm|
      Front.set(:farm, farm)
      metronome(farm, opts).start do |metronome|
        Front.set(:metronome, metronome)
        @log.info("Starting up the web front at http://#{host}:#{opts[:port]}...")
        Front.run!
        @log.info("The web front stopped at http://#{host}:#{opts[:port]}")
        @log.info('Thanks for helping Zold network!')
      end
    end
  end
end