Module: KL

Defined in:
lib/kldockeragent.rb,
lib/kldockeragent/net.rb,
lib/kldockeragent/agent.rb,
lib/kldockeragent/helper.rb,
lib/kldockeragent/commands.rb

Defined Under Namespace

Modules: Agent Classes: Api, Notifier, Server

Class Method Summary collapse

Class Method Details

.Command_notifyStatusObject



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/kldockeragent/commands.rb', line 22

def KL.Command_notifyStatus
  KL.logger.info '[command] Sending instance update...'
  data = KL.prepare_agent_data
  uri = "#{KL.config['notifier']['server']}/api/1.0/nodes/data"
  headers_auth = KL.getAuthorizationHeaders('/api/1.0/nodes/data', data.to_json)
  res = KL.net_post_json(uri, data.to_json, headers_auth)
  if res.is_a?(Net::HTTPSuccess)
    KL.logger.info '[command] Agent notification successfully executed.'
  else
    KL.logger.info '[command] An error has occurred trying to notify update.'
  end
end

.Command_registerNewAgentObject



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/kldockeragent/commands.rb', line 2

def KL.Command_registerNewAgent
  KL.logger.info '[command] Registering new agent...'
  agent = KL::Agent.getUUID
  data = KL.prepare_agent_register_data(agent)
  uri = "#{KL.config['notifier']['server']}/api/1.0/nodes/register"
  res = KL.net_post_json(uri, data.to_json)

  if res.is_a?(Net::HTTPSuccess)
    response = JSON.parse(res.body)
    registry = {
      agent: agent,
      server: response['code']
    }
    KL.create_registry_file(registry)
    KL.logger.info '[command] Agent registration has been completed correctly'
  else
    KL.logger.info '[command] An error has occurred trying to register agent.'
  end
end

.configObject



34
35
36
37
38
39
40
# File 'lib/kldockeragent/helper.rb', line 34

def KL.config
  configFile = "#{KL.home}/kldockeragent.json"
  KL.create_default_config(configFile, KL.logger) if !File.exist?(configFile)
    config_json = File.read(configFile)
    config_data = JSON.parse(config_json)
    config_data
end

.create_default_config(file, logger) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
# File 'lib/kldockeragent/helper.rb', line 6

def KL.create_default_config(file, logger)
  File.open(file, File::RDWR|File::CREAT, 0644) { |f|
    f.flock(File::LOCK_EX)
    value = '{"api":{"port":3344,"ssl":false},"notifier":{"server":"https://hub.kytoonlabs.com:4444","rate":120}}'
    f.rewind
    f.write(value.to_s)
    f.flush
    f.truncate(f.pos)
  }
  logger.info "[config] Default config file has been created at {#{file}}" if logger
end

.create_registry_file(data) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
# File 'lib/kldockeragent/helper.rb', line 65

def KL.create_registry_file(data)
  file = "#{KL.home}/kldockeragent.registry"
  File.open(file, File::RDWR|File::CREAT, 0644) { |f|
    f.flock(File::LOCK_EX)
    f.rewind
    f.write(data.to_json.to_s)
    f.flush
    f.truncate(f.pos)
  }
  logger.info "[config] Registry config file has been created at {#{file}}" if logger
end

.generateHash(url, json_data, private_key) ⇒ Object



104
105
106
107
108
# File 'lib/kldockeragent/helper.rb', line 104

def KL.generateHash(url, json_data, private_key)
  data = "#{url}#{json_data}"
  hash_data = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha1'), private_key, data)
  hash_data 
end

.getApplicationIdObject



82
83
84
85
86
87
88
89
90
# File 'lib/kldockeragent/helper.rb', line 82

def KL.getApplicationId
  if (KL.server_registered)
    registry = KL.getRegistryData
    id = registry['agent']
  else
    id = SecureRandom.uuid
  end
  id
end

.getApplicationInfo(name, filter) ⇒ Object



176
177
178
179
180
181
182
# File 'lib/kldockeragent/helper.rb', line 176

def KL.getApplicationInfo(name, filter)
  output = ""
  if (name.include? filter)
    output = name.gsub(filter,'')
  end
  return output
end

.getAuthorizationHeaders(url, json_data) ⇒ Object



92
93
94
95
96
97
98
99
100
101
102
# File 'lib/kldockeragent/helper.rb', line 92

def KL.getAuthorizationHeaders(url, json_data)
  headers = {}
  if (KL.server_registered)
    registry = KL.getRegistryData
    hash_data = KL.generateHash(url, json_data, registry['agent'])
    auth_code = "#{registry['server']}:#{hash_data}"
    headers = {}
    headers['Authorization'] = auth_code
  end
  headers
end

.getDockerConfigData(container) ⇒ Object



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
# File 'lib/kldockeragent/helper.rb', line 139

def KL.getDockerConfigData(container)
  query = `docker stats --no-stream #{container}`
  query.gsub!(/\r\n?/, "\n")
  keys = Array.new
  values = Array.new
  out = '{'
  i = 0
  query.each_line do |line|
    data = line.split('  ')
    data.each do |value|
      if (value.strip != '')
        if (i == 0)
          keys.push(value.strip)
        else
          values.push(value.strip)
        end
      end
    end
    i = i + 1
  end
  i = 0
  keys.each do |key|
    if (i > 0)
      out = out + ','
    end
      out = out + "\"#{key}\":\"#{values[i]}\""
      i = i + 1
  end
  out = out + '}'

  return JSON.parse(out)
end

.getRegistryDataObject



77
78
79
80
# File 'lib/kldockeragent/helper.rb', line 77

def KL.getRegistryData
  json_reg = JSON.parse(File.open("#{KL.home}/kldockeragent.registry").read)
  json_reg
end

.homeObject



29
30
31
32
# File 'lib/kldockeragent/helper.rb', line 29

def KL.home
  home = ((Process.euid == 0 and File.directory?('/var')) ? '/var/kldockerpagent' : File.expand_path(Dir.home + '/.kldockeragent'))
  home
end

.loggerObject



18
19
20
21
22
23
24
25
26
27
# File 'lib/kldockeragent/helper.rb', line 18

def KL.logger
  home = KL.home
  Dir.mkdir(home, 0700) if not File.exist?(home)
  logFile = "#{home}/kldockeragent.log"
  log = WEBrick::Log.new(logFile, WEBrick::BasicLog::INFO ||
                                       WEBrick::BasicLog::ERROR ||
                                       WEBrick::BasicLog::FATAL ||
                                       WEBrick::BasicLog::WARN)
  log
end

.net_post_json(url, data, headers = []) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/kldockeragent/net.rb', line 4

def KL.net_post_json(url, data, headers = [])
  KL.logger.info "[net] Posting JSON to #{url} => #{data}"
  
  uri = URI(url)
  
  req = Net::HTTP::Post.new(uri)
  req.content_type = 'application/json'
  req.body = data
  req['X-Kytoonlabs-Docker-Agent'] = KL::Agent.getUUID[0..13].gsub(/\s\w+\s*$/, '')
  headers.each do |key, value|
    req[key] = value
  end

  Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https') do |http|
       @res = http.request req
  end
  KL.logger.info "[net] Response Code: #{@res.code}, Response Body: #{@res.body}"
  @res
end

.prepare_agent_dataObject



110
111
112
113
114
115
116
117
118
# File 'lib/kldockeragent/helper.rb', line 110

def KL.prepare_agent_data
  data = {
    system_info: KL.Request_getSystemInfo,
    docker_info: KL.Request_getDockerListAllApplications,
    agent_version: KL::Agent.getVersion
  }
  data

end

.prepare_agent_register_data(hash) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
# File 'lib/kldockeragent/helper.rb', line 53

def KL.prepare_agent_register_data(hash)
  data = {
    private_hash: hash,
    hostname: `hostname`.gsub("\n",""),
    system_info: `uname -a`.gsub("\n",""),
    docker_version: `docker --version`.gsub("\n","").gsub("Docker version ",""),
    agent_version: KL::Agent.getVersion,
    ip_address: IPSocket.getaddress(Socket.gethostname) 
  }
  data
end

.publish_json(json_object, st = 200) ⇒ Object



48
49
50
51
52
# File 'lib/kldockeragent/helper.rb', line 48

def KL.publish_json(json_object, st = 200)
  status st
  content_type :json
  json_object.to_json   
end

.removeEmptyObjects(json) ⇒ Object



172
173
174
# File 'lib/kldockeragent/helper.rb', line 172

def KL.removeEmptyObjects(json)
  return json.gsub('{}','""')
end

.Request_getDockerListAllApplicationsObject



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/kldockeragent/helper.rb', line 120

def KL.Request_getDockerListAllApplications
  filter = '_klac'
  apps = Array.new
    query = `docker ps --format="{{.ID}}::{{.Names}}::{{.Status}}::{{.Image}}"`
    query.gsub!(/\r\n?/, "\n")
    query.each_line do |line|
        data = line.split('::')
        apps.push({
          'id' => data[0], 
          'name' => data[1],
          'status'=>data[2],
          'image'=>data[3].gsub("\n",""),
          'stats'=>KL.getDockerConfigData(data[0]),
          'application' => KL.getApplicationInfo(data[1], filter)
          })
    end
    return apps
end

.Request_getSystemInfoObject



184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/kldockeragent/helper.rb', line 184

def KL.Request_getSystemInfo
  usw = Usagewatch
  info = {}
  if KL::Agent.is_linux
    info['os'] = 'linux'
    info['diskused'] = usw.uw_diskused.to_s
    info['diskused_perc'] = usw.uw_diskused_perc.to_s
    info['cpuused'] = usw.uw_cpuused.to_s
    info['memused'] = usw.uw_memused.to_s
  else
    info['os'] = 'not linux'
  end 
  info
end

.server_registeredObject



42
43
44
45
46
# File 'lib/kldockeragent/helper.rb', line 42

def KL.server_registered
  registryFile = "#{KL.home}/kldockeragent.registry"
  reg = File.exist?(registryFile)
  reg
end