require 'json' require 'etcdv3' module RubyPitaya class EtcdConnector def initialize(server_uuid, desktop_name, server_name, etcd_prefix, etcd_address, allow_reconnect, lease_seconds, log) @server_uuid = server_uuid @server_name = server_name @desktop_name = desktop_name @etcd_prefix = etcd_prefix @etcd_address = etcd_address @allow_reconnect = allow_reconnect @lease_seconds = lease_seconds @log = log @renew_connection_seconds = lease_seconds / 2.0 @renew_connection_key = nil @renew_connection_value = nil @renew_connection_thread = nil end def connect connection_key = get_connection_key connection_value = get_connection_value @connection = Etcdv3.new(endpoints: @etcd_address, allow_reconnect: @allow_reconnect) @lease = @connection.lease_grant(@lease_seconds) @connection.put(connection_key, connection_value, lease: @lease.ID) @renew_connection_key = connection_key @renew_connection_value = connection_value renew_connection end def disconnect stop_renew_connection @connection.del(get_connection_key) end private def get_connection_key "#{@etcd_prefix}servers/#{@server_name}/#{@server_uuid}" end def get_connection_value JSON.generate(get_server_data) end def renew_connection stop_renew_connection @renew_connection_thread = Thread.new do loop do sleep(@renew_connection_seconds) begin @lease = @connection.lease_keep_alive_once(@lease.ID) if @lease.TTL == 0 @lease = @connection.lease_grant(@lease_seconds) @connection.put(@renew_connection_key, @renew_connection_value, lease: @lease.ID) end rescue Exception => error @log.error "ETCD RENEW ERROR: #{error.class} | #{error.message}} \n #{error.backtrace.join("\n")}" end end end end def stop_renew_connection @renew_connection_thread.exit.join unless @renew_connection_thread.nil? @renew_connection_thread = nil end def get_server_data { id: @server_uuid, hostname: @desktop_name, type: @server_name, frontend: false, metadata: { stack: 'default', stackInfo: JSON.generate({ Maintenance: false, Platforms: { android: { Max: '9.9.9', Min: '0.0.0' }, ios: { Max: '9.9.9', Min: '0.0.0' }, iphoneplayer: { Max: '9.9.9', Min: '0.0.0' }, mac: { Max: '9.9.9', Min: '0.0.0' }, osxeditor: { Max: '9.9.9', Min: '0.0.0' } } }) } } end end end