Module: Cnvrg::Helpers

Extended by:
Helpers
Included in:
Helpers
Defined in:
lib/cnvrg/helpers.rb

Defined Under Namespace

Classes: Agent, Executer

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.parallel_optionsObject



9
10
11
12
13
14
15
# File 'lib/cnvrg/helpers.rb', line 9

def self.parallel_options
  {
      in_processes: Cnvrg::CLI::ParallelProcesses,
      in_thread: Cnvrg::CLI::ParallelThreads,
      isolation: true
  }
end

Instance Method Details

#checkmarkObject



16
17
18
19
# File 'lib/cnvrg/helpers.rb', line 16

def checkmark
  checkmark = "\u2713"
  return checkmark.encode('utf-8')
end

#cnvrgignore_contentObject



152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/cnvrg/helpers.rb', line 152

def cnvrgignore_content
  #TODO: cnvrg ignore add .conflict
  %{
# cnvrg ignore: Ignore the following directories and files
# for example:
# some_dir/
# some_file.txt
.git*
.gitignore
*.conflict
*.deleted
        }.strip
end

#cpu_timeObject

cpu



256
257
258
# File 'lib/cnvrg/helpers.rb', line 256

def cpu_time
  Process.clock_gettime(Process::CLOCK_PROCESS_CPUTIME_ID, :microsecond)
end

#decrypt(key, iv, str) ⇒ Object



264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/cnvrg/helpers.rb', line 264

def decrypt(key,iv,str)
  begin

  cipher = OpenSSL::Cipher.new("aes-256-cbc").decrypt
  cipher.key = key
  cipher.iv = Base64.decode64 iv.encode('utf-8')

  result = Base64.decode64 (str.encode('utf-8'))
  result = cipher.update(result)
  result << cipher.final
  return result.force_encoding('utf-8')

  # return result
  rescue => e
    puts e


  end


end

#extract_owner_slug_from_url(url, breaker) ⇒ Object



246
247
248
249
250
251
252
# File 'lib/cnvrg/helpers.rb', line 246

def extract_owner_slug_from_url(url, breaker)
  url_parts = url.split("/")
  project_index = Cnvrg::Helpers.look_for_in_path(url, breaker)
  slug = url_parts[project_index + 1]
  owner = url_parts[project_index - 1]
  return owner, slug
end

#get_configObject



45
46
47
48
49
50
51
52
53
54
# File 'lib/cnvrg/helpers.rb', line 45

def get_config
  home_dir = File.expand_path('~')
  config = {}
  begin
    if File.exist? home_dir+"/.cnvrg/config.yml"
      config = YAML.load_file(home_dir+"/.cnvrg/config.yml")
    end
  end
  return config
end

#get_experiment_events_log_from_server(exp, project, commit: nil) ⇒ Object



355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
# File 'lib/cnvrg/helpers.rb', line 355

def get_experiment_events_log_from_server(exp, project, commit: nil)
  dest_dir = exp["slug"]
  commit = commit || exp["end_commit"]
  response = project.clone(0, commit)
  Cnvrg::CLI.is_response_success(response, should_exit=false)
  commit_sha1 = response["result"]["commit"]
  files = response["result"]["tree"].keys
  files = files.select do |f| f.include?("tfevents") end
  @files = Cnvrg::Files.new(project.owner, project.slug, project_home: "", project: project)
  @files.download_files(files, commit_sha1, progress: nil)
  FileUtils.rm_rf("#{dest_dir}")
  FileUtils.mkdir_p(dest_dir)
  num_of_new_files = 0
  files.each do |f|
    file_dir = "#{dest_dir}/#{File.dirname(f)}"
    FileUtils.mkdir_p(file_dir)
    num_of_new_files += 1 unless File.exist?("#{dest_dir}/#{f}")
    FileUtils.mv(f, "#{dest_dir}/#{f}")
  end
  return num_of_new_files
end

#get_experiment_events_log_via_kubectl(exp, namespace) ⇒ Object



377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/cnvrg/helpers.rb', line 377

def get_experiment_events_log_via_kubectl(exp, namespace)
  dest_dir = exp["slug"]
  result = `kubectl -n #{namespace} get pods | grep #{exp["slug"]}`

  pod_name = result.split(" ")[0]
  return false, 0 if pod_name.blank?
  FileUtils.mkdir_p(dest_dir)
  working_dir = `kubectl -n #{namespace} exec #{pod_name} -c agent -- pwd`
  working_dir.strip!
  res = `kubectl -n #{namespace} exec #{pod_name} -c agent -- /bin/bash -c "ls -R #{working_dir}"`
  files_and_folders = res.split("\n\n")
  all_files = []

  files_and_folders.each do |file_and_folder|
    files = file_and_folder.split("\n")
    if files.first.include?(":")
      folder = files.first.gsub(":", "")

      folder = folder.sub(working_dir + "/", "")
      files = files.drop(1)
    end
    files.each do |file|
      if file.include?("tfevents")
        all_files << "#{folder}/#{file}"
      end
    end
  end

  num_of_new_files = 0
  all_files.each do |file|
    file_dir = "#{dest_dir}/#{File.dirname(file)}"
    FileUtils.mkdir_p(file_dir)
    num_of_new_files += 1 unless File.exist?("#{dest_dir}/#{file}")
    res = `kubectl -n #{namespace} cp #{pod_name}:#{file} -c agent #{dest_dir}/#{file}`
  end

  return true, num_of_new_files
rescue => e
  Cnvrg::Logger.log_error(e)
  return false, 0
end

#get_mem(pid) ⇒ Object

memory



288
289
# File 'lib/cnvrg/helpers.rb', line 288

def get_mem(pid)
end

#get_s3_props(files) ⇒ Object

will return client and decryptor



291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/cnvrg/helpers.rb', line 291

def get_s3_props(files) #will return client and decryptor
  sts_path = files["path_sts"]
  retries = 0
  success= false
  while !success and retries < 20
    begin
      if !Helpers.is_verify_ssl
        body = open(sts_path, {ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE}).read
      else
        body = open(sts_path).read
      end
      success = true
    rescue => e
      retries +=1
      sleep(5)

    end
  end
  if !success
    return Cnvrg::Result.new(false,"couldn't download some files", "error in sts", "" )
  end
  split = body.split("\n")
  key = split[0]
  iv = split[1]

  access =  Cnvrg::Helpers.decrypt(key, iv, files["sts_a"])

  secret =  Cnvrg::Helpers.decrypt(key,iv, files["sts_s"])

  session =  Cnvrg::Helpers.decrypt(key,iv, files["sts_st"])
  region =  Cnvrg::Helpers.decrypt(key,iv, files["region"])

  bucket =  Cnvrg::Helpers.decrypt(key,iv, files["bucket"])
  is_s3 = files["is_s3"]
  server_side_encryption =files["server_side_encryption"]

  if is_s3 or is_s3.nil?
    client = Aws::S3::Client.new(
        :access_key_id =>access,
        :secret_access_key => secret,
        :session_token => session,
        :region => region,
        :http_open_timeout => 60, :retry_limit => 20)
    use_accelerate_endpoint = true
  else

    endpoint = Cnvrg::Helpers.decrypt(key,iv, files["endpoint"])
    client = Aws::S3::Client.new(
        :access_key_id =>access,
        :secret_access_key => secret,
        :region => region,
        :endpoint=> endpoint,:force_path_style=> true,:ssl_verify_peer=>false,
        :http_open_timeout => 60, :retry_limit => 20)
    use_accelerate_endpoint = false
  end

  if !server_side_encryption
    upload_options = {:use_accelerate_endpoint => use_accelerate_endpoint}
  else
    upload_options = {:use_accelerate_endpoint => use_accelerate_endpoint, :server_side_encryption => server_side_encryption}
  end
  return {client: client, key: key, iv: iv, bucket: bucket, upload_options: upload_options}
end

#hyper_contentObject



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
# File 'lib/cnvrg/helpers.rb', line 166

def hyper_content
  %{# Hyperparameter Optimization is the process of choosing a set of parameters for a learning algorithm, usually with the goal of optimizing a measure of the algorithm's performance on an independent data set.

# Below is the list of parameters that will be used in the optimization process. Each parameter has a param_name that should match the argument that is feeded to the experiment s.t kernel => --kernel='rbf'

parameters:
  # Integer parameter is a range of possible values between a minimum (inclusive)
  # and maximum (not inclusive) values. Values are floored (0.7 => 0)
- param_name: "learning_rate"
  type: "integer" 
  min: 0 # inclusive
  max: 10 # not inclusive
  scale: "linear"
  steps: 4 # The number of linear steps to produce.


# Float parameter is a range of possible values between a minimum (inclusive)
# and maximum (not inclusive) values.
#
- param_name: "learning_rate"
  type: "float" # precision is 9 after period
  min: 0.00001
  max: 0.1
  scale: "log2" # Could be log10 as well
  steps: 2

# Discrete parameter is an array of numerical values.
#
- param_name: "c"
  type: "discrete"
  values: [0, 0.1 ,0.001]

# Categorical parameter is an array of string values
#
- param_name: "kernel"
  type: "categorical"
  values: ["linear", "poly", "rbf"] 

}
end

#internet_connection?Boolean

Returns:

  • (Boolean)


21
22
23
24
25
26
27
# File 'lib/cnvrg/helpers.rb', line 21

def internet_connection?
  begin
    true if open("http://www.google.com/")
  rescue
    false
  end
end

#is_verify_sslObject



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/cnvrg/helpers.rb', line 97

def is_verify_ssl
  home_dir = File.expand_path('~')
  config = ""
  begin
    if File.exist? home_dir+"/.cnvrg/config.yml"
      config = YAML.load_file(home_dir+"/.cnvrg/config.yml")
    else
     return true

    end

  rescue
    return true
  end
  if !config or config.empty? or config.to_h[:verify_ssl].nil?
    return true
  else
    return config.to_h[:verify_ssl]
  end
end

#linux?Boolean

Returns:

  • (Boolean)


143
144
145
# File 'lib/cnvrg/helpers.rb', line 143

def linux?
  not mac? and not windows?
end

#look_for_in_path(path, name) ⇒ Object



236
237
238
239
240
241
242
243
244
# File 'lib/cnvrg/helpers.rb', line 236

def look_for_in_path(path, name)
  url_split = path.split("/")
  url_split.each_with_index do |u, i|
    if u == name
      return i
    end
  end
  return -1
end

#mac?Boolean

Returns:

  • (Boolean)


139
140
141
# File 'lib/cnvrg/helpers.rb', line 139

def mac?
  !!(RUBY_PLATFORM =~ /-darwin\d/)
end

#netrc_domainObject



232
233
234
# File 'lib/cnvrg/helpers.rb', line 232

def netrc_domain
  "cnvrg.io"
end

#osObject



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/cnvrg/helpers.rb', line 118

def os

  if windows?
    return "windows"
  elsif mac?
    return "mac"
  elsif ubuntu?
    return "ubuntu"
  elsif linux?

    return "linux"
  else

    return "N/A"
  end
end

#parallel_threadsObject



5
6
7
# File 'lib/cnvrg/helpers.rb', line 5

def parallel_threads
  15
end

#readme_contentObject



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# File 'lib/cnvrg/helpers.rb', line 207

def readme_content
  %{
        # README

        This README would normally contain some context and description about the project. 

        Things you may want to cover:

        * Data description

        * Benchmark and measurement guidelines

        * Used algorithms

        * Scores

        * Configurations

        * Requirements

        * How to run the experiments

        * ...}.strip
end

#remote_urlObject



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/cnvrg/helpers.rb', line 63

def remote_url
  home_dir = File.expand_path('~')
  config = ""
  begin
    if File.exist? home_dir+"/.cnvrg/config.yml"
      config = YAML.load_file(home_dir+"/.cnvrg/config.yml")
    else
      return "https://app.cnvrg.io"
    end

  rescue
    return "https://app.cnvrg.io"
  end
  if !config or config.empty? or config.to_h[:api].nil?
    return "https://app.cnvrg.io"
  else
    return config.to_h[:api].gsub("/api", "")
  end
end

#server_versionObject



83
84
85
86
# File 'lib/cnvrg/helpers.rb', line 83

def server_version
  config = self.get_config
  config[:version].try(:to_i) || 0
end

#set_config(config) ⇒ Object



56
57
58
59
60
# File 'lib/cnvrg/helpers.rb', line 56

def set_config(config)
  home_dir = File.expand_path('~')
  File.open("#{home_dir}/.cnvrg/config.yml", "w"){|f| f.write config.to_yaml }
  return config
end

#try_until_success(tries: 3) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/cnvrg/helpers.rb', line 29

def try_until_success(tries: 3)
  exception = nil
  tries.times do |i|
    begin
      yield
      return true
    rescue => e
      Cnvrg::Logger.log_info("Error while trying for the #{i} time")
      Cnvrg::Logger.log_error(e)
      sleep(1)
      exception = e
    end
  end
  raise exception
end

#ubuntu?Boolean

Returns:

  • (Boolean)


147
148
149
150
# File 'lib/cnvrg/helpers.rb', line 147

def ubuntu?
  unix = `if [ -f  /etc/lsb-release ];  then echo "ubuntu"; fi`
  return unix.include? "ubuntu"
end

#update_version(version) ⇒ Object



88
89
90
91
92
93
94
95
# File 'lib/cnvrg/helpers.rb', line 88

def update_version(version)
  config = self.get_config
  if config[:version].to_s.eql? version
    return
  end
  config[:version] = version
  self.set_config(config)
end

#wall_timeObject



260
261
262
# File 'lib/cnvrg/helpers.rb', line 260

def wall_time
  Process.clock_gettime(Process::CLOCK_MONOTONIC, :microsecond)
end

#windows?Boolean

Returns:

  • (Boolean)


135
136
137
# File 'lib/cnvrg/helpers.rb', line 135

def windows?
  !!(RUBY_PLATFORM =~ /mswin32|mingw32/)
end