port-authority-prz 0.5.4

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: a097763b4216a171c756f1fa93c8d1f9bcf2d2a9
4
+ data.tar.gz: 32ba35072e6168e7e0d59625b7c19cbc157a6eb8
5
+ SHA512:
6
+ metadata.gz: f7de62fe39132a46cf906f89038111ceb3956d10e7783f79b9265a125df00ff9422fd85aa932251ba983e4999e7e249bc432a5b12d2859b341837f2fa1a25a22
7
+ data.tar.gz: 1c3c05227f3efc65fa3f3c5d8cf06b9a91d0f341f83c11b1a8640b93071790b3ebdf0197d4f4bd8fdeb3f719812863fce290451d965cf6f0b4c9061ff7bfb179
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env ruby
2
+ require 'port-authority/agents/lbaas'
3
+ PortAuthority::Agents::LBaaS.new
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env ruby
2
+ require 'port-authority/tools/service_list'
3
+ PortAuthority::Tools::ServiceList.new
@@ -0,0 +1,154 @@
1
+ require 'timeout'
2
+ require 'json'
3
+ require 'yaml'
4
+ require 'port-authority'
5
+ require 'port-authority/config'
6
+ require 'port-authority/logger'
7
+ require 'port-authority/etcd'
8
+
9
+ module PortAuthority
10
+ # Scaffolding class for agents
11
+ class Agent
12
+ # Common agent process init. Contains configuration load,
13
+ # common signal responses and runtime variables init.
14
+ # Implements execution of actual agents via \+run+ method.
15
+ # Also handles any uncaught exceptions.
16
+ def initialize
17
+ Thread.current[:name] = 'main' # name main thread
18
+ @@_exit = false # prepare exit flag
19
+ @@_semaphores = { log: Mutex.new } # init semaphores
20
+ @@_threads = {} # init threads
21
+ Signal.trap('INT') { exit!(1) } # end immediatelly
22
+ Signal.trap('TERM') { end! } # end gracefully
23
+ Config.load! || exit!(1) # load config or die
24
+ begin # all-wrapping exception ;)
25
+ run # hook to child class
26
+ rescue StandardError => e
27
+ Logger.alert "UNCAUGHT EXCEPTION IN THREAD main! Dying! X.X"
28
+ Logger.alert [' ', "#{e.class}:", e.message].join(' ')
29
+ e.backtrace.each {|line| Logger.debug " #{line}"}
30
+ exit! 1
31
+ end
32
+ end
33
+
34
+ # Setup the agent process.
35
+ # Initializes logging, system process parameters,
36
+ # daemonizing.
37
+ #
38
+ # There are 4 optional parameters:
39
+ # +:name+:: \+String+ Agent name. Defaults to \+self.class.downcase+ of the child agent
40
+ # +:root+:: \+Bool+ Require to be ran as root. Defaults to \+false+.
41
+ # +:daemonize+:: \+Bool+ Daemonize the process. Defaults to \+false+.
42
+ # +:nice+:: \+Int+ nice of the process. Defaults to \+0+
43
+ def setup(args = {})
44
+ name = args[:name] || self.class.to_s.downcase.split('::').last
45
+ args[:root] ||= false
46
+ args[:daemonize] ||= false
47
+ args[:nice] ||= 0
48
+ Logger.init! @@_semaphores[:log], name
49
+ Logger.info 'Starting main thread'
50
+ Logger.debug 'Setting process name'
51
+ if RUBY_VERSION >= '2.1'
52
+ Process.setproctitle("pa-#{name}-agent")
53
+ else
54
+ $0 = "pa-#{name}-agent"
55
+ end
56
+ if args[:root] && Process.uid != 0
57
+ Logger.alert 'Must run under root user!'
58
+ exit! 1
59
+ end
60
+ Logger.debug 'Setting CPU nice level'
61
+ Process.setpriority(Process::PRIO_PROCESS, 0, args[:nice])
62
+ if args[:daemonize]
63
+ Logger.info 'Daemonizing process'
64
+ if RUBY_VERSION < '1.9'
65
+ exit if fork
66
+ Process.setsid
67
+ exit if fork
68
+ Dir.chdir('/')
69
+ else
70
+ Process.daemon
71
+ end
72
+ end
73
+ end
74
+
75
+ # Has the exit flag been raised?
76
+ def exit?
77
+ @@_exit
78
+ end
79
+
80
+ # Raise the exit flag
81
+ def end!
82
+ @@_exit = true
83
+ end
84
+
85
+ # Create a named \+Mutex+ semaphore
86
+ def sem_create(name)
87
+ @@_semaphores.merge!(Hash[name.to_sym], Mutex.new)
88
+ end
89
+
90
+ # Create a named \+Thread+ with its \+Mutex+ semaphore.
91
+ # The definition includes \+&block+ of code that should run
92
+ # within the thread.
93
+ #
94
+ # The method requires 3 parameters:
95
+ # +name+:: \+Symbol+ Thread/Mutex name.
96
+ # +interval+:: \+Integer+ Thread loop interval.
97
+ # +&block+:: \+Proc+ Block of code to run.
98
+ def thr_create(name, interval, &block)
99
+ @@_semaphores.merge!(Hash[name.to_sym, Mutex.new])
100
+ @@_threads.merge!(Hash[name.to_sym, Thread.new do
101
+ Thread.current[:name] = name.to_s
102
+ Logger.info "Starting thread #{Thread.current[:name]}"
103
+ begin
104
+ until exit?
105
+ yield block
106
+ sleep interval
107
+ end
108
+ Logger.info "Ending thread #{Thread.current[:name]}"
109
+ rescue StandardError => e
110
+ Logger.alert "UNCAUGHT EXCEPTION IN THREAD #{Thread.current[:name]}"
111
+ Logger.alert [' ', "#{e.class}:", e.message].join(' ')
112
+ e.backtrace.each {|line| Logger.debug " #{line}"}
113
+ end!
114
+ end
115
+ end
116
+ ])
117
+ end
118
+
119
+ # Run thread-safe code.
120
+ # The \+name+ parameter can be omitted when used
121
+ # from within a block of thread code. In this case
122
+ # the Mutex with the same \+:name+ will be used.
123
+ #
124
+ # The method accepts following parameters:
125
+ # +name+:: \+Symbol+ Mutex name.
126
+ # +&block+:: \+Proc+ Block of code to run.
127
+ def thr_safe(name=Thread.current[:name].to_sym, &block)
128
+ @@_semaphores[name.to_sym].synchronize do
129
+ yield block
130
+ end
131
+ end
132
+
133
+ # Start named thread.
134
+ # If the name is omitted, applies to all spawned threads ;)
135
+ def thr_start(name=nil)
136
+ return @@_threads[name].run if name
137
+ @@_threads.each_value(&:run)
138
+ end
139
+
140
+
141
+ # Wait for named thread to finish.
142
+ # If the name is omitted, applies to all spawned threads ;)
143
+ def thr_wait(name=nil)
144
+ return @@_threads[name].join if name
145
+ @@_threads.each_value(&:join)
146
+ end
147
+
148
+ # Return hostname.
149
+ def hostname
150
+ @hostname ||= Socket.gethostname
151
+ end
152
+
153
+ end
154
+ end
@@ -0,0 +1,133 @@
1
+ # rubocop:disable MethodLength, CyclomaticComplexity, Metrics/BlockNesting, Metrics/LineLength, Metrics/AbcSize, Metrics/PerceivedComplexity
2
+ require 'socket'
3
+ require 'port-authority/agent'
4
+ require 'port-authority/mechanism/load_balancer'
5
+ require 'port-authority/mechanism/floating_ip'
6
+
7
+ module PortAuthority
8
+ module Agents
9
+ class LBaaS < PortAuthority::Agent
10
+ include PortAuthority::Mechanism
11
+
12
+ def run
13
+ setup(daemonize: Config.daemonize, nice: -10, root: true)
14
+ Signal.trap('HUP') { Config.load! && LoadBalancer.init! && FloatingIP.init! }
15
+ Signal.trap('USR1') { Logger.debug! }
16
+ Signal.trap('USR2') { @lb_update_hook = true }
17
+ @status_swarm = false
18
+ @etcd = PortAuthority::Etcd.cluster_connect Config.etcd
19
+
20
+ thr_create(:swarm, Config.lbaas[:swarm_interval] || Config.lbaas[:interval]) do
21
+ begin
22
+ Logger.debug 'Checking Swarm state'
23
+ status = @etcd.am_i_swarm_leader?
24
+ thr_safe { @status_swarm = status }
25
+ Logger.debug "I am Swarm #{status ? 'leader' : 'follower' }"
26
+ rescue StandardError => e
27
+ Logger.error [ e.class, e.message ].join(': ')
28
+ e.backtrace.each {|line| Logger.debug " #{line}"}
29
+ thr_safe { @status_swarm = false }
30
+ sleep(Config.lbaas[:swarm_interval] || Config.lbaas[:interval])
31
+ retry unless exit?
32
+ end
33
+ end
34
+
35
+ thr_start
36
+
37
+ FloatingIP.init!
38
+ LoadBalancer.init!
39
+
40
+ Logger.debug 'Waiting for threads to gather something...'
41
+ sleep Config.lbaas[:interval]
42
+ first_cycle = true
43
+ status_time = Time.now.to_i - 60
44
+
45
+ until exit?
46
+ status_swarm = false if first_cycle
47
+ if @lb_update_hook
48
+ Logger.notice 'LoadBalancer update triggerred'
49
+ LoadBalancer.update!
50
+ @lb_update_hook = false
51
+ Logger.notice 'LoadBalancer update finished'
52
+ end
53
+ sleep Config.lbaas[:interval]
54
+ thr_safe(:swarm) { status_swarm = @status_swarm }
55
+ # main logic
56
+ if status_swarm
57
+ # handle FloatingIP on leader
58
+ Logger.debug 'I am the LEADER'
59
+ if FloatingIP.up?
60
+ Logger.debug 'Got FloatingIP, that is OK'
61
+ else
62
+ Logger.notice 'No FloatingIP here, checking whether it is free'
63
+ FloatingIP.arp_del!
64
+ if FloatingIP.reachable?
65
+ Logger.notice 'FloatingIP is still up! (ICMP)'
66
+ else
67
+ Logger.info 'FloatingIP is unreachable by ICMP, checking for duplicates on L2'
68
+ FloatingIP.arp_del!
69
+ if FloatingIP.duplicate?
70
+ Logger.error 'FloatingIP is still assigned! (ARP)'
71
+ else
72
+ Logger.notice 'FloatingIP is free :) assigning'
73
+ FloatingIP.handle! status_swarm
74
+ Logger.notice 'Notifying the network about change'
75
+ FloatingIP.arp_update!
76
+ end
77
+ end
78
+ end
79
+ # handle LoadBalancer on leader
80
+ if LoadBalancer.up?
81
+ Logger.debug 'LoadBalancer is up, that is OK'
82
+ else
83
+ Logger.notice 'LoadBalancer is down, starting'
84
+ LoadBalancer.start!
85
+ end
86
+ else
87
+ # handle FloatingIP on follower
88
+ Logger.debug 'I am a follower'
89
+ if FloatingIP.up?
90
+ Logger.notice 'I got FloatingIP and should not, removing'
91
+ FloatingIP.handle! status_swarm
92
+ FloatingIP.arp_del!
93
+ Logger.notice 'Notifying the network about change'
94
+ FloatingIP.update_arp!
95
+ else
96
+ Logger.debug 'No FloatingIP here, that is OK'
97
+ end
98
+ # handle LoadBalancer on follower
99
+ if LoadBalancer.up?
100
+ Logger.notice 'LoadBalancer is up, stopping'
101
+ LoadBalancer.stop!
102
+ else
103
+ Logger.debug 'LoadBalancer is down, that is OK'
104
+ end
105
+ end # logic end
106
+ end
107
+
108
+ thr_wait
109
+
110
+ # remove FloatingIP on shutdown
111
+ if FloatingIP.up?
112
+ Logger.notice 'Removing FloatingIP'
113
+ FloatingIP.handle! false
114
+ FloatingIP.update_arp!
115
+ end
116
+
117
+ # stop LB on shutdown
118
+ if LoadBalancer.up?
119
+ Logger.notice 'Stopping LoadBalancer'
120
+ LoadBalancer.stop!
121
+ end
122
+
123
+ Logger.notice 'Exiting...'
124
+ exit 0
125
+ end
126
+
127
+ def my_ip
128
+ @my_ip ||= Socket.ip_address_list.detect(&:ipv4_private?).ip_address
129
+ end
130
+
131
+ end
132
+ end
133
+ end
@@ -0,0 +1,49 @@
1
+ require 'etcd-tools/mixins/hash'
2
+
3
+ module PortAuthority
4
+ module Config
5
+
6
+ extend self
7
+
8
+ attr_reader :_cfg
9
+
10
+ def method_missing(name, *_args, &_block)
11
+ return @_cfg[name.to_sym] if @_cfg[name.to_sym] != nil
12
+ fail(NoMethodError, "unknown configuration section #{name}", caller)
13
+ end
14
+
15
+ def load!
16
+ @_cfg = {
17
+ debug: false,
18
+ syslog: false,
19
+ daemonize: false,
20
+ etcd: {
21
+ endpoints: ['http://localhost:2379'],
22
+ timeout: 5
23
+ },
24
+ commands: {
25
+ arping: `which arping`.chomp,
26
+ arp: `which arp`.chomp,
27
+ iproute: `which ip`.chomp
28
+ }
29
+ }
30
+ files = ['/etc/port-authority.yaml', './etc/port-authority.yaml'].delete_if {|f| !File.exists?(f)}
31
+ dir_files = Dir['/etc/port-authority.d/**.yaml'] + Dir['./etc/port-authority.d/**.yaml']
32
+ files += dir_files
33
+ return false if files.empty?
34
+ files.each do |f|
35
+ @_cfg = @_cfg.deep_merge(YAML.load_file(f))
36
+ end
37
+ true
38
+ end
39
+
40
+ def dump
41
+ self._cfg
42
+ end
43
+
44
+ def to_yaml
45
+ self._cfg.to_yaml.to_s
46
+ end
47
+
48
+ end
49
+ end
@@ -0,0 +1,47 @@
1
+ require 'etcd-tools'
2
+ require 'etcd-tools/mixins'
3
+
4
+ module PortAuthority
5
+ class Etcd < Etcd::Client
6
+
7
+ def self.cluster_connect(config)
8
+ endpoints = config[:endpoints].map {|ep| Hash[[:host, :port].zip(ep.match(/^(?:https?:\/\/)?([0-9a-zA-Z\.-_]+):([0-9]+)\/?/).captures)]}
9
+ timeout = config[:timeout].to_i
10
+ PortAuthority::Etcd.new(cluster: endpoints, read_timeout: timeout)
11
+ end
12
+
13
+ def self.shell_cluster_connect(env, timeout = 2)
14
+ env.split(',').each do |u|
15
+ (host, port) = u.gsub(/^https?:\/\//, '').gsub(/\/$/, '').split(':')
16
+ etcd = PortAuthority::Etcd.new(cluster: [{ host: host, port: port }], read_timeout: timeout)
17
+ return etcd if etcd.healthy?
18
+ next
19
+ end
20
+ raise Etcd::ClusterConnectError
21
+ end
22
+
23
+
24
+ def swarm_leader
25
+ get('/_pa/docker/swarm/leader').value.split(':').first
26
+ end
27
+
28
+ def am_i_swarm_leader?
29
+ Socket.ip_address_list.map(&:ip_address).member?(swarm_leader)
30
+ end
31
+
32
+ def swarm_overlay_id(name)
33
+ get_hash('/_pa/docker/network/v1.0/network').each_value do |network|
34
+ return network['id'] if network['name'] == name
35
+ end
36
+ end
37
+
38
+ def swarm_list_services(network, service_name='.*')
39
+ services = {}
40
+ self.get_hash("/_pa/docker/network/v1.0/endpoint/#{swarm_overlay_id(network)}").each_value do |container|
41
+ next unless Regexp.new(service_name).match container['name']
42
+ services = { container['name'] => { 'id' => container['id'], 'ip' => container['ep_iface']['addr'].sub(/\/[0-9]+$/, ''), 'ports' => container['exposed_ports'].map { |port| port['Port'] } } }
43
+ end
44
+ services
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,56 @@
1
+ # rubocop:disable Metrics/LineLength, Metrics/AbcSize, Metrics/MethodLength
2
+ require 'syslog'
3
+
4
+ module PortAuthority
5
+ module Logger
6
+
7
+ extend self
8
+
9
+ def init!(s,n)
10
+ @_s = s
11
+ @debug = Config.debug
12
+ Syslog.open("pa-#{n}-agent", Syslog::LOG_PID, Syslog::LOG_DAEMON) if Config.syslog
13
+ end
14
+
15
+ def debug!
16
+ @debug = !@debug
17
+ end
18
+
19
+ def debug(message)
20
+ log :debug, message if @debug
21
+ end
22
+
23
+ def method_missing(name, *args, &_block)
24
+ if name
25
+ return log(name.to_sym, args[0])
26
+ else
27
+ fail(NoMethodError, "Unknown Logger method '#{name}'", caller)
28
+ end
29
+ end
30
+
31
+ def log(lvl, msg)
32
+ if Config.syslog
33
+ case lvl
34
+ when :debug
35
+ l = Syslog::LOG_DEBUG
36
+ when :info
37
+ l = Syslog::LOG_INFO
38
+ when :notice
39
+ l = Syslog::LOG_NOTICE
40
+ when :error
41
+ l = Syslog::LOG_ERR
42
+ when :alert
43
+ l = Syslog::LOG_ALERT
44
+ end
45
+ @_s.synchronize do
46
+ Syslog.log(l, "(%s) %s", Thread.current[:name], msg.to_s)
47
+ end
48
+ else
49
+ @_s.synchronize do
50
+ $stdout.puts [Time.now.to_s, sprintf('%-6.6s', lvl.to_s.upcase), "(#{Thread.current[:name]})", msg.to_s].join(' ')
51
+ $stdout.flush
52
+ end
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,65 @@
1
+ # rubocop:disable Metrics/LineLength, Metrics/AbcSize
2
+ require 'net/ping'
3
+ require 'digest/sha2'
4
+
5
+ module PortAuthority
6
+ module Mechanism
7
+ module FloatingIP
8
+
9
+ extend self
10
+
11
+ attr_accessor :_icmp
12
+
13
+ def init!
14
+ @_icmp = Net::Ping::ICMP.new(Config.lbaas[:floating_ip])
15
+ Logger.debug(Config.lbaas.to_yaml)
16
+ end
17
+
18
+ # add or remove VIP on interface
19
+ def handle!(leader)
20
+ return true if shellcmd Config.commands[:iproute], 'address', leader ? 'add' : 'delete', "#{Config.lbaas[:floating_ip]}/32", 'dev', Config.lbaas[:floating_iface], '>/dev/null 2>&1'
21
+ false
22
+ end
23
+
24
+ # send gratuitous ARP to the network
25
+ def arp_update!
26
+ return true if shellcmd Config.commands[:arping], '-U', '-q', '-c', Config.lbaas[:arping_count], '-I', Config.lbaas[:floating_iface], Config.lbaas[:floating_ip]
27
+
28
+ false
29
+ end
30
+
31
+ # check whether VIP is assigned to me
32
+ def up?
33
+ Socket.ip_address_list.map(&:ip_address).member?(Config.lbaas[:floating_ip])
34
+ end
35
+
36
+ # check reachability of VIP by ICMP echo
37
+ def reachable?
38
+ (1..Config.lbaas[:icmp_count]).each { return true if @_icmp.ping }
39
+ false
40
+ end
41
+
42
+ def arp_del!
43
+ return true if shellcmd Config.commands[:arp], '-d', Config.lbaas[:floating_ip], '>/dev/null 2>&1'
44
+ false
45
+ end
46
+
47
+ # check whether the IP is registered anywhere
48
+ def duplicate?
49
+ return false if shellcmd Config.commands[:arping], '-D', '-q', '-c', Config.lbaas[:arping_count], '-w', Config.lbaas[:arping_wait], '-I', Config.lbaas[:floating_iface], Config.lbaas[:floating_ip]
50
+ true
51
+ end
52
+
53
+ private
54
+ def shellcmd(*args)
55
+ cmd = args.join(' ').to_s
56
+ cksum = Digest::SHA256.hexdigest(args.join.to_s)[0..15]
57
+ Logger.debug "Executing shellcommand #{cksum} - #{cmd}"
58
+ ret = system cmd
59
+ Logger.debug "Shellcommand #{cksum} returned #{ret.to_s}"
60
+ return ret
61
+ end
62
+
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,90 @@
1
+ require 'docker-api'
2
+
3
+ module PortAuthority
4
+ module Mechanism
5
+ module LoadBalancer
6
+
7
+ extend self
8
+
9
+ attr_reader :_container, :_container_def, :_image
10
+
11
+ def init!
12
+ Docker.url = Config.lbaas[:docker_endpoint]
13
+ Docker.options = { connect_timeout: Config.lbaas[:docker_timeout] || 10 }
14
+ self.container || ( self.pull! && self.create! )
15
+ end
16
+
17
+ def container
18
+ @_container ||= Docker::Container.get(Config.lbaas[:name]) rescue nil
19
+ end
20
+
21
+ def image
22
+ @_image ||= Docker::Image.create('fromImage' => Config.lbaas[:image])
23
+ end
24
+
25
+ def pull!
26
+ @_image = Docker::Image.create('fromImage' => Config.lbaas[:image])
27
+ end
28
+
29
+ def create!
30
+ port_bindings = Hash.new
31
+ self.image.json['ContainerConfig']['ExposedPorts'].keys.each do |port|
32
+ port_bindings[port] = [ { 'HostPort' => "#{port.split('/').first}" } ]
33
+ end
34
+ @_container_def = {
35
+ 'Image' => self.image.json['Id'],
36
+ 'name' => Config.lbaas[:name],
37
+ 'Hostname' => Config.lbaas[:name],
38
+ 'Env' => [ "ETCDCTL_ENDPOINT=#{Config.etcd[:endpoints].join(',')},#{Config.lbaas[:env]}" ],
39
+ 'RestartPolicy' => { 'Name' => 'never' },
40
+ 'HostConfig' => {
41
+ 'PortBindings' => port_bindings,
42
+ 'NetworkMode' => Config.lbaas[:network]
43
+ }
44
+ }
45
+ if Config.lbaas[:log_dest] != ''
46
+ @_container_def['HostConfig']['LogConfig'] = {
47
+ 'Type' => 'gelf',
48
+ 'Config' => {
49
+ 'gelf-address' => Config.lbaas[:log_dest],
50
+ 'tag' => Socket.gethostbyname(Socket.gethostname).first + '/{{.Name}}/{{.ID}}'
51
+ }
52
+ }
53
+ end
54
+ @_container = Docker::Container.create(@_container_def)
55
+ end
56
+
57
+
58
+ def update!
59
+ begin
60
+ ( self.stop! && start = true ) if self.up?
61
+ self.remove!
62
+ self.pull!
63
+ self.create!
64
+ self.start! if start == true
65
+ rescue StandardError => e
66
+ Logger.error "UNCAUGHT EXCEPTION IN THREAD #{Thread.current[:name]}"
67
+ Logger.error [' ', e.class, e.message].join(' ')
68
+ Logger.error ' ' + e.backtrace.to_s
69
+ end
70
+ end
71
+
72
+ def remove!
73
+ @_container.delete
74
+ end
75
+
76
+ def up?
77
+ @_container.json['State']['Running']
78
+ end
79
+
80
+ def start!
81
+ @_container.start
82
+ end
83
+
84
+ def stop!
85
+ @_container.stop
86
+ end
87
+
88
+ end
89
+ end
90
+ end
@@ -0,0 +1,9 @@
1
+ module PortAuthority
2
+ class Tool
3
+ def initialize
4
+ self.optparse
5
+ @ARGS = ARGV
6
+ self.run
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,93 @@
1
+ require 'optparse'
2
+ require 'json'
3
+ require 'yaml'
4
+ require 'etcd-tools'
5
+ # require 'etcd-tools/mixins'
6
+ require 'port-authority/etcd'
7
+ require 'port-authority/tool'
8
+
9
+ module PortAuthority
10
+ module Tools
11
+ class ServiceList < PortAuthority::Tool
12
+
13
+ attr_reader :etcd
14
+
15
+ def optparse
16
+ @options = Hash.new
17
+ @options[:url] = ENV['ETCDCTL_ENDPOINT']
18
+ @options[:url] ||= "http://127.0.0.1:2379"
19
+ @options[:output_yaml] = false
20
+ @options[:output_json] = false
21
+ @options[:ip_only] = false
22
+ @options[:ports] = false
23
+ @options[:service_filter] = '.*'
24
+
25
+ OptionParser.new do |opts|
26
+ opts.banner = "Lists\n\nUsage: #{$0} [OPTIONS] NETWORK_NAME"
27
+ opts.separator ""
28
+ opts.separator "Connection options:"
29
+ opts.on("-u", "--url URL", "URL endpoint of the ETCD service (ETCDCTL_ENDPOINT envvar also applies) [DEFAULT: http://127.0.0.1:2379]") do |param|
30
+ @options[:url] = param
31
+ end
32
+
33
+ opts.separator ""
34
+ opts.separator "Filter options:"
35
+ opts.on("-s SERVICE_NAME", "--service-filter SERVICE_NAME", String, "List only services by name") do |param|
36
+ @options[:service_filter] = param
37
+ end
38
+
39
+ opts.separator ""
40
+ opts.separator "Output options:"
41
+ opts.on("-i", "--ips", "List only IPs (text mode)") do
42
+ @options[:ip_only] = true
43
+ end
44
+ opts.on("-p", "--ports", "List exposed ports (text mode)") do
45
+ @options[:ports] = true
46
+ end
47
+ opts.on("-y", "--yaml", "Output the data as YAML") do
48
+ @options[:output_yaml] = true
49
+ end
50
+ opts.on("-j", "--json", "Output the data as JSON") do
51
+ @options[:output_json] = true
52
+ end
53
+
54
+ opts.separator ""
55
+ opts.separator "Common options:"
56
+ opts.on_tail("-h", "--help", "show usage") do |param|
57
+ puts opts
58
+ exit! 0
59
+ end
60
+ end.parse!
61
+ end
62
+
63
+ def run
64
+ unless @ARGS[0]
65
+ $stderr.puts 'Missing NETWORK_NAME!'
66
+ exit 1
67
+ end
68
+
69
+ @etcd = PortAuthority::Etcd.shell_cluster_connect(@options[:url])
70
+
71
+ services = @etcd.swarm_list_services(@ARGS[0], @options[:service_filter])
72
+
73
+ if @options[:output_yaml]
74
+ puts services.to_yaml
75
+ elsif @options[:output_json]
76
+ puts services.to_json
77
+ else
78
+ if @options[:ip_only]
79
+ services.each { |_, params| puts params['ip'] }
80
+ elsif @options[:ports]
81
+ services.each do |name, params|
82
+ params['ports'].each do |port|
83
+ puts "#{name} #{params['ip']}:#{port}"
84
+ end
85
+ end
86
+ else
87
+ services.each { |name, params| puts "#{name} #{params['ip']}" }
88
+ end
89
+ end
90
+ end
91
+ end
92
+ end
93
+ end
@@ -0,0 +1,23 @@
1
+ module PortAuthority
2
+
3
+ module Errors
4
+
5
+ class ETCDConnectFailed < StandardError
6
+ attr_reader :etcd, :message
7
+ def initialize(etcd, message = "Can't connect to ETCD")
8
+ @message = message
9
+ @etcd = etcd
10
+ end
11
+ end
12
+
13
+ class ETCDIsSick < StandardError
14
+ attr_reader :etcd, :message
15
+ def initialize(etcd, message = 'ETCD is not healthy')
16
+ @message = message
17
+ @etcd = etcd
18
+ end
19
+ end
20
+
21
+ end
22
+
23
+ end
metadata ADDED
@@ -0,0 +1,139 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: port-authority-prz
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.5.4
5
+ platform: ruby
6
+ authors:
7
+ - Radek 'blufor' Slavicinsky
8
+ - Tomas 'arteal' Hejatko
9
+ - Jan 'liquid' Kaufman
10
+ autorequire:
11
+ bindir: bin
12
+ cert_chain: []
13
+ date: 2016-06-02 00:00:00.000000000 Z
14
+ dependencies:
15
+ - !ruby/object:Gem::Dependency
16
+ name: etcd
17
+ requirement: !ruby/object:Gem::Requirement
18
+ requirements:
19
+ - - "~>"
20
+ - !ruby/object:Gem::Version
21
+ version: '0.3'
22
+ - - ">="
23
+ - !ruby/object:Gem::Version
24
+ version: 0.3.0
25
+ type: :runtime
26
+ prerelease: false
27
+ version_requirements: !ruby/object:Gem::Requirement
28
+ requirements:
29
+ - - "~>"
30
+ - !ruby/object:Gem::Version
31
+ version: '0.3'
32
+ - - ">="
33
+ - !ruby/object:Gem::Version
34
+ version: 0.3.0
35
+ - !ruby/object:Gem::Dependency
36
+ name: etcd-tools
37
+ requirement: !ruby/object:Gem::Requirement
38
+ requirements:
39
+ - - "~>"
40
+ - !ruby/object:Gem::Version
41
+ version: '0.4'
42
+ - - ">="
43
+ - !ruby/object:Gem::Version
44
+ version: 0.4.4
45
+ type: :runtime
46
+ prerelease: false
47
+ version_requirements: !ruby/object:Gem::Requirement
48
+ requirements:
49
+ - - "~>"
50
+ - !ruby/object:Gem::Version
51
+ version: '0.4'
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: 0.4.4
55
+ - !ruby/object:Gem::Dependency
56
+ name: net-ping
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '1.7'
62
+ - - ">="
63
+ - !ruby/object:Gem::Version
64
+ version: 1.7.8
65
+ type: :runtime
66
+ prerelease: false
67
+ version_requirements: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - "~>"
70
+ - !ruby/object:Gem::Version
71
+ version: '1.7'
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ version: 1.7.8
75
+ - !ruby/object:Gem::Dependency
76
+ name: docker-api
77
+ requirement: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - "~>"
80
+ - !ruby/object:Gem::Version
81
+ version: '1.0'
82
+ - - ">="
83
+ - !ruby/object:Gem::Version
84
+ version: 1.25.0
85
+ type: :runtime
86
+ prerelease: false
87
+ version_requirements: !ruby/object:Gem::Requirement
88
+ requirements:
89
+ - - "~>"
90
+ - !ruby/object:Gem::Version
91
+ version: '1.0'
92
+ - - ">="
93
+ - !ruby/object:Gem::Version
94
+ version: 1.25.0
95
+ description: Highly opinionated PaaS based on Docker Swarm and ETCD
96
+ email: devops@prozeta.eu
97
+ executables:
98
+ - pa-service-list
99
+ - pa-lbaas-agent
100
+ extensions: []
101
+ extra_rdoc_files: []
102
+ files:
103
+ - bin/pa-lbaas-agent
104
+ - bin/pa-service-list
105
+ - lib/port-authority.rb
106
+ - lib/port-authority/agent.rb
107
+ - lib/port-authority/agents/lbaas.rb
108
+ - lib/port-authority/config.rb
109
+ - lib/port-authority/etcd.rb
110
+ - lib/port-authority/logger.rb
111
+ - lib/port-authority/mechanism/floating_ip.rb
112
+ - lib/port-authority/mechanism/load_balancer.rb
113
+ - lib/port-authority/tool.rb
114
+ - lib/port-authority/tools/service_list.rb
115
+ homepage: https://github.com/prozeta/port-authority
116
+ licenses:
117
+ - GPLv2
118
+ metadata: {}
119
+ post_install_message:
120
+ rdoc_options: []
121
+ require_paths:
122
+ - lib
123
+ required_ruby_version: !ruby/object:Gem::Requirement
124
+ requirements:
125
+ - - ">="
126
+ - !ruby/object:Gem::Version
127
+ version: 1.9.3
128
+ required_rubygems_version: !ruby/object:Gem::Requirement
129
+ requirements:
130
+ - - ">="
131
+ - !ruby/object:Gem::Version
132
+ version: '0'
133
+ requirements: []
134
+ rubyforge_project:
135
+ rubygems_version: 2.5.1
136
+ signing_key:
137
+ specification_version: 4
138
+ summary: Port Authority
139
+ test_files: []