Class: Cnvrg::Images

Inherits:
Object
  • Object
show all
Defined in:
lib/cnvrg/Images.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeImages

Returns a new instance of Images.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/cnvrg/Images.rb', line 13

def initialize()
  begin
    home_dir = File.expand_path('~')
    config = YAML.load_file(home_dir+"/.cnvrg/config.yml")
    @owner = config.to_h[:owner]
    @username =  config.to_h[:username]
  rescue => e
    @owner = ""
    @username =  ""
    Cnvrg::Logger.log_info("cnvrg is not configured")

  end

end

Class Method Details

.commit_custom_image(owner, slug, logs) ⇒ Object



176
177
178
179
# File 'lib/cnvrg/Images.rb', line 176

def self.commit_custom_image(owner,slug,logs)
  response = Cnvrg::API.request("users/#{owner}/images/#{slug}/commit_custom_image", 'POST', {image_logs:logs})
  return response
end

.create_new_custom_image(type, owner, image_name, is_public, is_base, image_extend, python3, tar_path) ⇒ Object



138
139
140
141
142
143
144
# File 'lib/cnvrg/Images.rb', line 138

def self.create_new_custom_image(type,owner,image_name,is_public,is_base,image_extend,python3,tar_path)
   response = Cnvrg::API.request("users/#{owner}/images/custom", 'POST', {instance_type:type,image_name:image_name,is_public:is_public,
                                                                            is_base:is_base,image_extend:image_extend,
                                                                            python3:python3})

  return response
end

.create_new_custom_image_with_docker(type, owner, image_name, is_public, is_base, image_extend, python3, tar_path, files) ⇒ Object



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/cnvrg/Images.rb', line 145

def self.create_new_custom_image_with_docker(type,owner,image_name,is_public,is_base,image_extend,python3,tar_path,files)
    file_name = File.basename tar_path
    file_size = File.size(tar_path).to_f
    mime_type = MimeMagic.by_path(tar_path)
    content_type = !(mime_type.nil? or mime_type.text?) ? mime_type.type : "text/plain"

    upload_resp = Cnvrg::API.request("/users/#{owner}/images/upload_docker", 'POST_FILE', {absolute_path: tar_path, relative_path: tar_path,
                                                                                    file_name: file_name, file_size: file_size,
                                                                                    file_content_type: content_type,
                                                                                    image_name:image_name,is_public:is_public,
                                                                                    is_base:is_base,image_extend:image_extend,
                                                                                    python3:python3 })

    if Cnvrg::CLI.is_response_success(upload_resp, false)
      path = upload_resp["result"]["path"]

      s3_res = files.upload_small_files_s3(path, tar_path, content_type)
      if s3_res
        image_slug = upload_resp["result"]["id"]
        response = Cnvrg::API.request("users/#{owner}/images/#{image_slug}/build", 'POST', {instance_type:type,image_extend:image_extend})
      end
    end

end

.image_exist(owner, image_name) ⇒ Object



112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/cnvrg/Images.rb', line 112

def self.image_exist(owner, image_name)

  image_res = Cnvrg::API.request("users/#{owner}/images/" + "find", 'POST', {image_name: image_name})

  if Cnvrg::CLI.is_response_success(image_res)
    image= image_res["result"]["image"]
    return image
  else
    return false

  end
end

.revoke_custom_new_image(owner, slug) ⇒ Object



172
173
174
175
# File 'lib/cnvrg/Images.rb', line 172

def self.revoke_custom_new_image(owner,slug)
  response = Cnvrg::API.request("users/#{owner}/images/#{slug}/revoke_image", 'GET')
  return response
end

.ssh_to_machine(resp) ⇒ Object



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

def self.ssh_to_machine(resp)

  sts_path = resp["result"]["sts_path"]

  uri = URI.parse(sts_path)

  http_object = Net::HTTP.new(uri.host, uri.port)
  http_object.use_ssl = true if uri.scheme == 'https'
  request = Net::HTTP::Get.new(sts_path)

  body = ""
  http_object.start do |http|
    response = http.request request
    body = response.read_body
  end

  URLcrypt::key = [body].pack('H*')

  ip = URLcrypt.decrypt(resp["result"]["machine_i"])

  user = URLcrypt.decrypt(resp["result"]["machine_u"])
  key = URLcrypt.decrypt(resp["result"]["machine_k"])
  tempssh = Tempfile.new "sshkey"
  tempssh.write open(key).read
  tempssh.rewind
  key_path = tempssh.path
  count = 0
  while count < 5

  begin
      ssh = Net::SSH.start(ip, user=user, :keys => key_path, :timeout => 10)
      if !ssh.nil?
        return ssh
      else
        count+=1
        sleep(2)

      end
    rescue
  count+=1
  sleep(2)


  end
  end
  if tempssh
    tempssh.close
    tempssh.unlink
  end
  return false
end

Instance Method Details

#container_portObject



103
104
105
106
107
108
109
110
# File 'lib/cnvrg/Images.rb', line 103

def container_port()
  config = YAML.load_file(@working_dir+"/.cnvrg/config.yml")
  if config[:container].nil?
    return false
  else
    return config[:port]
  end
end

#create_container(port = 7654, is_remote = false) ⇒ Object



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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'lib/cnvrg/Images.rb', line 309

def create_container(port=7654, is_remote=false)
  begin
    image_settings = {
        'Image' => "#{@image_name}:latest",
        'User' => 'ds',
        'Cmd' => '/usr/local/cnvrg/run_ipython.sh',
        'WorkingDir' => '/home/ds/notebooks',
        'ExposedPorts' => {
            '8888/tcp' => {},
        },
        'HostConfig' => {
            'Binds' => ["#{@working_dir}:/home/ds/notebooks"],
            'PortBindings' => {
                '8888/tcp' => [
                    {'HostPort' => "#{port}", 'HostIp' => 'localhost'}
                ],
            },
        },
    }
    container = Docker::Container.create(image_settings)
    container.start()
    netrc = File.open(File.expand_path('~')+"/.netrc", "rb")
    netrc_content = netrc.read
    container.store_file("/home/ds/.netrc", netrc_content)
    command = ["/bin/bash", "-lc", "sudo chmod 600 /home/ds/.netrc"]
    p = container.exec(command, tty: true)
    command = ["/bin/bash", "-lc", "sudo chown -R ds /home/ds/.netrc"]
    p = container.exec(command, tty: true)
    config = File.open(File.expand_path('~')+"/.cnvrg/config.yml", "rb")
    config_content = config.read
    container.store_file("/home/ds/.cnvrg/config.yml", config_content)
    command = ["/bin/bash", "-lc", "sudo chown -R ds /home/ds/.cnvrg"]
    container.exec(command, tty: true)
    # Libraries instlled
    save_installed_libraries(container)
    config = {project_name: @project_name,
              project_slug: @project_slug,
              owner: @owner,
              docker: true, image_base: @image_name, image_tag: @image_tag, container: container.id, port: port, image_slug: @image_slug}

    File.open(@working_dir+"/.cnvrg/config.yml", "w+") { |f| f.write config.to_yaml }


    return container


  rescue => e
    if e.message.include? "is not running"
      return create_container(port-1)
    end
    return false
  rescue SignalException

    say "\nAborting", Thor::Shell::Color::RED
    exit(1)
  end


end

#create_custom_image(new_image_name, working_dir, stored_commands) ⇒ Object



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/cnvrg/Images.rb', line 234

def create_custom_image(new_image_name,working_dir,stored_commands)

  python2_arr = get_installed_packages("python2")
  py2 = python2_arr.join(",") unless python2_arr.nil? or python2_arr.empty?
  python3_arr = get_installed_packages("python3")
  py3 = python3_arr.join(",") unless python3_arr.nil? or python3_arr.empty?
  system_arr = get_installed_packages("system")
  sys = system_arr.join(",") unless system_arr.nil? or system_arr.empty?

  response = Cnvrg::API.request("users/#{@owner}/projects/#{@project_slug}/images/push", 'POST', {image_slug: @image_slug, py2: py2,py3:py3,
                                                                                         dpkg: sys, new_image_name: new_image_name,
                                                                                         run_commands:stored_commands})
  if Cnvrg::CLI.is_response_success(response) and !response["result"]["slug"].nil?
    container = get_container()
    name = response["result"]["name"]
    container = get_container()
    container.commit({repo:name,tag:"latest"})
    update_image(name+":latest", container, response["result"]["slug"])
    File.truncate(working_dir+"/.cnvrg/custom_image.txt", 0)

  end

  return true

end

#find_image(update = true) ⇒ Object



431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
# File 'lib/cnvrg/Images.rb', line 431

def find_image(update=true)
  config = YAML.load_file(@working_dir+"/.cnvrg/config.yml")
  image_slug = config[:image_slug]
  if image_slug.nil? or image_slug.empty?
    image_res = Cnvrg::API.request("users/#{@owner}/images/" + "find", 'POST', {image_name: @image_name})

    if Cnvrg::CLI.is_response_success(image_res)
      image_slug = image_res["result"]["image"]["slug"]
      update_slug(image_slug) unless !update
      return image_slug
    end
  else
    return image_slug

  end
end

#get_bash_historyObject



410
411
412
413
414
415
416
417
418
# File 'lib/cnvrg/Images.rb', line 410

def get_bash_history
  container = get_container()
  command = ["/bin/bash", "-lc", "cat /home/ds/.bash_history"]
  history = container.exec(command, tty: true)[0][0]
  if history.include? "No such file"
    history = ""
  end
  return history
end

#get_container(stop = false) ⇒ Object



275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'lib/cnvrg/Images.rb', line 275

def get_container(stop=false)
  begin
    container_id=is_container_exist()

    if !container_id
      return create_container()
    else
      container = Docker::Container.get(container_id)
      status = container.json["State"]["Status"]

      if status == "running"
        return container
      else
        if stop
          return false
        end
        res = container.start()
        if res.info["State"]["Status"].eql? "exited" and  res.info["State"]["Error"].include? "port is already allocated"
          return create_container()
        end
        return container
      end
    end
  rescue => e
    if e.message.include? "No such container"

      return create_container()
    else
      return false
    end
  end

end

#get_image_stateObject



421
422
423
424
425
426
427
428
429
# File 'lib/cnvrg/Images.rb', line 421

def get_image_state
  python_arr = self.get_installed_packages("python")
  py = python_arr.join(",") unless python_arr.nil? or python_arr.empty?
  system_arr = self.get_installed_packages("system")
  sys = system_arr.join(",") unless system_arr.nil? or system_arr.empty?
  # bash_history = self.get_bash_history
  diff = [py, sys]

end

#get_installed_packages(repo) ⇒ Object



393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
# File 'lib/cnvrg/Images.rb', line 393

def get_installed_packages(repo)
  container = get_container()
  case repo
    when "python2"
      command = ['/bin/bash', '-lc', '/opt/ds/bin/pip freeze']
    when "python3"
      command = ['/bin/bash', '-lc', '/opt/ds3/bin/pip3 freeze']
    when "system"
      command = ["/bin/bash", "-lc", "dpkg -l | grep '^ii' | awk '{print $2\"==\"$3}'"]
  end

  libs = container.exec(command, tty: true)[0]
  libs_arr = libs.join("").split("\r\n")
  return libs_arr

end

#handle_image_activityObject



488
489
490
491
492
493
494
495
496
# File 'lib/cnvrg/Images.rb', line 488

def handle_image_activity
  home_dir = File.expand_path('~')
  zip_dir = "#{home_dir}/.cnvrg/tmp/config.zip"
  compress = `zip -j #{zip_dir} #{home_dir}/.netrc #{home_dir}/.cnvrg/config.yml`
  @files = Cnvrg::Files.new(@owner, @project_slug)
  res_id = @files.upload_exec_file(zip_dir, @image_name, @commit_id)
  FileUtils.remove zip_dir
  return res_id
end

#is_container_existObject



95
96
97
98
99
100
101
# File 'lib/cnvrg/Images.rb', line 95

def is_container_exist()
  config = YAML.load_file(@working_dir+"/.cnvrg/config.yml")
  if config[:container].nil?
    return false
  end
  return config[:container]
end

#new_machine(instance_type) ⇒ Object



476
477
478
479
480
481
# File 'lib/cnvrg/Images.rb', line 476

def new_machine(instance_type)
  title = "#{instance_type} auto created by cli"
  response = Cnvrg::API.request("users/#{@owner}/machines/new", 'POST', {machine_name: title, instance_type: instance_type})
  return Cnvrg::CLI.is_response_success(response)

end

#note_slugObject



453
454
455
456
457
458
459
460
461
# File 'lib/cnvrg/Images.rb', line 453

def note_slug
  config = YAML.load_file(@working_dir+"/.cnvrg/config.yml")
  note_slug = config[:notebook_slug]
  if note_slug.nil? or note_slug.empty?
    return false
  else
    return note_slug
  end
end

#remote_notebook(notebook_path, instance_type, kernel, data, data_commit) ⇒ Object



383
384
385
386
387
388
389
390
391
# File 'lib/cnvrg/Images.rb', line 383

def remote_notebook(notebook_path, instance_type, kernel,data,data_commit)
  response = Cnvrg::API.request("users/#{@owner}/images/#{@image_slug}/remote_notebook", 'POST', {dir: notebook_path,
                                                                                                  project_slug: @project_slug,
                                                                                                  instance_type: instance_type,
                                                                                                  kernel: kernel,
                                                                                                  dataset_slug:data,
                                                                                                  dataset_commit: data_commit})
  return response
end

#remove_note_slugObject



462
463
464
465
466
467
# File 'lib/cnvrg/Images.rb', line 462

def remove_note_slug
  config = YAML.load_file(@working_dir+"/.cnvrg/config.yml")
  config[:notebook_slug] = ""
  File.open(@working_dir+"/.cnvrg/config.yml", "w+") { |f| f.write config.to_yaml }

end

#save_docker_image(image_id) ⇒ Object



89
90
91
92
93
# File 'lib/cnvrg/Images.rb', line 89

def save_docker_image(image_id)
  image_res = Cnvrg::API.request("users/#{@owner}/images/#{image_id}/save" , 'POST', {})
   Cnvrg::CLI.is_response_success(image_res, true)
  return image_res
end

#save_installed_libraries(container) ⇒ Object



369
370
371
372
373
374
375
376
377
378
379
380
381
# File 'lib/cnvrg/Images.rb', line 369

def save_installed_libraries(container)
  begin
    command = ['/bin/bash', '-lc', '/opt/ds/bin/pip freeze']
    pip = container.exec(command, tty: true)[0]
    command = ["/bin/bash", "-lc", "dpkg -l | grep '^ii' | awk '{print $2\"==\"$3}'"]
    dpkg = container.exec(command, tty: true)[0]
    File.open(@working_dir+"/.cnvrg/pip_base.txt", "w+") { |f| f.write pip }
    File.open(@working_dir+"/.cnvrg/dpkg_base.txt", "w+") { |f| f.write dpkg }
  rescue => e
  end


end

#set_note_url(note_slug) ⇒ Object



448
449
450
451
452
# File 'lib/cnvrg/Images.rb', line 448

def set_note_url(note_slug)
  config = YAML.load_file(@working_dir+"/.cnvrg/config.yml")
  config[:notebook_slug] = note_slug
  File.open(@working_dir+"/.cnvrg/config.yml", "w+") { |f| f.write config.to_yaml }
end

#store_image_build_commands(working_dir, cmd) ⇒ Object



124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/cnvrg/Images.rb', line 124

def store_image_build_commands(working_dir, cmd)
  begin
  custom_image_file = working_dir+"/.cnvrg/custom_image.txt"
  if !File.exist? custom_image_file
    FileUtils.touch [custom_image_file]
  end
  File.open(custom_image_file, 'a' ) do  |f|
    f.puts cmd
  end
  rescue
  end


end

#update_image(image_name, container, image_slug) ⇒ Object



260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/cnvrg/Images.rb', line 260

def update_image(image_name, container, image_slug)
  config = YAML.load_file(@working_dir+"/.cnvrg/config.yml")
  @image_name = image_name
  if !@image_name.nil? and !@image_name.empty?
    @image_name = image_name[0, image_name.index(":")]
    @image_tag = image_name[image_name.index(":")+1, image_name.size]
  end
  config = {project_name: config[:project_name],
            project_slug: config[:project_slug],
            owner: config[:owner],
            docker: true, image_base: @image_name, image_tag: @image_tag, container: container.id, image_slug: image_slug}

  File.open(@working_dir+"/.cnvrg/config.yml", "w+") { |f| f.write config.to_yaml }
end

#update_image_activity(commit, exp_slug) ⇒ Object



483
484
485
486
# File 'lib/cnvrg/Images.rb', line 483

def update_image_activity(commit, exp_slug)
  response = Cnvrg::API.request("users/#{@owner}/images/#{@image_slug}/update_activity", 'POST', {commit: commit, project_slug: @project_slug, experiment: exp_slug})
  return Cnvrg::CLI.is_response_success(response)
end

#update_slug(slug) ⇒ Object



470
471
472
473
474
# File 'lib/cnvrg/Images.rb', line 470

def update_slug(slug)
  config = YAML.load_file(@working_dir+"/.cnvrg/config.yml")
  config[:image_slug] = slug
  File.open(@working_dir+"/.cnvrg/config.yml", "w+") { |f| f.write config.to_yaml }
end

#upload_docker_image(image_path, image_name, workdir, user, description, is_gpu) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
# File 'lib/cnvrg/Images.rb', line 28

def upload_docker_image(image_path, image_name,workdir, user, description, is_gpu )
  begin
  if image_name.present? and image_name.include? ":"
    image_split = image_name.split(":")
    image_name = image_split[0]
    image_tag = image_split[1]
    if image_tag.blank?
      image_tag = "latest"
    end
    if image_name.blank?
      Cnvrg::Logger.log_info("image_name: #{image_name} is not valid")
      return false
    end
  end
  if !File.exist? image_path
    Cnvrg::Logger.log_info("image_path: #{image_path} was not found")
    return false
  end
  is_dockerfile = (!image_path.end_with? ".tar") ? true : false
  file_name = File.basename image_path
  file_size = File.size(image_path).to_f
  mime_type = MimeMagic.by_path(image_path)
  content_type = mime_type.present? ? mime_type.type : "application/x-tar"

  image_res = Cnvrg::API.request("users/#{@owner}/images/upload" , 'POST_FILE', {image_name: image_name, image_tag: image_tag,
                                                                            workdir: workdir, user: user, description:description, is_gpu:is_gpu,
                                                                            file_name: file_name,relative_path:image_path,
                                                                            file_size: file_size, file_content_type: content_type, is_dockerfile: is_dockerfile
                                                                             })
  Cnvrg::CLI.is_response_success(image_res, true)

  path = image_res["result"]["path"]
  image_id = image_res["result"]["image_id"]

  props = Cnvrg::Helpers.get_s3_props(image_res["result"])
  if props.is_a? Cnvrg::Result
    return false
  end

  client = props[:client]
  upload_options = props[:upload_options]
  bucket = Aws::S3::Resource.new(client: client).bucket(props[:bucket])

  resp = bucket.object(path).
      upload_file(image_path, upload_options)

  unless resp
    raise Exception.new("Cant upload #{image_path}")
    return false
  end
  return save_docker_image(image_id)
  rescue => e
    Cnvrg::Logger.log_error(e)

    return false
  end



end