Class: Cnvrg::CLI

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

Constant Summary collapse

INSTALLATION_URLS =
{docker: "https://docs.docker.com/engine/installation/", jupyter: "http://jupyter.readthedocs.io/en/latest/install.html"}
IP =
"localhost"
PORT =
7654

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.is_thor_reserved_word?(word, type) ⇒ Boolean

Hackery.Take the run method away from Thor so that we can redefine it.

Returns:

  • (Boolean)


153
154
155
156
# File 'lib/cnvrg/cli.rb', line 153

def is_thor_reserved_word?(word, type)
  return false if word == "run"
  super
end

Instance Method Details

#build(*cmd) ⇒ Object



3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
# File 'lib/cnvrg/cli.rb', line 3966

def build(*cmd)
  begin
    verify_logged_in(false)
    log_start(__method__, args, options)
    working_dir = is_cnvrg_dir
    install_file = options["install"] || nil
    if !install_file.nil?
      commands = File.open(install_file).read.chop.gsub!("\n", ",").split(",")

    else
      commands = [cmd.join(" ")]
    end


    image = is_project_with_docker(working_dir)
    if image and image.is_docker
      container = image.get_container
      if !container

        say "Couldn't create container with image #{image.image_name}:#{image.image_tag}", Thor::Shell::Color::RED
        exit(1)
      end
    else
      say "Project is not configured with any image", Thor::Shell::Color::RED
      exit(1)

    end
    commands.each do |c|
      if c.include? "pip"
        c.sub("pip", "/opt/ds/bin/pip")
      end
      if c.include? "pip3"
        c.sub("pip3", "/opt/ds3/bin/pip3")
      end

      say "Running #{c}", Thor::Shell::Color::BLUE
      command = ["/bin/bash", "-lc", "#{c}"]
      res = container.exec(command, tty: false)
      if res[2] != 0
        say "Could not run command: #{c}, #{res[1][0]}", Thor::Shell::Color::RED
        container.stop()
        log_end(0)

        exit(1)
      end
      say res[0].join("\n")
      image.store_image_build_commands(working_dir, c)
    end

    checks = Helpers.checkmark()
    say "Updating image", Thor::Shell::Color::BLUE
    # image.create_custom_image("",working_dir)
    container.stop()
    say "#{checks} Done", Thor::Shell::Color::GREEN

    log_end(0)
  rescue => e
    log_end(-1, e.message)
    say "Error occurred, aborting", Thor::Shell::Color::RED
    if container
      container.stop()
    end
  rescue SignalException
    log_End(-1)
    if container
      container.stop()
    end
    say "\nAborting"
    exit(1)
  end

end

#build_image(image_name) ⇒ Object



3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
# File 'lib/cnvrg/cli.rb', line 3839

def build_image(image_name)
  begin
    verify_logged_in(false)
    log_start(__method__, args, options)
    instances = {"small" => options["small"], "medium" => options["medium"], "large" => options["large"],
                 "gpu" => options["gpu"], "gpuxl" => options["gpuxl"], "gpuxxl" => options["gpuxxl"]}
    instance_type = get_instance_type(instances)
    image_extend = options["image"]
    public = options["public"]
    base = options["base"]
    python3 = options["python3"]
    docker_path = options["docker_path"]
    owner = CLI.get_owner
    checks = Helpers.checkmark()
    tar_path = nil
    if !docker_path.nil? and !docker_path.empty?
      docker_path = File.absolute_path(docker_path)
      #create tar of the docker path: it could be a docker file, and it could be a docker folder
      tar_path = File.expand_path('~')+"/.cnvrg/tmp/docker_#{File.basename docker_path}.tar.gz"
      resp = create_docker_tar(docker_path, tar_path)
      if !resp
        log_message("Couldn't create tar from docker path", Thor::Shell::Color::RED)
        FileUtils.rm_rf tar_path
        exit(1)
      end
      files = Cnvrg::Files.new(owner, "")
      resp = Images.create_new_custom_image_with_docker(instance_type, owner, image_name, public, base, image_extend, python3, tar_path, files)
      if resp
      end
    else
      log_message("Creating machine for your custom image, this may take a few moments...", Thor::Shell::Color::BLUE)
      resp = Images.create_new_custom_image(instance_type, owner, image_name, public, base, image_extend, python3, nil)

    end

    if Cnvrg::CLI.is_response_success(resp, false)
      image_slug = resp["result"]["slug"]
      container = resp["result"]["machine_c"]
      log_message("#{checks} Created image and machine successfully", Thor::Shell::Color::GREEN)
      log_message("Connecting to machine", Thor::Shell::Color::BLUE)
      ssh = Ssh.new(resp)
      if !ssh.is_ssh
        log_message("Couldn't connect to machine,aborting", Thor::Shell::Color::RED)
        Images.revoke_custom_new_image(owner, image_slug)
      end
      log_message("run command until ctrl + c or quit is initiated", Thor::Shell::Color::BLUE)
      begin
        logs = []

        while true
          command = ask("$>")
          logs << {time: Time.now,
                   message: command,
                   type: "stdout"
          }
          if command.eql? "quit"
            log_message("Commiting Image..", Thor::Shell::Color::BLUE)
            break
          end
          res = ssh.exec_command(command)
          begin
            res_parsed = JSON.parse(res)
            res = res_parsed.join(",")
          end

          puts res
          logs << {time: Time.now,
                   message: res,
                   type: "stdout"
          }
          logs.flatten!

        end

      rescue SignalException
        log_message("Commiting Image..", Thor::Shell::Color::BLUE)

      end
      resp = Images.commit_custom_image(owner, image_slug, logs)
      if Cnvrg::CLI.is_response_success(resp, false)
        log_message("#{checks} Image commited successfuly, email will be sent when image is ready", Thor::Shell::Color::GREEN)
      else
        if image_slug
          Images.revoke_custom_new_image(owner, image_slug)
        end
        if ssh
          ssh.close_ssh()
        end
        log_message("Image couldn't be commited, rolling back changes", Thor::Shell::Color::RED)

        exit(1)
      end
      if ssh
        ssh.close_ssh()
      end


    end
  rescue => e
    log_message("Error occurd, aborting", Thor::Shell::Color::RED)

    log_error(e)
    if image_slug
      Images.revoke_custom_new_image(owner, image_slug)
    end
    if ssh
      ssh.close_ssh()
    end


  rescue SignalException
    if image_slug
      Images.revoke_custom_new_image(owner, image_slug)
    end
    if ssh
      ssh.close_ssh
    end
    say "\nAborting"
    exit(1)
  end

end

#clone(project_url) ⇒ Object



1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
# File 'lib/cnvrg/cli.rb', line 1468

def clone(project_url)
  begin
    verify_logged_in(false)
    log_start(__method__, args, options)
    url_parts = project_url.split("/")
    project_index = Cnvrg::Helpers.look_for_in_path(project_url, "projects")
    slug = url_parts[project_index+1]
    owner = url_parts[project_index-1]
    remote = options["remote"] || false
    response = Cnvrg::API.request("users/#{owner}/projects/#{slug}/get_project", 'GET')
    Cnvrg::CLI.is_response_success(response)
    response = JSON.parse response["result"]
    project_name = response["title"]
    commit_to_clone = options["commit"] || nil

    log_message("Cloning #{project_name}", Thor::Shell::Color::BLUE)
    clone_resp = false
    if remote
      clone_resp = Project.clone_dir_remote(slug, owner, project_name)
      project_home = Dir.pwd
    else
      if (Dir.exists? project_name)
        log_message("Error: Conflict with dir #{project_name}", Thor::Shell::Color::RED)
        if no? "Sync to repository anyway? (current data might lost)", Thor::Shell::Color::YELLOW
          log_message("Remove dir in order to clone #{project_name}", Thor::Shell::Color::RED)
          exit(1)
        end

      end
      clone_resp = Project.clone_dir(slug, owner, project_name)
      project_home = Dir.pwd+"/"+project_name


    end

    if clone_resp
      @project = Project.new(project_home)
      @files = Cnvrg::Files.new(@project.owner, slug)
      response = @project.clone(remote, commit_to_clone)
      Cnvrg::CLI.is_response_success response
      working_dir = project_home
      docker_image = response["result"]["image"]
      current_commit = response["result"]["commit"]
      idx = {commit: response["result"]["commit"], tree: response["result"]["tree"]}
      File.open(working_dir + "/.cnvrg/idx.yml", "w+") { |f| f.write idx.to_yaml }
      if !docker_image.nil? and !docker_image.empty? and !remote
        local_images = Docker::Image.all
        docker_image_local = local_images.map { |x| x.info["RepoTags"] }.flatten.select { |y| y.eql? "#{docker_image}:latest" }.flatten
        if docker_image_local.size == 0
          if yes? "Image wasn't found locally, pull image from cnvrg repository?", Thor::Shell::Color::YELLOW
            image = pull(docker_image)
            if image
              log_message("downloaded image: #{docker_image}", Thor::Shell::Color::BLUE)
              @image = Images.new(working_dir, docker_image)
            else
              log_message("Could not create a new project with docker, image was not found", Thor::Shell::Color::RED)
              @project.revert(working_dir)
              exit(1)
            end
          end

        elsif docker_image_local.size == 1
          log_message("found image: #{docker_image_local[0]}, setting it up..", Thor::Shell::Color::BLUE)
          @image = Images.new(working_dir, docker_image_local[0])
        elsif docker_image_local.size >1
          log_message("found #{docker_image_local.size} images, choose the image name you want to use", Thor::Shell::Color::BLUE)
          image_name = ask "#{docker_image_local.join("\n")}\n", Thor::Shell::Color::BLUE
          @image = Images.new(working_dir, image_name)
        end

      end

      successful_changes = []
      log_message("Downloading files", Thor::Shell::Color::BLUE)
      if !response["result"]["tree"].nil?
        parallel_options = {
            :progress => {
                :title => "Download Progress",
                :progress_mark => '=',
                :format => "%b>>%i| %p%% %t",
                :starting_at => 0,
                :total => response["result"]["tree"].size,
                :autofinish => true
            },
            in_processes: ParallelProcesses,
            in_thread: ParallelThreads
        }
        begin
          is_success = true
          clone_result = Parallel.map((response["result"]["tree"]), parallel_options) do |f|

            relative_path = f[0].gsub(/^#{@project.local_path}/, "")
            if f[0].end_with? "/"
              # dir
              if @files.download_dir(f[0], relative_path, project_home)
                f
                successful_changes << relative_path
              else
                is_success =false
                log_message("Could not create directory: #{f[0]}", Thor::Shell::Color::RED)
                raise Parallel::Kill
              end
            else
              # blob

              if @files.download_file_s3(f[0], relative_path, project_home, commit_sha1=current_commit)
                f
                successful_changes << relative_path
              else
                is_success =false
                log_message("Could not download file: #{f[0]}", Thor::Shell::Color::RED)
                raise Parallel::Kill

              end
            end
          end
        rescue Interrupt
          is_success =false
          log_message("Couldn't download, Rolling Back all changes.", Thor::Shell::Color::RED)

          @files.revoke_download([], response["result"]["tree"])
          exit(1)
        end


      end
      successful_changes = response["result"]["tree"]
      if !successful_changes.nil? and is_success
        Project.verify_cnvrgignore_exist(project_name,remote)
        log_message("Done.\nDownloaded  #{successful_changes.size}/#{response["result"]["tree"].size} files", Thor::Shell::Color::GREEN)
      else
        log_message("Couldn't download some files", Thor::Shell::Color::RED)

      end

    else

      log_message("Error: Couldn't create directory: #{project_name}", Thor::Shell::Color::RED)
      exit(1)
    end
  rescue SignalException
    say "\nAborting"
    exit(1)
  end

end

#clone_data(dataset_url) ⇒ Object



800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
# File 'lib/cnvrg/cli.rb', line 800

def clone_data(dataset_url)
  begin
    verify_logged_in(false)
    log_start(__method__, args, options)
    url_parts = dataset_url.split("/")
    project_index = Cnvrg::Helpers.look_for_in_path(dataset_url, "datasets")
    slug = url_parts[project_index+1]
    owner = url_parts[project_index-1]
    response = Cnvrg::API.request("users/#{owner}/datasets/#{slug}/clone", 'GET')

    Cnvrg::CLI.is_response_success(response)
    dataset_name = response["result"]["name"]

    if (Dir.exists? dataset_name)
      log_messgae("Error: Conflict with dir #{dataset_name}", Thor::Shell::Color::RED)
      if no? "Sync to repository anyway? (current data might lost)", Thor::Shell::Color::YELLOW
        log_message("Remove dir in order to clone #{dataset_name}", Thor::Shell::Color::RED)
        exit(1)
      end

    end
    if Dataset.clone(owner, dataset_name, slug)
      log_message("Cloning #{dataset_name}", Thor::Shell::Color::BLUE)

      commit_to_clone = options["commit"] || nil
      working_dir = "#{Dir.pwd}/#{dataset_name}"
      @dataset = Dataset.new(working_dir)
      @dataset.generate_idx()


      download_res = download_data(false, false, path = working_dir, in_dir=false)
      if !download_res
        exit(1)
      end


      check = Helpers.checkmark
      log_message("#{check} Clone finished successfully", Thor::Shell::Color::GREEN)

    else
      @dataset.revert(working_dir) unless @dataset.nil?
      log_message("Error creating dataset, please contact support.", Thor::Shell::Color::RED)
      exit(0)
    end
  rescue => e
    log_error(e)
  rescue SignalException

    say "\nAborting"
    exit(1)
  end
end

#commit_imageObject



4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
# File 'lib/cnvrg/cli.rb', line 4041

def commit_image
  verify_logged_in(true)
  log_start(__method__, args, options)

  begin
    image = is_project_with_docker(Dir.pwd)
    if image and image.is_docker
      container= image.get_container
      if !container

        say "Couldn't create container with image #{image.image_name}:#{image.image_tag}", Thor::Shell::Color::RED
        exit(1)
      end
    else
      say "Project is not configured with any image", Thor::Shell::Color::RED
      exit(1)

    end
    project_home = get_project_home
    @project = Project.new(project_home)
    last_local_commit = @project.last_local_commit
    say "Commiting container into image", Thor::Shell::Color::BLUE
    new_image_name = "#{@project.slug}#{last_local_commit}:latest"
    image.update_image(new_image_name, container)
    new_image = container.commit('repo' => "#{@project.slug}#{last_local_commit}", 'tag' => "lastest")
    checks = Helpers.checkmark()
    say "#{checks} Done, image was updated", Thor::Shell::Color::GREEN
    log_end(0)
    return new_image.id
  rescue => e
    log_end(-1, e.message)
    say "\nError occurred, aborting"
    exit(1)
  rescue SignalException
    log_end(-1)
    say "\nAborting"
    exit(1)
  end
end

#config_flask_remote(image_name, port = 80) ⇒ Object



4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
# File 'lib/cnvrg/cli.rb', line 4412

def config_flask_remote(image_name, port=80)
  local_images = Docker::Image.all

  docker_image_local = local_images.map { |x| x.info["RepoTags"] }.flatten.select { |y| y.eql? "#{image_name}:latest" }.flatten
  if docker_image_local.empty?
    say "no image"
    exit(1)
  end

  begin
     = options["login"]
    image_settings = {
        'Image' => "#{image_name}:latest",
        'User' => 'ds',
        'Cmd' => '/usr/local/cnvrg/start_super.sh',
        'WorkingDir' => '/home/ds/app',
        'ExposedPorts' => {
            '80/tcp' => {},
        },
        'HostConfig' => {
            'PortBindings' => {
                '80/tcp' => [
                    {'HostPort' => "#{port}", 'HostIp' => 'localhost'}
                ],
            },
        },
    }
    container = Docker::Container.create(image_settings)
    container.start()
    command = ["/bin/bash", "-lc", "sudo echo -e \"#{}\" >/home/ds/.netrc"]
    container.exec(command, tty: true)
    command = ["/bin/bash", "-lc", "sudo chown -R ds:ds /home/ds/.netrc"]
    container.exec(command, tty: true)
    command = ["/bin/bash", "-lc", "sudo chmod 0600 /home/ds/.netrc"]
    container.exec(command, tty: true)
    say "#{container.id}:#{port}"
  rescue => e
    pus e
    if e.message.include? "is not running"
      return "port is taken"
    end
    puts "error"
    if container
      container.kill()
    end
    return false
  end
end

#config_flask_remote_gpu(image_name, port = 80) ⇒ Object



4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
# File 'lib/cnvrg/cli.rb', line 4464

def config_flask_remote_gpu(image_name, port=80)
  local_images = Docker::Image.all

  docker_image_local = local_images.map { |x| x.info["RepoTags"] }.flatten.select { |y| y.eql? "#{image_name}:latest" }.flatten
  if docker_image_local.empty?
    say "no image"
    exit(1)
  end

  begin
     = options["login"]
    container_id = `nvidia-docker run -itd -p 80:80 -w /home/ds/app #{image_name}:latest /usr/local/cnvrg/start_super.sh`
    container_id = container_id.gsub("\n", "")
    container = Docker::Container.get(container_id)
    command = ["/bin/bash", "-lc", "sudo echo -e \"#{}\" >/home/ds/.netrc"]
    container.exec(command, tty: true)
    command = ["/bin/bash", "-lc", "sudo chown -R ds:ds /home/ds/.netrc"]
    container.exec(command, tty: true)
    command = ["/bin/bash", "-lc", "sudo chmod 0600 /home/ds/.netrc"]
    container.exec(command, tty: true)
    say "#{container.id}:#{port}"
  rescue => e
    puts e
    if e.message.include? "is not running"
      return "port is taken"
    end
    puts "error"
    if container
      container.kill()
    end
    return false
  end
end

#config_netrc(container) ⇒ Object



4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
# File 'lib/cnvrg/cli.rb', line 4330

def config_netrc(container)

   = options["login"]

  container = Docker::Container.get(container)
  command = ["/bin/bash", "-lc", "sudo echo -e \"#{}\" >/home/ds/.netrc"]
  container.exec(command, tty: true)
  command = ["/bin/bash", "-lc", "sudo chown -R ds:ds /home/ds/.netrc"]
  container.exec(command, tty: true)
  command = ["/bin/bash", "-lc", "sudo chmod 0600 /home/ds/.netrc"]
  container.exec(command, tty: true)
  say "OK"

end

#config_remote(image_name, port = 7654, tensport = 6006) ⇒ Object



4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
# File 'lib/cnvrg/cli.rb', line 4265

def config_remote(image_name, port=7654, tensport=6006)
  local_images = Docker::Image.all

  docker_image_local = local_images.map { |x| x.info["RepoTags"] }.flatten.select { |y| y.eql? "#{image_name}:latest" }.flatten
  if docker_image_local.empty?
    say "no image"
    exit(1)
  end

  begin
     = options["login"]
    app_dir = options["app_dir"]
    cmd= options["cmd"]
    volume_from = options["volume"]

    image_settings = {
        'Image' => "#{image_name}:latest",

        'Cmd' => cmd,
        'WorkingDir' => app_dir,
        'ExposedPorts' => {
            '8888/tcp' => {},
        },
        'HostConfig' => {
            'Binds' => ["/var/run/docker.sock:/var/run/docker.sock", "/usr/bin/docker:/usr/bin/docker"],
            'PortBindings' => {
                '8888/tcp' => [
                    {'HostPort' => "#{port}", 'HostIp' => 'localhost'}
                ],
                '6006/tcp' => [
                    {'HostPort' => "#{tensport}", 'HostIp' => 'localhost'}
                ],
            },
        },
    }
    container = Docker::Container.create(image_settings)
    container.start()
    command = ["/bin/bash", "-lc", "sudo echo -e \"#{}\" >/home/ds/.netrc"]
    container.exec(command, tty: true)
    # command = ["/bin/bash", "-lc", "mkdir /home/ds/.cnvrg"]
    # container.exec(command, tty: true)
    # command = ["/bin/bash", "-lc", "mkdir /home/ds/.cnvrg/tmp"]
    # container.exec(command, tty: true)
    command = ["/bin/bash", "-lc", "sudo chown -R ds:ds /home/ds/.netrc"]
    container.exec(command, tty: true)
    command = ["/bin/bash", "-lc", "sudo chmod 0600 /home/ds/.netrc"]
    container.exec(command, tty: true)
    say "#{container.id}:#{port}##{tensport}"
  rescue => e
    puts e
    if e.message.include? "is not running"
      return config_remote(image_name, port-1, tensport-1)
    end

    if container
      container.kill()
    end
    return false
  end
end

#config_remote_gpu(image_name, port = 7654, tensport = 6006) ⇒ Object



4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
# File 'lib/cnvrg/cli.rb', line 4351

def config_remote_gpu(image_name, port=7654, tensport=6006)
  local_images = Docker::Image.all

  docker_image_local = local_images.map { |x| x.info["RepoTags"] }.flatten.select { |y| y.eql? "#{image_name}:latest" }.flatten
  if docker_image_local.empty?
    say "no image"
    exit(1)
  end

  begin
     = options["login"]
    app_dir = options["app_dir"]
    cmd= options["cmd"]

    # image_settings = {
    #     'Image' => "#{image_name}:latest",
    #     'User' => 'ds',
    #     'Cmd' => cmd,
    #     'WorkingDir' => app_dir,
    #     'ExposedPorts' => {
    #         '8888/tcp' => {},
    #     },
    #     'HostConfig' => {
    #         'PortBindings' => {
    #             '8888/tcp' => [
    #                 {'HostPort' => "#{port}", 'HostIp' => 'localhost'}
    #             ],
    #             '6006/tcp' => [
    #                 {'HostPort' => "6006", 'HostIp' => 'localhost'}
    #             ],
    #         },
    #     },
    # }

    container_id = `nvidia-docker run -itd -p #{port}:8888 -p #{tensport}:6006 -w #{app_dir} -v /usr/bin/nvidia-smi:/usr/bin/nvidia-smi  -v /var/run/docker.sock:/var/run/docker.sock -v /usr/bin/docker:/usr/bin/docker #{image_name}:latest #{cmd} `
    container_id = container_id.gsub("\n", "")
    container = Docker::Container.get(container_id)
    # container.start()
    command = ["/bin/bash", "-lc", "sudo echo -e \"#{}\" >/home/ds/.netrc"]
    container.exec(command, tty: true)
    command = ["/bin/bash", "-lc", "sudo chown -R ds:ds /home/ds/.netrc"]
    container.exec(command, tty: true)
    command = ["/bin/bash", "-lc", "sudo chmod 0600 /home/ds/.netrc"]
    container.exec(command, tty: true)
    say "#{container.id}:#{port}##{tensport}"
  rescue => e
    if e.message.include? "is not running"
      puts "running asgain with: #{port-1} #{tensport-1}"
      return config_remote_gpu(image_name, port-1, tensport-1)
    end

    if container
      container.kill()
    end
    return false
  end
end

#create_volumeObject



1396
1397
1398
1399
1400
1401
1402
1403
# File 'lib/cnvrg/cli.rb', line 1396

def create_volume
  verify_logged_in(false)
  log_start(__method__, args, options)
  dataset_dir = is_cnvrg_dir(Dir.pwd)
  @dataset = Dataset.new(dataset_dir)
  @dataset.create_volume()

end

#data_init_container(owner, dataset_slug, dataset_name) ⇒ Object



903
904
905
906
907
908
909
910
911
912
913
# File 'lib/cnvrg/cli.rb', line 903

def data_init_container(owner, dataset_slug, dataset_name)

  if Dataset.init_container(owner, dataset_slug, dataset_name)

    say "init finished successfully", Thor::Shell::Color::GREEN

  else
    say "error creating dataset, please contact support.", Thor::Shell::Color::RED
    exit(0)
  end
end

#data_jump(*commit_sha1) ⇒ Object



2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
# File 'lib/cnvrg/cli.rb', line 2275

def data_jump(*commit_sha1)
  begin
    verify_logged_in()
    log_start(__method__, args, options)
    dataset_dir = is_cnvrg_dir(Dir.pwd)
    @dataset = Dataset.new(dataset_dir)

    @files = Cnvrg::Datafiles.new(@dataset.owner, @dataset.slug)
    if commit_sha1.nil? or commit_sha1.empty?
      commit_sha1 = @dataset.last_local_commit
    end
    response = @dataset.compare_commits(commit_sha1)
    successful_changes = []
    if !response["result"]["status"].nil?
      idx = {commit: response["result"]["commit"], tree: response["result"]["tree"]}
      File.open(dataset_dir + "/.cnvrg/idx.yml", "w+") { |f| f.write idx.to_yaml }
      status = response["result"]["status"]
      (status["delete"]).each do |f|
        relative_path = f[0].gsub(/^#{@dataset.local_path}/, "")
        FileUtils.rm_rf(relative_path)
      end
      # current_tree = Dir.entries(".").reject { |file| file.start_with? '.' }
      (status["dirs"]).each do |f|
        relative_path = f[0].gsub(/^#{@dataset.local_path}/, "")
        # dir
        if @files.download_dir(dataset_dir, relative_path)
          # current_tree.delete(relative_path[0, relative_path.size-1])
          successful_changes << relative_path
        end
      end
      (status["download"]).each do |f|
        relative_path = f["name"].gsub(/^#{@dataset.local_path}/, "")
        # dir
        if @files.download_file_s3(f["name"], relative_path, dataset_dir, f["sha1"])
          successful_changes << relative_path
        end
      end


      log_message("Done. Jumped to #{commit_sha1} completed successfully", Thor::Shell::Color::GREEN)
    end
  rescue => e
    log_message("Error occurred, Aborting", Thor::Shell::Color::RED)
    log_error(e)

  rescue SignalException
    exit(1)
  end
end

#deploy(file_to_run, function) ⇒ Object



3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
# File 'lib/cnvrg/cli.rb', line 3084

def deploy(file_to_run, function)
  verify_logged_in(true)
  log_start(__method__, args, options)
  working_dir = is_cnvrg_dir
  begin
    instances = {"small" => options["small"], "medium" => options["medium"], "large" => options["large"],
                 "gpu" => options["gpu"], "gpuxl" => options["gpuxl"], "gpuxxl" => options["gpuxxl"]}
    instance_type = get_instance_type(instances)

    schedule = options["schedule"] || ""


    if !schedule.nil? and !schedule.empty?

      local_timestamp = get_schedule_date

    end
    project = Project.new(working_dir)
    commit_to_run = options["commit"] || nil

    workers = options["workers"] || nil
    begin
      num_workers = workers.to_i
    rescue
      log_message("Number of workers should be a number between 1 to 10", Thor::Shell::Color::RED)
      exit(1)
    end
    file_as_input = options["file_as_input"] || false


    image = is_project_with_docker(working_dir)
    if !image or !image.is_docker
      # say "Couldn't find image related to project", Thor::Shell::Color::RED
      # default = yes? "use cnvrg default image?", Thor::Shell::Color::YELLOW
      # if default
      image = Images.new(working_dir, "cnvrg")
      image_slug = image.image_slug
      # else
      #   exit(0)
      # end
    else
      image_slug = image.image_slug
    end


    invoke :sync, [false], []

    res = project.deploy(file_to_run, function, nil, commit_to_run, instance_type, image_slug, schedule, local_timestamp, num_workers, file_as_input)

    if Cnvrg::CLI.is_response_success(res)

      # if res["result"]["machine"] == -1
      #   say "There are no available machines", Thor::Shell::Color::BLUE
      #   create = yes? "create new machine?", Thor::Shell::Color::YELLOW
      #   if create
      #     res = Cnvrg::API.request("users/#{image.owner}/machines/list", 'GET')
      #     if Cnvrg::CLI.is_response_success(res)
      #       instance_type = machine_options(res["result"]["aws_options"])
      #       if @image.new_machine(instance_type)
      #         say "Running remote experiment", Thor::Shell::Color::BLUE
      #
      #         # res = image.exec_remote(exec_args, exec_options, project.last_local_commit)
      #         # if Cnvrg::CLI.is_response_success(res)
      #
      #           check = Helpers.checkmark()
      #           say "#{check} Finished successfuly", Thor::Shell::Color::GREEN
      #           exit(0)
      #         # end
      #       end
      #     else
      #       say "No machines are avilable", Thor::Shell::Color::RED
      #       exit(0)
      #     end
      #
      #
      #   else
      #     say "Can't execute command on remote machine with local image", Thor::Shell::Color::RED
      #     exit(1)
      #
      #   end
      # else
      check = Helpers.checkmark()
      log_message("#{check} Deployment process is on: #{Cnvrg::Helpers.remote_url}/#{project.owner}/projects/#{project.slug}/deploys/show/#{res["result"]["deploy_slug"]}", Thor::Shell::Color::GREEN)

      exit(0)
      # end
    end
  rescue => e
    log_message("Error occurred, Aborting", Thor::Shell::Color::RED)
    log_error(e)


  rescue SignalException
    exit_status = -1
    end_commit = project.last_local_commit

    res = @exp.end(log, exit_status, end_commit, "", "")
    say "\nAborting"

    exit(1)
  end
end

#download(sync = false, ignore_list = "") ⇒ Object



1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
# File 'lib/cnvrg/cli.rb', line 1992

def download(sync=false, ignore_list="")
  begin
    verify_logged_in(true)
    log_start(__method__, args, options)
    project_home = get_project_home
    @project = Project.new(project_home)
    @files = Cnvrg::Files.new(@project.owner, @project.slug)
    ignore = options[:ignore] || ""
    if ignore.nil? or ignore.empty?
      ignore = ignore_list
    end
    data_ignore = data_dir_include()
    if !data_ignore.nil?
      if ignore.nil? or ignore.empty?
        ignore = data_ignore
      else
        ignore ="#{ignore},#{data_ignore}"
      end
    end
    if !@project.update_ignore_list(ignore)
      log_message("Couldn't append new ignore files to .cnvrgignore", Thor::Shell::Color::YELLOW)
    end
    new_branch = options["new_branch"] || false
    res = @project.compare_idx(new_branch)["result"]

    result = res["tree"]

    commit = res["commit"]
    if result["updated_on_server"].empty? and result["conflicts"].empty? and result["deleted"].empty?
      log_message("Project is up to date", Thor::Shell::Color::GREEN, ((options["sync"] or sync) ? false : true))
      return true
    end
    # if result["added"].any? {|x| x.include? ".conflict"} or !result["conflicts"].empty?
    #   all = result["added"].select {|x| x.include? ".conflict"} +result["conflicts"].flatten
    #   if all.size == 1
    #     num = "1 conflict"
    #   else
    #     num =  "#{result["conflicts"].size} conflicts"
    #   end
    #   say "Project contains #{num}:", Thor::Shell::Color::RED
    #   say "#{all.join("\n")}"
    #   say "Please fix them, and retry", Thor::Shell::Color::RED
    #   exit(1)
    #   end
    update_count = 0
    update_total = result["updated_on_server"].size + result["conflicts"].size + result["deleted"].size


    successful_changes = []
    if update_total ==1
      log_message("Downloading #{update_total} file", Thor::Shell::Color::BLUE, !options["sync"])
    elsif update_total == 0
      log_message("Project is up to date", Thor::Shell::Color::GREEN, !options["sync"])
      return true
    elsif options["verbose"]
      log_message("Downloading #{update_total} files", Thor::Shell::Color::BLUE)
    else
      log_message("Syncing files", Thor::Shell::Color::BLUE, !options["sync"])

    end
    parallel_options = {
        :progress => {
            :title => "Download Progress",
            :progress_mark => '=',
            :format => "%b>>%i| %p%% %t",
            :starting_at => 0,
            :total => result["updated_on_server"].size,
            :autofinish => true
        },
        in_processes: ParallelProcesses,
        in_thread: ParallelThreads
    }
    if !result["conflicts"].empty?
      begin


        conflicts_result = Parallel.map(result["conflicts"], in_processes: ParallelProcesses, in_thread: ParallelThreads) do |f|

          relative_path = f.gsub(/^#{@project.local_path}/, "")
          log_message("downloading: #{f}.conflict", Thor::Shell::Color::BLUE, options["verbose"])

          if @files.download_file_s3(f, relative_path, project_home, commit_sha1=nil, conflict=true)
            f
          else
            log_message("Couldn't download: #{f}", Thor::Shell::Color::RED)
            raise Parallel::Kill

          end
        end
      rescue Interrupt

        log_message("Couldn't download, Rolling Back all changes.", Thor::Shell::Color::RED)

        @files.revoke_download(result["conflicts"], [])
        exit(1)
      end
    end


    successful_changes += conflicts_result.to_a
    if !result["updated_on_server"].empty?
      begin
        updated_on_server_result = Parallel.map(result["updated_on_server"], parallel_options) do |f|

          relative_path = f.gsub(/^#{@project.local_path}/, "")
          if f.end_with? "/"
            # dir
            log_message("downloading dir: #{f}", Thor::Shell::Color::BLUE, options["verbose"])

            if @files.download_dir(f, relative_path, project_home)
              f
            else
              log_message("Couldn't create directory: #{f}", Thor::Shell::Color::RED)
              raise Parallel::Kill


            end

          else
            # blob
            log_message("downloading file: #{f}", Thor::Shell::Color::BLUE, options["verbose"])

            if @files.download_file_s3(f, relative_path, project_home)
              f
            else


              log_message("Couldn't download: #{f}", Thor::Shell::Color::RED)
              raise Parallel::Kill


            end
          end


        end
        successful_changes += updated_on_server_result.to_a
      rescue Interrupt
        log_message("Couldn't download, Rolling Back all changes.", Thor::Shell::Color::RED)

        @files.revoke_download(result["conflicts"], result["updated_on_server"])
        exit(1)

      end
    end

    deleted = result["deleted"].to_a
    delete_res = @files.delete_commit_files_local(deleted)
    if !delete_res
      log_message("Couldn't delete #{deleted.join(" ")}", Thor::Shell::Color::RED)
      log_message("Couldn't download, Rolling Back all changes.", Thor::Shell::Color::RED)

      @files.revoke_download(result["conflicts"], result["updated_on_server"])
      exit(1)

    end
    successful_changes += deleted


    successful_changes = successful_changes.select { |x| not x.nil? }

    if update_total == successful_changes.size
      # update idx with latest commit
      @project.update_idx_with_commit!(commit)
      check = Helpers.checkmark()

      if options["verbose"]
        log_message("#{check} Done, Downloaded:", Thor::Shell::Color::GREEN)
        log_message(successful_changes.join("\n"), Thor::Shell::Color::GREEN)
        log_message("Total of #{successful_changes.size} / #{update_total} files.", Thor::Shell::Color::GREEN)
      else
        log_message("#{check} Downloaded changes successfully", Thor::Shell::Color::GREEN, ((sync or options["sync"]) ? false : true))
      end


    end
  rescue => e

    log_message("Error occurred, \nAborting", Thor::Shell::Color::BLUE)
    log_error(e)
    if successful_changes.nil?
      exit(1)
    end
    begin
      @files.revoke_download(result["conflicts"], result["updated_on_server"])
    end
    exit(1)
  rescue SignalException
    say "\nAborting", Thor::Shell::Color::BLUE
    if successful_changes.nil?
      exit(1)
    end
    begin
      @files.revoke_download(result["conflicts"], result["updated_on_server"])
    end
    exit(1)
  end
end

#download_built_image(image_name, image_slug) ⇒ Object



4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
# File 'lib/cnvrg/cli.rb', line 4525

def download_built_image(image_name, image_slug)
  begin
    verify_logged_in(false)
    log_start(__method__, args, options)
    owner = Cnvrg::CLI.get_owner()
    path = File.expand_path('~')+"/.cnvrg/tmp/#{image_name}.tar.gz"
    @files = Cnvrg::Files.new(owner, "")

    log_message("Downloading image file", Thor::Shell::Color::BLUE)
    begin
      if @files.download_image(path, image_slug, owner)
        gzipRes = system("gunzip -f #{path}")
        if !gzipRes

          log_message("Couldn't create tar file from image", Thor::Shell::Color::RED)
          exit(1)
        else
          path = path.gsub(".gz", "")
          return path
        end

      else
        log_message("Couldn't download image #{image_name}", Thor::Shell::Color::RED)
        return false
      end
    rescue Interrupt
      say "The user has exited to process, aborting", Thor::Shell::Color::BLUE
      exit(1)
    end
  rescue SignalException
    say "\nAborting"
    exit(1)
  end
end

#download_cnvrg_image(image_name, secret) ⇒ Object



4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
# File 'lib/cnvrg/cli.rb', line 4609

def download_cnvrg_image(image_name, secret)
  verify_logged_in(false)

  begin
    @files = Cnvrg::Files.new("", "")

    say "Downloading image file", Thor::Shell::Color::BLUE
    begin
      if @files.download_cnvrg_image(image_name, secret)

        say "Successfully downloaded image #{image_name}", Thor::Shell::Color::GREEN

      else
        say "Couldn't download image #{image_name}", Thor::Shell::Color::RED
        return false
      end
    rescue Interrupt
      say "The user has exited to process, aborting", Thor::Shell::Color::BLUE
      exit(1)
    end
  rescue SignalException
    say "\nAborting"
    exit(1)
  end
end

#download_data(verbose, sync, path = Dir.pwd, in_dir = true) ⇒ Object



919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
# File 'lib/cnvrg/cli.rb', line 919

def download_data(verbose, sync, path=Dir.pwd, in_dir=true)
  begin
    verify_logged_in(in_dir)
    log_start(__method__, args, options)
    if path.nil? or path.empty?
      path = Dir.pwd
    end
    dataset_dir = is_cnvrg_dir(path)
    @dataset = Dataset.new(dataset_dir)

    @files = Cnvrg::Datafiles.new(@dataset.owner, @dataset.slug)
    new_branch = options["new_branch"] || false

    res = @dataset.compare_idx(new_branch)["result"]

    result = res["tree"]

    commit = res["commit"]
    if result["updated_on_server"].empty? and result["conflicts"].empty? and result["deleted"].empty?
      log_message("Project is up to date", Thor::Shell::Color::GREEN, ((options["sync"] or sync)) ? false : true)
      return true
    end
    log_message("Downloading data", Thor::Shell::Color::BLUE)

    result = @dataset.downlowd_updated_data(@dataset.last_local_commit)

    delete = result["result"]["delete"]
    commits = result["result"]["commits"]
    updated_idx = result["result"]["idx"]
    parallel_options = {
        :progress => {
            :title => "Download Progress",
            :progress_mark => '=',
            :format => "%b>>%i| %p%% %t",
            :starting_at => 0,
            :total => commits.size,
            :autofinish => true
        },
        in_processes: ParallelProcesses,
        in_thread: ParallelThreads
    }

    begin
      tar_files = []
      download_result = Parallel.map(commits, parallel_options) do |c|

        file_name = @files.download_data_file(c, dataset_dir)

        if file_name.eql? false or file_name.nil?
          count = 0
          success_download = false
          while count < 3 and !success_download
            log_message("Couldn't download data files, retrying.. ", Thor::Shell::Color::BLUE)

            file_name = @files.download_data_file(c, dataset_dir)
            success_download = (file_name.eql? false or file_name.nil?)
            count +=1

          end
          if count > 3 or !success_download
            log_message("Couldn't download data files,revoking", Thor::Shell::Color::RED)

            raise Parallel::Kill
          end
        end
        file_path = "#{dataset_dir}/#{file_name}"
        tar_files << file_path
        success = extarct_tar(file_path, dataset_dir)
        if !success
          log_message("Couldn't extract data files,revoking", Thor::Shell::Color::RED)

          raise Parallel::Kill
        end

        FileUtils.rm_rf([file_path])

      end
    rescue Interrupt
      @files.revoke_download(tar_files, updated_idx[:tree].keys)
      return false
    end


    to_delete = []
    delete.each do |d|
      to_delete << "#{dataset_dir}/#{d}"
    end
    FileUtils.rm_rf(to_delete)

    @dataset.update_idx(updated_idx)


    check = Helpers.checkmark()
    log_message("#{check} Downloaded changes successfully", Thor::Shell::Color::GREEN)
    return true


  end
rescue => e
  log_message("Error occurd, \nAborting", Thor::Shell::Color::BLUE)
  log_error(e)
  @files.revoke_download(tar_files, updated_idx[:tree].keys)

  exit(1)
rescue SignalException
  say "\nAborting", Thor::Shell::Color::BLUE
  exit(1)
end

#download_image(image_name, image_slug) ⇒ Object



4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
# File 'lib/cnvrg/cli.rb', line 4562

def download_image(image_name, image_slug)
  begin
    verify_logged_in(false)
    log_start(__method__, args, options)
    owner = Cnvrg::CLI.get_owner()
    path = File.expand_path('~')+"/.cnvrg/tmp/#{image_name}.zip"
    @files = Cnvrg::Files.new(owner, "")

    say "Downloading image file", Thor::Shell::Color::BLUE
    begin
      if @files.download_image(path, image_slug, owner)

        dir_path = File.expand_path('~')+"/.cnvrg/tmp/#{image_name}"
        FileUtils.rm_rf([dir_path])

        Zip::File.open(path) do |zip_file|
          zip_file.each do |entry|

            f_path=File.join(dir_path, entry.name)
            FileUtils.mkdir_p(File.dirname(f_path))
            zip_file.extract(entry, f_path)
          end
        end

        return dir_path

      else
        say "Couldn't download image #{image_name}", Thor::Shell::Color::RED
        log_end(1, "can't download image")
        return false
      end
    rescue Interrupt
      log_end(-1)
      say "The user has exited to process, aborting", Thor::Shell::Color::BLUE
      exit(1)
    end
  rescue SignalException
    log_end(-1)
    say "\nAborting"
    exit(1)
  ensure
    if !path.nil?
      FileUtils.rm(path)
    end
  end
end

#exec(*cmd) ⇒ Object



2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
# File 'lib/cnvrg/cli.rb', line 2443

def exec(*cmd)

  log = []
  cpu_average =0
  memory_average = 0
  verify_logged_in(true)
  log_start(__method__, args, options)
  working_dir = is_cnvrg_dir
  script_path = get_cmd_path_in_dir(working_dir, Dir.pwd)


  sync_before = options["sync_before"]
  sync_after = options["sync_after"]
  print_log = options["log"]
  title = options["title"]
  commit = options["commit"] || nil
  image = options["image"] || nil
  indocker = options["indocker"] || false
  ignore = options[:ignore] || ""
  force = options[:force]


  email_notification = options["email_notification"]
  upload_output = options["upload_output"]
  upload_output = "1m" if upload_output.nil? or upload_output.empty?
  time_to_upload = calc_output_time(upload_output)
  project_home = get_project_home
  @project = Project.new(project_home)

  is_new_branch = @project.compare_commit(commit)
  begin
    if !commit.nil? and !commit.empty?
      invoke :jump, [commit], []
    else
      if sync_before
        # Sync before run

        invoke :sync, [false], :new_branch => is_new_branch, :ignore => ignore, :force => force
      end
    end
    #set image for the project
    if !image.nil? and !image.empty?
      invoke :set_image, [image]
    end
    if !indocker
      image_proj = is_project_with_docker(working_dir)


      if image_proj and image_proj.is_docker
        container= image_proj.get_container
        if !container
          log_message("Couldn't create container with image #{image_proj.image_name}:#{image_proj.image_tag}", Thor::Shell::Color::RED)
          exit(1)
        end


        exec_args = args.flatten.join(" ")
        options_hash = Hash[options]
        options_hash.except!("image", "indocker")
        exec_options = options_hash.map { |x| "--#{x[0]}=#{x[1]}" }.flatten.join(" ")
        command_to_run = copy_args.join(" ")
        command = ["/bin/bash", "-lc", "cnvrg exec --indocker #{exec_options} #{command_to_run} #{exec_args}"]
        puts container.exec(command, tty: true)
        container.stop()
        exit(0)
      end
    end
    remote = options["remote"]
    if remote
      docker_id = `cat /etc/hostname`
      docker_id = docker_id.strip()
    end
    is_on_gpu = options["gpu"]
    start_commit = @project.last_local_commit
    cmd = cmd.join("\s")

    @exp = Experiment.new(@project.owner, @project.slug)

    platform = RUBY_PLATFORM
    machine_name = Socket.gethostname
    begin
      machine_activity = @exp.get_machine_activity(working_dir)
      @exp.start(cmd, platform, machine_name, start_commit, title, email_notification, machine_activity, script_path)
      log_message("Experiment's live results: #{Cnvrg::Helpers.remote_url}/#{@project.owner}/projects/#{@project.slug}/experiments/#{@exp.slug}", Thor::Shell::Color::GREEN)
      log_message("Running: #{cmd}\n", Thor::Shell::Color::BLUE)
      unless @exp.slug.nil?
        real = Time.now
        exp_success = true
        memory_total = []
        cpu_total = []
        start_loop = Time.now
        stdout, stderr = '', ''
        begin
          PTY.spawn(cmd) do |stdout, stdin, pid, stderr|
            begin
              stdout.each do |line|
                cur_time = Time.now
                real_time= Time.now-real

                cur_log = {time: cur_time,
                           message: line,
                           type: "stdout",
                           real: real_time

                }


                if print_log
                  puts cur_log
                end
                log << cur_log

                begin
                  if time_to_upload !=0
                    if time_to_upload <= Time.now - start_loop
                      if remote
                        stats = usage_metrics_in_docker(docker_id)
                        cpu = stats[0]
                        memory = stats[1]
                        if is_on_gpu
                          gpu_stats = gpu_util
                          gpu_utilization = gpu_stats[0]
                          gpu_memory_util = gpu_stats[1]
                        end
                      else
                        memory = memory_usage()
                        cpu = cpu_usage()
                      end
                      log.each do |l|
                        if remote and is_on_gpu
                          l.merge!(cpu: cpu, memory: memory, gpu_util: gpu_utilization, gpu_memory_util: gpu_memory_util)
                        else
                          l.merge!(cpu: cpu, memory: memory)
                        end
                      end


                      #upload current log
                      # cpu_average = cpu_total.inject(0) { |sum, el| sum + el }.to_f / cpu_total.size
                      # memory_average = memory_total.inject(0) { |sum, el| sum + el }.to_f / memory_total.size

                      @exp.upload_temp_log(log, cpu_average, memory_average)
                      log = []
                      start_loop = Time.now
                    end

                  end
                rescue => e

                  log_message("Failed to upload ongoing results, continuing with experiment", Thor::Shell::Color::YELLOW)
                  log_error(e)
                end

              end


              if stderr

                stderr.each do |err|

                  log << {time: Time.now, message: err, type: "stderr"}
                end
              end

            rescue Errno::EIO => e
              log_error(e)

                # break
            rescue Errno::ENOENT => e

              exp_success = false

              log_message("command \"#{cmd}\" couldn't be executed, verify command is valid", Thor::Shell::Color::RED)
              log_error(e)
            rescue Open4::ChildExited
              exp_success = false
              log_message("The process exited!", Thor::Shell::Color::RED)
            rescue => e
              res = @exp.end(log, 1, start_commit, cpu_average, memory_average)

              log_message("Error occurred,aborting", Thor::Shell::Color::RED)
              log_error(e)
              exit(0)
            end
            ::Process.wait pid
          end

            cpu_average = cpu_total.inject(0) { |sum, el| sum + el }.to_f / cpu_total.size
            memory_average = memory_total.inject(0) { |sum, el| sum + el }.to_f / memory_total.size
            exit_status = $?.exitstatus
            if $?.exitstatus != 0
              exp_success = false
            end
            if !exp_success
              if !Cnvrg::Helpers.internet_connection?
                wait_offline = agree "Seems like you're offline, wait until you're back online?", Thor::Shell::Color::YELLOW
                if wait_offline
                  log_message("Waiting until your'e online..", Thor::Shell::Color::BLUE)
                  while !Cnvrg::Helpers.internet_connection?
                  end
                  exit_status = 0
                else
                  log_message("Experiment has failed, your'e computer is offline", Thor::Shell::Color::RED)
                  exit(0)
                end
              else

                end_commit = @project.last_local_commit
                res = @exp.end(log, exit_status, end_commit, cpu_average, memory_average)
                log_message("Experiment has failed, look at the log for more details or run cnvrg exec --log", Thor::Shell::Color::RED)
                exit(0)
              end

            end
            if sync_after
              # Sync after run


              download(sync=true, ignore_list=ignore)
              upload(link=false, sync=true, direct=false, ignore_list=ignore)

            end
            end_commit = @project.last_local_commit

            res = @exp.end(log, exit_status, end_commit, cpu_average, memory_average)
            check = Helpers.checkmark()
            log_message("#{check} Done. Experiment's results were updated!", Thor::Shell::Color::GREEN)
        rescue => e
          if container
            container.stop()
          end
          log_message("Couldn't run #{cmd}, check your input parameters", Thor::Shell::Color::RED)
          if @exp
            cur_time = Time.now
            real_time= Time.now-real
            cur_log = {time: cur_time,
                       message: "Couldn't run #{cmd}, check your input parameters",
                       type: "stdout",
                       real: real_time

            }
            log << cur_log
            res = @exp.end(log, "-1", end_commit, cpu_average, memory_average)

          end
          log_error(e)

          exit(1)
        end


      end

    end
  rescue SignalException
    exit_status = -1
    end_commit = @project.last_local_commit

    res = @exp.end(log, exit_status, end_commit, cpu_average, memory_average)
    if container
      container.stop()
    end
    say "\nAborting"

    exit(1)
  end
end

#exec_container(container_id, *cmd) ⇒ Object



4227
4228
4229
4230
4231
4232
4233
4234
# File 'lib/cnvrg/cli.rb', line 4227

def exec_container(container_id, *cmd)
  container = Docker::Container.get(container_id)
  container.start()
  cnvrg_command = cmd.join(" ")
  command = ["/bin/bash", "-lc", "#{cnvrg_command}"]
  res = container.exec(command, tty: true, wait: 5400)[0]
  say res
end

#exec_docker(*cmd) ⇒ Object



2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
# File 'lib/cnvrg/cli.rb', line 2719

def exec_docker(*cmd)
  log = []
  cpu_average =0
  memory_average = 0
  verify_logged_in()
  log_start(__method__, args, options)
  project_home = "/home/ds/notebooks"
  @project = Project.new(project_home)
  sync_before = options["sync_before"]
  sync_after = options["sync_after"]
  print_log = options["log"]
  title = options["title"]
  email_notification = options["email_notification"]
  upload_output = options["upload_output"]
  time_to_upload = calc_output_time(upload_output)
  @image = is_project_with_docker(project_home)


  begin
    start_commit = @project.last_local_commit
    cmd = cmd.join("\s")

    log_message("Running: #{cmd}\n", Thor::Shell::Color::BLUE)

    @exp = Experiment.new(@project.owner, @project.slug)
    machine_activity = @exp.get_machine_activity(project_home)

    platform = RUBY_PLATFORM
    machine_name = Socket.gethostname
    begin

      @exp.start(cmd, platform, machine_name, start_commit, title, email_notification, machine_activity, Dir.pwd)
      unless @exp.slug.nil?
        real = Time.now
        exp_success = true
        memory_total = []
        cpu_total = []
        start_loop = Time.now
        begin
          PTY.spawn(cmd) do |stdout, stdin, pid, stderr|
            begin
              stdout.each do |line|
                cur_time = Time.now
                monitor = %x{ps aux|awk  '{print $2,$3,$4}'|grep #{pid} }
                monitor_by = monitor.split(" ")
                memory = monitor_by[2]
                cpu = monitor_by[1]
                memory_total << memory.to_f
                cpu_total << cpu.to_f
                real_time= Time.now-real

                cur_log = {time: cur_time,
                           message: line,
                           type: "stdout",
                           real: real_time}
                if print_log
                  puts cur_log
                end
                log << cur_log

                begin
                  if time_to_upload !=0
                    if time_to_upload <= Time.now - start_loop
                      #upload current log
                      cpu_average = cpu_total.inject(0) { |sum, el| sum + el }.to_f / cpu_total.size
                      memory_average = memory_total.inject(0) { |sum, el| sum + el }.to_f / memory_total.size

                      @exp.upload_temp_log(log, cpu_average, memory_average)
                      log = []
                      start_loop = Time.now
                    end

                  end
                rescue
                  log_message("Failed to upload ongoing results, continuing with experiment", Thor::Shell::Color::YELLOW)
                end

              end


              if stderr

                stderr.each do |err|

                  log << {time: Time.now, message: err, type: "stderr"}
                end
              end

            rescue Errno::EIO => e
              break
            rescue Errno::ENOENT

              exp_success = false

              log_message("command \"#{cmd}\" couldn't be executed, verify command is valid", Thor::Shell::Color::RED)
            rescue PTY::ChildExited
              exp_success = false
              log_message("The process exited!", Thor::Shell::Color::RED)
            rescue => e
              log_message("Error occurred, aborting", Thor::Shell::Color::RED)
              log_error(e)
              exit(0)
            end
            ::Process.wait pid
            cpu_average = cpu_total.inject(0) { |sum, el| sum + el }.to_f / cpu_total.size
            memory_average = memory_total.inject(0) { |sum, el| sum + el }.to_f / memory_total.size
            exit_status = $?.exitstatus
            if $?.exitstatus != 0
              exp_success = false
            end
            if !exp_success
              if !Cnvrg::Helpers.internet_connection?
                wait_offline = agree "Seems like you're offline, wait until your'e back online?", Thor::Shell::Color::YELLOW
                if wait_offline
                  log_message("Waiting until your'e online..", Thor::Shell::Color::BLUE)
                  while !Cnvrg::Helpers.internet_connection?
                  end
                  exit_status = 0
                else
                  log_message("Experiment has failed, your'e computer is offline", Thor::Shell::Color::RED)
                  exit(0)
                end
              else

                end_commit = @project.last_local_commit
                res = @exp.end(log, exit_status, end_commit, cpu_average, memory_average)
                @image.update_image_activity(@project.last_local_commit, @exp.slug)
                log_message("Experiment has failed, look at the log for more details or run cnvrg exec --log", Thor::Shell::Color::RED)
                exit(0)
              end

            end
            if sync_after
              log_message("Syncing project after running", Thor::Shell::Color::BLUE)
              # Sync after run
              download()
              upload()
              log_message("Done Syncing", Thor::Shell::Color::BLUE)
            end
            end_commit = @project.last_local_commit

            res = @exp.end(log, exit_status, end_commit, cpu_average, memory_average)
            @image.update_image_activity(@project.last_local_commit, @exp.slug)

            check = Helpers.checkmark()
            log_message("#{check} Done. Experiment's result: #{Cnvrg::Helpers.remote_url}/#{@project.owner}/projects/#{@project.slug}/experiments/#{@exp.slug}", Thor::Shell::Color::GREEN)
          end
        rescue => e
          log_message("Couldn't run #{cmd}, check your input parameters", Thor::Shell::Color::RED)
          log_error(e)
          exit(1)
        end


      end

    end
  rescue => e
    log_message("Error occurred, Aborting", Thor::Shell::Color::RED)
    log_error(e)

  rescue SignalException
    exit_status = -1
    end_commit = @project.last_local_commit
    if !@exp.nil?

      res = @exp.end(log, exit_status, end_commit, cpu_average, memory_average)
    end

    say "\nAborting"

    exit(1)
  end
end

#exec_remote(*cmd) ⇒ Object



2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
# File 'lib/cnvrg/cli.rb', line 2911

def exec_remote(*cmd)
  verify_logged_in(true)
  log_start(__method__, args, options)
  working_dir = is_cnvrg_dir
  path_to_cmd = get_cmd_path_in_dir(working_dir, Dir.pwd)

  begin
    grid = options["grid"] || nil
    data = options["data"] || nil
    data_commit = options["data_commit"] || nil
    sync_before = options["sync_before"]
    force = options["force"]

    instance_type = options["machine_type"] || nil
    schedule = options["schedule"] || ""
    if schedule.start_with? 'in'
      time = schedule.split(" ")

      local = Time.now.localtime
      if time[2].downcase().start_with? "min"
        new = local + (time[1].to_i * 60)
      elsif time[2].downcase().start_with? "hours"
        new = local + (time[1].to_i * 3600)
      elsif time[2].downcase().start_with? "days"
        new = local + (time[1].to_i * 3600 * 24)
      else
        log_message("Could not undersatnd when to schedule experiment", Thor::Shell::Color::RED)
        exit(1)
      end
      new_time = new.to_s
      new_time = new_time[0, new_time.size-6] #remove timezone
      schedule = "at #{new_time}"
    end
    upload_output = options["upload_output"]
    time_to_upload = calc_output_time(upload_output)
    if time_to_upload==0 or time_to_upload==-1
      upload_output_option = "--upload_output=1m"
    else
      upload_output_option = "--upload_output=#{upload_output}"
    end
    remote = "--remote=true"
    if !instance_type.nil? and instance_type.include? "gpu"
      remote= "#{remote} --gpu=true"
    end

    options_hash = Hash[options]
    options_hash.except!("schedule", "machine_type", "image", "upload_output", "grid", "data", "data_commit", "local", "small", "medium", "large", "gpu", "gpuxl", "gpuxxl")
    exec_options = options_hash.map { |x| "--#{x[0]}=#{x[1]}" }.flatten.join(" ")
    command = "#{exec_options} #{remote}  #{upload_output_option} #{cmd.flatten.join(" ")}"
    commit_to_run = options["commit"] || nil
    if !schedule.nil? and !schedule.empty?

      local_timestamp = get_schedule_date

    end
    project = Project.new(working_dir)

    choose_image = options["image"]

    if !choose_image.nil? and !choose_image.empty?
      invoke :set_image, [choose_image]
    end
    image = is_project_with_docker(working_dir)
    if !image or !image.is_docker
      # say "Couldn't find image related to project", Thor::Shell::Color::RED

      image_slug = "cnvrg"
      if instance_type.eql? "gpu" or instance_type.eql? "gpuxl"
        image_slug = "cnvrg_gpu"
      end
      # default = yes? "use #{default_image_name} default image?", Thor::Shell::Color::YELLOW
      # if default
      #   image = Images.new(working_dir, default_image_name)
      #   image_slug = image.image_slug
      # else
      #   exit(0)
      # end
    else
      image_slug = image.image_slug
    end

    invoke :sync, [false], :force=>force if sync_before


    if command.include? "'"
      oc = command.to_enum(:scan, /'/).map { Regexp.last_match }
      pairs = oc.enum_for(:each_slice, 2).to_a
      pairs.each_with_index do |p, i|
        add=0
        if i!=0
          add=2*i
        end
        total_loc = command[p[0].offset(0)[0]+add..p[1].offset(0)[0]+add]
        command[p[0].offset(0)[0]+add..p[1].offset(0)[0]+add] = "\"#{total_loc}\""
      end


    end
    log_message("Running remote experiment", Thor::Shell::Color::BLUE)
    exp = Experiment.new(project.owner, project.slug)
    res = exp.exec_remote(command, commit_to_run, instance_type, image_slug, schedule, local_timestamp, grid, path_to_cmd, data, data_commit)
    if Cnvrg::CLI.is_response_success(res)
      # if res["result"]["machine"] == -1
      #   say "There are no available machines", Thor::Shell::Color::BLUE
      #   create = yes? "create new machine?", Thor::Shell::Color::YELLOW
      #   if create
      #     res = Cnvrg::API.request("users/#{image.owner}/machines/list", 'GET')
      #     if Cnvrg::CLI.is_response_success(res)
      #       instance_type = machine_options(res["result"]["aws_options"])
      #       if @image.new_machine(instance_type)
      #         say "Running remote experiment", Thor::Shell::Color::BLUE
      #
      #         # res = image.exec_remote(exec_args, exec_options, project.last_local_commit)
      #         # if Cnvrg::CLI.is_response_success(res)
      #
      #           check = Helpers.checkmark()
      #           say "#{check} Finished successfuly", Thor::Shell::Color::GREEN
      #           exit(0)
      #         # end
      #       end
      #     else
      #       say "No machines are avilable", Thor::Shell::Color::RED
      #       exit(0)
      #     end
      #
      #
      #   else
      #     say "Can't execute command on remote machine with local image", Thor::Shell::Color::RED
      #     exit(1)
      #
      #   end
      # else
      check = Helpers.checkmark()
      str = "#{check} Experiment's is on: #{Cnvrg::Helpers.remote_url}/#{project.owner}/projects/#{project.slug}/experiments/#{res["result"]["exp_url"]}"

      if res["result"]["grid"]
        str = "Running grid search. #{Cnvrg::Helpers.remote_url}/#{project.owner}/projects/#{project.slug}/experiments?grid=#{res["result"]["exp_url"]} "
      end

      log_message(str, Thor::Shell::Color::GREEN)

      exit(0)
      # end
    end

  rescue => e
    log_message("Error occurred, Aborting", Thor::Shell::Color::RED)
    log_error(e)

  rescue SignalException
    exit_status = -1
    end_commit = project.last_local_commit

    res = @exp.end(log, exit_status, end_commit, "", "")
    say "\nAborting"

    exit(1)
  end
end

#experimentsObject



4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
# File 'lib/cnvrg/cli.rb', line 4690

def experiments
  verify_logged_in(true)
  log_start(__method__, args, options)

  project_dir = is_cnvrg_dir(Dir.pwd)
  @project = Project.new(project_dir)
  unless options['id'].to_s.size > 5
    result = @project.get_experiments()
    list = result["result"]["experiments"]
    if list and list.size > 1
      print_table(list)
    else
      say "No experiments"
    end
  else
    result = @project.get_experiment(options['id'])
    result = result["result"]["experiment"]
    if result
      if options["tag"].to_s.size == 0
        list = []
        list << result.keys
        list << result.values

        print_table(list)
      else
        if result.keys.include? options["tag"]
          say result[options["tag"]]
        else
          say "No such tag"
        end
      end
    else
      say "No such experiment"
    end


  end

end

#get_machineObject



4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
# File 'lib/cnvrg/cli.rb', line 4732

def get_machine()
  begin
    verify_logged_in(true)
    log_start(__method__, args, options)
    owner = Cnvrg::CLI.get_owner()
    working_dir = is_cnvrg_dir
    @image = Images.new(working_dir)
    if @image.nil? or !@image.is_docker
      say "Couldn't find image related to this project", Thor::Shell::Color::RED
      exit(0)
    end
    res = Cnvrg::API.request("users/#{owner}/machines/list", 'GET')
    if Cnvrg::CLI.is_response_success(res)
      if res["result"]["machines"].empty?
        create = yes? "No machines available, create new machine?", Thor::Shell::Color::YELLOW
        if create
          instance_type = machine_options(res["result"]["aws_options"])
        else
          exit(0)
        end
      end
      printf "%-20s %-20s %-20s\n", "name", "created by", "last_used", "instance_type"
      res["result"]["machines"].each do |u|
        time = Time.parse(u["last_used"])
        update_at = get_local_time(time)
        printf "%-20s %-20s %-20s\n", u["name"], u["created_by"], update_at, u["instance type"]
      end
    end

  rescue SignalException
    log_end(-1)
    say "\nAborting"
    exit(1)
  end
end

#init_data(public) ⇒ Object



758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
# File 'lib/cnvrg/cli.rb', line 758

def init_data(public)
  begin
    verify_logged_in(false)
    log_start(__method__, args, options)
    dataset_name =File.basename(Dir.getwd)
    if File.directory?(Dir.getwd+"/.cnvrg")
      config = YAML.load_file("#{Dir.getwd}/.cnvrg/config.yml")
      log_message("Directory is already linked to #{config[:dataset_slug]}", Thor::Shell::Color::RED)

      exit(0)
    end
    log_message("Init dataset: #{dataset_name}", Thor::Shell::Color::BLUE)

    working_dir = Dir.getwd
    owner = CLI.get_owner
    if Dataset.init(owner, dataset_name, options["public"])
      path = Dir.pwd
      @dataset = Dataset.new(path)

      url = @dataset.url
      check = Helpers.checkmark
      log_message("#{check} Link finished successfully", Thor::Shell::Color::GREEN)
      log_message("#{dataset_name}'s location is: #{url}\n", Thor::Shell::Color::GREEN)

    else
      @dataset.revert(working_dir) unless @dataset.nil?
      log_message("Error creating dataset, please contact support.", Thor::Shell::Color::RED)
      exit(0)
    end
  rescue => e
    log_error(e)
  rescue SignalException
    say "\nAborting"
    exit(1)
  end
end

#init_data_container(container) ⇒ Object



856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
# File 'lib/cnvrg/cli.rb', line 856

def init_data_container(container)
  begin
     = options["login_content"]

    container = Docker::Container.get(container)
    command = ["/bin/bash", "-lc", "sudo echo -e \"#{}\" >/home/ds/.netrc"]
    container.exec(command, tty: true)
    command = ["/bin/bash", "-lc", "mkdir /home/ds/.cnvrg"]
    container.exec(command, tty: true)
    command = ["/bin/bash", "-lc", "mkdir /home/ds/.cnvrg/tmp"]
    container.exec(command, tty: true)
    command = ["/bin/bash", "-lc", "sudo chown -R ds /home/ds/.cnvrg /home/ds/.netrc"]
    container.exec(command, tty: true)
    command = ["/bin/bash", "-lc", "sudo chmod 0600 /home/ds/.netrc"]
    container.exec(command, tty: true)

  rescue SignalException

    say "\nAborting"
    exit(1)
  end
end

#install_python_libraries(*lib) ⇒ Object



3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
# File 'lib/cnvrg/cli.rb', line 3766

def install_python_libraries(*lib)
  begin
    verify_logged_in(false)
    log_start(__method__, args, options)
    image = is_project_with_docker(Dir.pwd)
    if image and image.is_docker
      container = image.get_container
      if !container

        say "Couldn't create container with image #{image.image_name}:#{image.image_tag}", Thor::Shell::Color::RED
        exit(1)
      end
    else
      say "Project is not configured with any image", Thor::Shell::Color::RED
      exit(1)

    end
    req_file = options["requirement"] || nil
    if lib.nil? and not req_file.nil?
      if not File.exist? req_file
        say "Couldn't find #{req_file}", Thor::Shell::Color::RED
        exit(1)

      end
      command_to_run = "pip install -r #{req_file}"

    else
      command_to_run = lib.join(" ")

    end
    say "Running #{command_to_run} in container", Thor::Shell::Color::BLUE
    command = ["/bin/bash", "-lc", "#{command_to_run}"]
    res = container.exec(command, tty: false)
    say res[0].join("\n")
    checks = Helpers.checkmark()
    say "Updating image", Thor::Shell::Color::BLUE

    image.create_custom_image("")
    say "#{checks} Done, installing libraries completed", Thor::Shell::Color::GREEN
    container.stop()

    log_end(0)
  rescue => e
    log_end(-1, e.message)
    say "Error occurred, aborting"
    if container
      container.stop()
    end
  rescue SignalException
    if container
      container.stop()
    end
    say "\nAborting"
    exit(1)
  end

end

#install_system_libraries(*command_to_run) ⇒ Object



3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
# File 'lib/cnvrg/cli.rb', line 3715

def install_system_libraries(*command_to_run)
  begin
    verify_logged_in(false)
    log_start(__method__, args, options)
    image = is_project_with_docker(Dir.pwd)
    if image and image.is_docker
      container = image.get_container
      if !container

        say "Couldn't create container with image #{image.image_name}:#{image.image_tag}", Thor::Shell::Color::RED
        exit(1)
      end
    else
      say "Project is not configured with any image", Thor::Shell::Color::RED
      exit(1)

    end

    command_to_run = command_to_run.join(" ")
    say "Running #{command_to_run} in container", Thor::Shell::Color::BLUE
    command = ["/bin/bash", "-lc", "#{command_to_run}"]
    res = container.exec(command, tty: false)
    say res[0].join("\n")
    checks = Helpers.checkmark()
    say "Updating image", Thor::Shell::Color::BLUE

    image.create_custom_image("")
    say "#{checks} Done, installing libraries completed", Thor::Shell::Color::GREEN
    container.stop()

    log_end(0)
  rescue => e
    log_end(-1, e.message)
    say "Error occurred, aborting"
    if container
      container.stop()
    end
  rescue SignalException
    log_End(-1)
    if container
      container.stop()
    end
    say "\nAborting"
    exit(1)
  end

end

#jump(commit_sha1) ⇒ Object



2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
# File 'lib/cnvrg/cli.rb', line 2195

def jump(commit_sha1)
begin
  verify_logged_in()
  log_start(__method__, args, options)
  is_remote = options["remote"]
  project_home = get_project_home
  @project = Project.new(project_home)
  # say "Syncing existing project tree before jumping", Thor::Shell::Color::BLUE
  current_commit = @project.last_local_commit
  if current_commit.eql? commit_sha1
    log_message("Project is already updated", Thor::Shell::Color::GREEN)
    exit(0)
  end
  @files = Cnvrg::Files.new(@project.owner, @project.slug)
  response = @project.clone(false, commit_sha1)
  Cnvrg::CLI.is_response_success(response, true)

  successful_changes = []

  if !response["result"]["tree"].nil?
    parallel_options = {
        :progress => {
            :title => "Jump Progress",
            :progress_mark => '=',
            :format => "%b>>%i| %p%% %t",
            :starting_at => 0,
            :total => response["result"]["tree"].size,
            :autofinish => true
        },
        in_processes: ParallelProcesses,
        in_thread: ParallelThreads
    }
    commit_sha1 = response["result"]["commit"]
    idx = {commit: response["result"]["commit"], tree: response["result"]["tree"]}
    File.open(project_home + "/.cnvrg/idx.yml", "w+") { |f| f.write idx.to_yaml }
    if is_remote
      current_tree = Dir.glob("**/*", File::FNM_DOTMATCH).flatten.reject { |file| file.start_with? '.' or file.eql? "__init__.py" or file.eql? "uwsgi.ini" or file.ends_with? "/." or file.eql? "." }
    else
      current_tree = Dir.glob("**/*", File::FNM_DOTMATCH).flatten.reject { |file| file.start_with? '.cnvrg' or file.ends_with? "/."  or file.eql? "."}
    end

    jump_result = Parallel.map(response["result"]["tree"], parallel_options) do |f|

      relative_path = f[0].gsub(/^#{@project.local_path}/, "")
      log_message("Downloading #{f[0]}", Thor::Shell::Color::BLUE, false)
      if f[0].end_with? "/"
        # dir
      @files.download_dir(f[0], relative_path, project_home)

      else
        # blob
        @files.download_file_s3(f[0], relative_path, project_home, commit_sha1=commit_sha1)
      end
    end


      successful_changes = jump_result.select { |x| not x.nil? }
  end
  response["result"]["tree"].each do |f|
    if f[0].end_with? "/"
        current_tree .delete(f[0][0, f[0].size-1])
    else
      current_tree .delete(f[0])
    end
  end

    FileUtils.rm_rf(current_tree)
    log_message("Done. Jumped to #{commit_sha1} completed successfully", Thor::Shell::Color::GREEN)
    rescue => e
    log_message("Error occurred, Aborting", Thor::Shell::Color::RED)
    log_error(e)
    rescue SignalException

    exit(1)
  end
end


677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
# File 'lib/cnvrg/cli.rb', line 677

def link
  begin
    verify_logged_in(false)
    log_start(__method__, args, options)
    docker_image = options["docker_image"]
    if !docker_image.nil? and !docker_image.empty?
      docker = true
    else
      docker = false
    end

    sync = options["sync"]
    project_name =File.basename(Dir.getwd)
    log_message("Linking #{project_name}", Thor::Shell::Color::BLUE)
    if File.directory?(Dir.getwd+"/.cnvrg")
      config = YAML.load_file("#{Dir.getwd}/.cnvrg/config.yml")
      log_message("Directory is already linked to #{config[:project_slug]}", Thor::Shell::Color::RED)
      exit(0)
    end
    working_dir = Dir.getwd
    owner = CLI.get_owner
    if Project.link(owner, project_name, docker)
      path = Dir.pwd
      @project = Project.new(path)
      @project.generate_idx()
      if docker
        local_images = Docker::Image.all
        docker_image_local = local_images.map { |x| x.info["RepoTags"] }.flatten.select { |y| y.include? docker_image }.flatten
        if docker_image_local.size == 0
          if yes? "Image wasn't found locally, pull image from cnvrg repository?", Thor::Shell::Color::YELLOW
            image = pull(docker_image)
            if image
              log_message("downloaded image: #{docker_image}", Thor::Shell::Color::BLUE)
              @image = Images.new(working_dir, docker_image)
            else
              log_message("Could not create a new project with docker, image was not found", Thor::Shell::Color::RED)
              @project.revert(working_dir)
              exit(1)
            end
          else
            log_message("Could not create a new project with docker, image was not found", Thor::Shell::Color::RED)
            @project.revert(working_dir)
            exit(1)

          end
        elsif docker_image_local.size == 1
          log_message("found image: #{docker_image_local[0]}, setting it up..", Thor::Shell::Color::BLUE)
          @image = Images.new(working_dir, docker_image_local[0])
        elsif docker_image_local.size >1
          log_message("found #{docker_image_local.size} images, choose the image name you want to use", Thor::Shell::Color::BLUE)
          image_name = ask "#{docker_image_local.join("\n")}\n", Thor::Shell::Color::BLUE
          @image = Images.new(working_dir, image_name)
        end
      end
      if sync
        log_message("Syncing project", Thor::Shell::Color::BLUE)
        upload(true)
      end

      url = @project.url
      check = Helpers.checkmark
      log_message("#{check} Link finished successfully", Thor::Shell::Color::GREEN)
      log_message("#{project_name}'s location is: #{url}\n", Thor::Shell::Color::GREEN)

    else
      @project.revert(working_dir) unless @project.nil?
      log_message("Error linking project, please contact support.", Thor::Shell::Color::RED)
      exit(0)
    end
  rescue => e
    log_error(e)
  rescue SignalException

    say "\nAborting"
    exit(1)
  end
end

#list_commitsObject



1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
# File 'lib/cnvrg/cli.rb', line 1440

def list_commits()
  verify_logged_in(true)
  log_start(__method__, args, options)

  project_dir = is_cnvrg_dir(Dir.pwd)
  @project = Project.new(project_dir)
  result = @project.list_commits()
  list = result["result"]["list"]

  print_table(list)

end

#list_datasetObject



1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
# File 'lib/cnvrg/cli.rb', line 1407

def list_dataset
  verify_logged_in(false)
  log_start(__method__, args, options)
  dataset_dir = is_cnvrg_dir(Dir.pwd)
  @dataset = Dataset.new(dataset_dir)
  owner = @dataset.owner
  if owner.nil? or owner.empty?
    owner = CLI.get_owner()
  end
  result = @dataset.list(owner)
  list = result["result"]["list"]

  print_table(list)

end

#list_dataset_commitsObject



1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
# File 'lib/cnvrg/cli.rb', line 1425

def list_dataset_commits()
  verify_logged_in(true)
  log_start(__method__, args, options)

  dataset_dir = is_cnvrg_dir(Dir.pwd)
  @dataset = Dataset.new(dataset_dir)
  result = @dataset.list_commits()
  list = result["result"]["list"]

  print_table(list)

end

#list_imagesObject



4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
# File 'lib/cnvrg/cli.rb', line 4637

def list_images
  begin
    verify_logged_in(false)
    log_start(__method__, args, options)
    owner = Cnvrg::CLI.get_owner()
    res = Cnvrg::API.request("users/#{owner}/images/list", 'GET')
    if Cnvrg::CLI.is_response_success(res)
      printf "%-20s %-20s  %-30s %-20s %-20s\n", "name", "project", "created by", "is_public", "last updated"
      res["result"]["images"].each do |u|
        time = Time.parse(u["created_at"])
        update_at = get_local_time(time)
        created_by = u["created_by"]

        printf "%-20s %-20s  %-30s %-20s %-20s\n", u["name"], u["project"], created_by, u["is_public"], update_at
      end
    end
    return res["result"]["images"]
  rescue SignalException
    say "\nAborting"
    exit(1)
  end


end

#list_machinesObject



4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
# File 'lib/cnvrg/cli.rb', line 4664

def list_machines
  begin
    verify_logged_in(false)
    log_start(__method__, args, options)
    owner = Cnvrg::CLI.get_owner()
    res = Cnvrg::API.request("users/#{owner}/machines/list", 'GET')
    if Cnvrg::CLI.is_response_success(res)
      printf "%-20s %-20s %-20s\n", "name", "created by", "last_used"
      res["result"]["machines"].each do |u|
        time = Time.parse(u["last_used"])
        update_at = get_local_time(time)
        printf "%-20s %-20s %-20s\n", u["name"], u["created_by"], update_at
      end
    end
    return res["result"]["images"]
  rescue SignalException
    say "\nAborting"
    exit(1)
  end


end

#loginObject



405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
# File 'lib/cnvrg/cli.rb', line 405

def 
  begin
    log_handler()
    log_start(__method__, args, options)

    cmd = HighLine.new

    say 'Authenticating with cnvrg', Thor::Shell::Color::YELLOW

    @auth = Cnvrg::Auth.new
    netrc = Netrc.read
    @email, token = netrc[Cnvrg::Helpers.netrc_domain]

    if @email and token
      log_message('Seems you\'re already logged in', Thor::Shell::Color::BLUE)
      exit(0)
    end
    @email = ask("Enter your email:")
    password = cmd.ask("Enter your password (hidden):") { |q| q.echo = "*" }
    result = @auth.(@email, password)

    if !result["token"].nil?
      netrc[Cnvrg::Helpers.netrc_domain] = @email, result["token"]
      netrc.save

      log_message("Authenticated successfully as #{@email}", Thor::Shell::Color::GREEN)

      owners = result["owners"]
      urls = result["urls"]
      choose_owner = result["username"]
      ow_index = 0
      if owners.empty?
        choose_owner = result["username"]
      else
        choose_owner = owners[0]
      end

      # if owners.empty?
      # else
      #   owners << choose_owner
      #   chosen = false
      #   while !chosen
      #     owners_id = owners.each_with_index.map { |x, i| "#{i+1}. #{x}" }
      #     choose_owner = ask("Choose default owner:\n"+owners_id.join("\n")+"\n")
      #
      #     if choose_owner =~ /[[:digit:]]/
      #       ow_index = choose_owner.to_i-1
      #       if ow_index<0 or ow_index >= owners.size
      #         say "No such owner, please choose again", Thor::Shell::Color::BLUE
      #         chosen = false
      #         next
      #       end
      #       choose_owner = owners[choose_owner.to_i-1]
      #       chosen = true
      #
      #     else
      #
      #       owners_lower = owners.map { |o| o.downcase }
      #       ow_index = owners_lower.index(choose_owner.downcase)
      #       if ow_index.nil?
      #         say "Could not find owner named #{choose_owner}", Thor::Shell::Color::RED
      #       else
      #         chosen = true
      #       end
      #     end
      #
      #   end


      # end

      if set_owner(choose_owner, result["username"], urls[ow_index])
        log_message("Setting default owner: #{choose_owner}", Thor::Shell::Color::GREEN)

      else
        log_message("Setting default owenr has failed, logging out", Thor::Shell::Color::RED)

        return logout()
      end

    else
      log_message("Failed to authenticate, wrong email/password", Thor::Shell::Color::RED)

      exit(1)
    end
  rescue => e

    log_message("Error Occurred, aborting", Thor::Shell::Color::RED)
    log_error(e)

    logout()
    exit(1)
  rescue SignalException

    say "\nAborting"
    logout()
    exit(1)
  end
end

#logoutObject



508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
# File 'lib/cnvrg/cli.rb', line 508

def logout
  begin
    log_handler()
    log_start(__method__, args, options)
    netrc = Netrc.read
    netrc.delete(Cnvrg::Helpers.netrc_domain)
    netrc.save
    log_message("Logged out successfully.\n", Thor::Shell::Color::GREEN)
  rescue =>  e
    puts e.message
    puts e.backtrace
  rescue SignalException
    say "\nAborting"
    exit(1)
  end

end

#meObject



529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
# File 'lib/cnvrg/cli.rb', line 529

def me()
  begin
    verify_logged_in(false)
    log_start(__method__, args, options)
    auth = Cnvrg::Auth.new
    if (email = auth.get_email)
      log_message("Logged in as: #{email}", Thor::Shell::Color::GREEN)
    else
      log_message("You're not logged in.", Thor::Shell::Color::RED)
    end


  rescue SignalException
    say "\nAborting"
    exit(1)
  end
end

#new(project_name) ⇒ Object

Projects



548
# File 'lib/cnvrg/cli.rb', line 548

desc 'new', 'Create a new cnvrg project'

#notebookObject



3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
# File 'lib/cnvrg/cli.rb', line 3203

def notebook
  local = options["local"]
  notebook_dir = options["notebook_dir"]
  kernel = options["kernel"]
  image = options["image"]
  data = options["data"]
  data_commit = options["data_commit"]
  if local
    invoke :run_notebook, [], :notebook_dir => notebook_dir, :remote => false, :kernel => kernel, :image => image
    return
  else
    instances = {"small" => options["small"], "medium" => options["medium"], "large" => options["large"],
                 "gpu" => options["gpu"], "gpuxl" => options["gpuxl"], "gpuxxl" => options["gpuxxl"]}
    instance_type = get_instance_type(instances)

    invoke :remote_notebook, [], :notebook_dir => notebook_dir, :kernel => kernel, :machine_type => instance_type, :image => image,
           :data => data, :data_commit => data_commit
    return

  end


end

#notebook_stop(notebook_slug) ⇒ Object



3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
# File 'lib/cnvrg/cli.rb', line 3677

def notebook_stop(notebook_slug)
  begin
    verify_logged_in(true)
    log_start(__method__, args, options)
    project_dir = is_cnvrg_dir()


    @project = Project.new(project_dir)


    @note = Experiment.new(@project.owner, @project.slug)
    log_message("Stoping notebook session: #{notebook_slug}", Thor::Shell::Color::BLUE)

    res = @note.end_notebook_session(notebook_slug)
    if res
      check = Helpers.checkmark()
      log_message("#{check} Notebook session has stopped successfully", Thor::Shell::Color::GREEN)

      exit(0)
    else

      log_message("Couldn't stop notebook session, try stopping via cnvrg web", Thor::Shell::Color::RED)
      exit(1)
    end
  rescue => e
    log_message("Error occurd, aborting", Thor::Shell::Color::RED)
    log_error(e)
  rescue SignalException
    log_message("Aborting", Thor::Shell::Color::BLUE)
    exit(1)
  end


end

#port_container(container_id) ⇒ Object



4238
4239
4240
4241
# File 'lib/cnvrg/cli.rb', line 4238

def port_container(container_id)
  container = Docker::Container.get(container_id)
  say container.json["HostConfig"]["PortBindings"]["8888/tcp"][0]["HostPort"]
end

#pull_image(image_name) ⇒ Object



4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
# File 'lib/cnvrg/cli.rb', line 4771

def pull_image(image_name)
  begin
    verify_logged_in(false)
    log_start(__method__, args, options)
    owner = Cnvrg::CLI.get_owner()
    image = Cnvrg::Images.image_exist(owner, image_name)
    if !image
      log_message("Couldn't find image in cnvrg repository", Thor::Shell::Color::RED)
      exit(1)
    end
    path = download_image(image_name, image["slug"])
    if path
      log_message("Building image", Thor::Shell::Color::BLUE)
      Docker.options[:read_timeout]=216000
      image = Docker::Image.build_from_dir(path, {'dockerfile' => 'Dockerfile.cpu', 't' => "#{image_name}:latest"}) do |v|
        begin
          if (log = JSON.parse(v)) && log.has_key?("stream")
            next if log["stream"].starts_with? "Step"
            $stdout.puts log["stream"]
          end
        rescue
        end

      end

      if not image.nil?
        FileUtils.rm_rf(path)
        checks = Helpers.checkmark()
        log_message("#{checks} Image built successfully", Thor::Shell::Color::GREEN)
        return image
      else

        log_message("Could not build image", Thor::Shell::Color::RED)
        return false
      end
    else

      log_message("Could not download image", Thor::Shell::Color::RED)
      return false


    end

      # else
      #   path = download_image(image_name,image["slug"])
      #   if path
      #     image = Docker::Image.import(path)
      #     image.tag('repo' => image_name, 'tag' => 'latest')
      #     if not image.nil?
      #       say "Finished downloading image, cleaning up..", Thor::Shell::Color::GREEN
      #       FileUtils.rm(path)
      #       checks = Helpers.checkmark()
      #       say "#{checks} Done", Thor::Shell::Color::GREEN
      #       log_end(0)
      #       return image
      #       log_end(0)
      #     else
      #       say "Could not download image", Thor::Shell::Color::RED
      #       return false
      #     end
      #
      #   end
      # end
  rescue => e

    log_message "Error: couldn't build image", Thor::Shell::Color::RED
    log_error(e)

  rescue SignalException
    say "\nAborting"
    exit(1)
  ensure
    if path
      FileUtils.rm_rf(path)

    end
  end


end

#push(*name) ⇒ Object



4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
# File 'lib/cnvrg/cli.rb', line 4117

def push(*name)
  verify_logged_in(true)
  log_start(__method__, args, options)
  working_dir = is_cnvrg_dir()
  if !name.empty? and name == "cnvrg"
    log_message("can't create image with the name cnvrg", Thor::Shell::Color::RED)
    exit(1)
  end
  begin
    image = is_project_with_docker(working_dir)
    if !image or !image.is_docker
      log_message("Couldn't find image related to project", Thor::Shell::Color::RED)
      exit(0)
    end
    if !name.nil? and !name.empty?
      if name.include? " "
        name.gsub!(" ", "_")
      end
    end
    stored_commands = File.open(working_dir+"/.cnvrg/custom_image.txt").read.chop.gsub("\n", ",")
    if stored_commands.nil? or stored_commands.empty?
      log_message("Nothing to push", Thor::Shell::Color::BLUE)
      exit(0)
    end

    log_message("Pushing new image", Thor::Shell::Color::BLUE)
    if image.create_custom_image(name, working_dir, stored_commands)

      log_message("Image was updated successfully", Thor::Shell::Color::GREEN)
    end
  rescue => e
    log_message("error occurred, aborting", Thor::Shell::Color::RED)
    log_error(e)

  end
end

#remote_notebookObject



3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
# File 'lib/cnvrg/cli.rb', line 3339

def remote_notebook()
  verify_logged_in(true)
  log_start(__method__, args, options)

  working_dir = is_cnvrg_dir()
  instance_type = options["machine_type"] || nil
  data = options["data"]
  data_commit = options["data_commit"]
  commit = options["commit"]
  notebook_type = options["notebook_type"]


  begin
    project = Project.new(working_dir)
    exp = Experiment.new(project.owner, project.slug)

    if !notebook_type.nil? and !notebook_type.empty?
      notebook_type = "jupyter"
    end
    invoke :sync, [false], []
    slug = ""
    res =exp.remote_notebook( instance_type, commit, data, data_commit, notebook_type)
    if Cnvrg::CLI.is_response_success(res)
      slug = res["result"]["notebook_url"]
      log_message("#{Helpers.checkmark} Notebook is ready: #{Cnvrg::Helpers.remote_url}/#{project.owner}/projects/#{project.slug}/notebook_sessions/show/#{slug}", Thor::Shell::Color::GREEN)

    end
  rescue => e
    log_message("Error occurred, Aborting", Thor::Shell::Color::RED)
    log_error(e)

  rescue SignalException
    log_message("Aborting", Thor::Shell::Color::BLUE)
    notebook_stop(slug) unless slug.nil? or slug.empty?

    exit(1)
  end
end

#remote_notebook_oldObject



3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
# File 'lib/cnvrg/cli.rb', line 3236

def remote_notebook_old()
  verify_logged_in(true)
  log_start(__method__, args, options)

  working_dir = is_cnvrg_dir()
  notebook_dir = options["notebook_dir"]
  instance_type = options["machine_type"] || nil
  kernel = options["kernel"] || nil
  data = options["data"]
  data_commit = options["data_commit"]


  begin
    choose_image = options["image"]

    if !choose_image.nil? and !choose_image.empty?
      invoke :set_image, [choose_image]
    end
    @image = is_project_with_docker(working_dir)
    if !@image or !@image.is_docker
      # say "Couldn't find image related to project", Thor::Shell::Color::RED
      default_image_name = "cnvrg"
      if instance_type.eql? "gpu" or instance_type.eql? "gpuxl"
        default_image_name = "cnvrg-gpu"
      end
      # default = yes? "use #{default_image_name} default image?", Thor::Shell::Color::YELLOW
      # if default
      @image = Images.new(working_dir, default_image_name)
      # else
      #   exit(0)
      # end
    end

    invoke :sync, [false], []


    res = @image.remote_notebook(notebook_dir, instance_type, kernel, data, data_commit)
    if Cnvrg::CLI.is_response_success(res)
      if res["result"]["machine"] == -1
        log_message("There are no available machines", Thor::Shell::Color::BLUE)
        create = yes? "create new machine?", Thor::Shell::Color::YELLOW
        if create
          res = Cnvrg::API.request("users/#{@image.owner}/machines/list", 'GET')
          if Cnvrg::CLI.is_response_success(res)
            instance_type = machine_options(res["result"]["aws_options"])
            if @image.new_machine(instance_type)
              res = @image.remote_notebook(notebook_dir, instance_type, kernel)
              if Cnvrg::CLI.is_response_success(res)
                url = res["result"]["url"]
                if !url.nil? and !url.empty?
                  check = Helpers.checkmark()

                  log_message("#{check} Notebook server started successfully", Thor::Shell::Color::GREEN)
                  Launchy.open(url)
                else
                  log_message("Couldn't run notebook server", Thor::Shell::Color::RED)
                end
                exit(0)
              end
            end
          else
            log_message("No machines are avilable", Thor::Shell::Color::RED)
            exit(0)
          end


        else
          log_message("Can't execute command on remote machine with local image", Thor::Shell::Color::RED)
          exit(1)

        end
      else
        note_url = res["result"]["notebook_url"]
        @image.set_note_url(note_url)
        check = Helpers.checkmark()
        log_message("#{check} Notebook is on: #{Cnvrg::Helpers.remote_url}/#{@image.owner}/projects/#{@image.project_slug}/notebook_sessions/show/#{note_url}", Thor::Shell::Color::GREEN)
        # Launchy.open(url)

        exit(0)
      end
    end
  rescue => e
    log_message("Error occurred, Aborting", Thor::Shell::Color::RED)
    log_error(e)

  rescue SignalException
    exit_status = -1
    end_commit = @project.last_local_commit

    res = @exp.end(log, exit_status, end_commit, cpu_average, memory_average)
    say "\nAborting"

    exit(1)
  end
end

#revert_expObject



1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
# File 'lib/cnvrg/cli.rb', line 1678

def revert_exp
  begin
    log_start(__method__, args, options)
    @project = Project.new(get_project_home)
    ignore_list = @project.get_ignore_list()

    result = @project.compare_idx(false)["result"]
    result = result["tree"]
    if result["added"].size > 0
      FileUtils.rm_rf(result["added"])
    end
    say "Changes were removed successfully", Thor::Shell::Color::GREEN


  rescue SignalException
    log_end(-1)
    say "\nAborting"
    exit(1)
  end
end

#run(*cmd) ⇒ Object



2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
# File 'lib/cnvrg/cli.rb', line 2371

def run(*cmd)
  sync_before = options["sync_before"]
  sync_after = options["sync_after"]
  log = options["log"]
  title = options["title"]
  commit = options["commit"] || nil
  email_notification = options["email_notification"]
  upload_output = options["upload_output"]
  local = options["local"]
  schedule = options["schedule"]
  image = options["image"]
  grid = options["grid"]
  data = options["data"]
  data_commit = options["data_commit"]
  ignore = options["ignore"]
  force = options["force"]

  options_hash = Hash[options]
  real_options = []
  options_hash.each do |o|
    real_options << o if (!o[1].eql? "" and !["small", "medium", "large", "gpu", "gpuxl", "gpuxxl"].include? o[0])
  end
  if local
    invoke :exec, [cmd], :sync_before => sync_before, :sync_after => sync_after, :title => title,
           :log => log, :email_notification => email_notification, :upload_output => upload_output,
           :commit => commit, :image => image, :data => data, :data_commit => data_commit, :ignore => ignore, :force=>force
    return
  else
    real_options.delete(["local", false])
    instances = {"small" => options["small"], "medium" => options["medium"], "large" => options["large"],
                 "gpu" => options["gpu"], "gpuxl" => options["gpuxl"], "gpuxxl" => options["gpuxxl"]}
    instance_type = get_instance_type(instances)
    if !instance_type.nil? and !instance_type.empty?
      real_options << ["machine_type", instance_type]
    end
    exec_options = real_options.map { |x| "--#{x[0]}=#{x[1]}" }.flatten.join(" ")
    cmd_to_exec = "#{exec_options} #{cmd.join(" ")}"
    invoke :exec_remote, [cmd], :sync_before => sync_before, :sync_after => sync_after, :title => title, :machine_type => instance_type,
           :schedule => schedule, :log => log, :email_notification => email_notification, :upload_output => upload_output, :commit => commit,
           :image => image, :grid => grid, :data => data, :data_commit => data_commit, :ignore => ignore, :force=>force
    return
  end

  # if local
  #
  # else


  #   invoke :exec_remote, [cmd_to_exec.split(" ")], :sync_before => sync_before, :sync_after => sync_after, :title => title, :machine_type => instance_type,
  #          :schedule => schedule, :log => log, :email_notification => email_notification, :upload_output => upload_output, :commit => commit,
  #          :image => image, :grid => grid, :data => data, :data_commit => data_commit, :ignore => ignore
  #   return
  # end
end

#run_notebookObject



3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
# File 'lib/cnvrg/cli.rb', line 3506

def run_notebook

  begin
    verify_logged_in(true)
    log_start(__method__, args, options)

    project_dir = is_cnvrg_dir()

    notebook_dir = options["notebook_dir"]
    remote = options["remote"] || false
    kernel = options["kernel"] || ""
    notebooks_pid = nil

    if notebook_dir.empty?
      notebook_dir = project_dir
    else

      notebook_dir = project_dir+ notebook_dir
    end
    choose_image = options["image"]

    if !choose_image.nil? and !choose_image.empty?
      invoke :set_image, [choose_image]
    end

    image = is_project_with_docker(Dir.pwd)
    if !image
      jupyter_installed = `which jupyter`
      if !$?.success?
        say "Could not find jupyter, Is it installed?", Thor::Shell::Color::RED
        exit(1)
      end


      cmd = "jupyter-notebook --port=8888"
      PTY.spawn(cmd) do |stdout, stdin, pid, stderr|
        begin
          notebooks_pid = pid
          stdout.each do |line|
            puts line

          end

        rescue Errno::EIO => e
          # break
        rescue Errno::ENOENT
          log_end(1, "command #{cmd} isn't valid")


          say "command \"#{cmd}\" couldn't be executed, verify command is valid", Thor::Shell::Color::RED
        rescue PTY::ChildExited
          log_end(1, "proccess exited")
          say "The process exited!", Thor::Shell::Color::RED
        rescue => e
          log_end(-1, e.message)
          say "Error occurred,aborting", Thor::Shell::Color::RED
          exit(0)

        end


      end

    end

    if image and image.is_docker and !remote
      container= image.get_container
      if !container
        say "Couldn't start docker container", Thor::Shell::Color::RED
        exit(1)

      end

      if options["verbose"]
        say "Syncing project before running", Thor::Shell::Color::BLUE
        say 'Checking for new updates from remote version', Thor::Shell::Color::BLUE
      end
      @project = Project.new(project_dir)

      start_commit = @project.last_local_commit

      if (note_slug=image.note_slug)
        say "There is a running notebook session in: https://cnvrg.io/#{@project.owner}/projects/#{@project.slug}/notebook_sessions/show/#{note_slug}", Thor::Shell::Color::BLUE
        new = yes? "Create a new session?", Thor::Shell::Color::YELLOW
        if !new
          exit(0)
        end

      end
      invoke :sync, [false], :verbose => options["verbose"]
      say "Done Syncing", Thor::Shell::Color::BLUE if options["verbose"]
      #replace url
      base_url = get_base_url()

      local_url = "/#{@project.owner}/projects/#{@project.slug}/notebook_sessions/view/local"
      command = ["/bin/bash", "-lc", "sed -i 's#c.NotebookApp.base_url = .*#c.NotebookApp.base_url = \"#{local_url}\"#' /home/ds/.jupyter/jupyter_notebook_config.py"]
      container.exec(command, tty: true)
      container.stop()
      container.start()
      sleep(7)
      @note = Experiment.new(@project.owner, @project.slug)
      port = image.container_port()

      command = ["/bin/bash", "-lc", "jupyter notebook list"]
      list = container.exec(command, tty: true)[0]
      if list.empty? or list.nil?
        say "Couldn't start notebook server", Thor::Shell::Color::RED
        log_end(1, "can't start notebook server")
        exit(1)
      end

      result = ""
      list.each do |r|
        if r.include? "http"
          result = r
        end
      end
      token = result.to_s.split("::")[0].to_s.match(/(token=)(.+)\s/)[2]

      # machine_activity = @note.get_machine_activity(project_dir)


      slug = @note.start_notebook_session(kernel, start_commit, token, port, false, notebook_dir)
      image.set_note_url(slug)
      note_url = "http://localhost:#{port}/#{@project.owner}/projects/#{@project.slug}/notebook_sessions/view/local/?token=#{token}"


      if !note_url.empty?
        check = Helpers.checkmark()

        say "#{check} Notebook server started successfully", Thor::Shell::Color::GREEN
        Launchy.open(note_url)
      else
        say "Couldn't start notebook server", Thor::Shell::Color::RED
        log_end(1, "can't start notebook server")
        exit(1)
      end
    end


  rescue => e
    log_end(-1, e.message)
    say "Error occurred, aborting", Thor::Shell::Color::RED
    if container
      container.stop()
    end
  rescue SignalException
    if !notebooks_pid.nil?
      ::Process.kill(0, notebooks_pid)
      say "#{check} Notebook has stopped successfully", Thor::Shell::Color::GREEN


      invoke :sync, [false], []
    else
      log_end(-1)

      if container
        container.stop()
      end
    end

  end


end

#search_libraries(library) ⇒ Object



3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
# File 'lib/cnvrg/cli.rb', line 3380

def search_libraries(library)
  begin
    verify_logged_in(true)
    log_start(__method__, args, options)
    project_dir = is_cnvrg_dir()

    image = is_project_with_docker(project_dir)
    if image and image.is_docker
      container= image.get_container
      if !container
        say "Couldn't create container with image #{image.image_name}:#{image.image_tag}", Thor::Shell::Color::RED
        exit(1)
      end
    else
      say "Project is not configured with any image", Thor::Shell::Color::RED
      exit(1)

    end

    say "Searching for #{library}", Thor::Shell::Color::BLUE
    pip_arr = image.get_installed_packages("python")
    pip_arr = pip_arr.map(&:downcase)
    check = Helpers.checkmark()
    if !(p = pip_arr.map { |x| x.split("==")[0] }.index(library.downcase)).nil?

      say "#{check} Found it!", Thor::Shell::Color::GREEN


      printf "%-40s %-30s\n", "#{pip_arr[p].split("==")[0]}", "#{pip_arr[p].split("==")[1]}"

    else
      dpkg_arr = image.get_installed_packages("system")
      dpkg_arr = dpkg_arr.map(&:downcase)
      if !(p = dpkg_arr.map { |x| x.split("==")[0] }.index(library.downcase)).nil?
        say "#{check} Found!", Thor::Shell::Color::GREEN

        printf "%-40s %-30s\n", "#{dpkg_arr[p].split("==")[0]}", "#{dpkg_arr[p].split("==")[1]}"
      else
        say "Couldn't find #{library}, run cnvrg install_libraries to install", Thor::Shell::Color::RED
        exit(1)
      end


    end
  rescue => e
    log_end(-1, e.message)
    say "Error occurred, aborting", Thor::Shell::Color::RED
    if container
      container.stop()
    end
  rescue SignalException
    log_end(-1)
    if container
      container.stop()
    end
    say "Aborting"
    exit(1)
  end
end

#set_api_url(url) ⇒ Object



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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/cnvrg/cli.rb', line 197

def set_api_url(url)
  home_dir = File.expand_path('~')
  if !url.end_with? "/api"
    url = url+"/api"
  end
  begin
    if !File.directory? home_dir+"/.cnvrg"
      FileUtils.mkdir_p([home_dir+"/.cnvrg", home_dir+"/.cnvrg/tmp"])
    end
    if !File.exist?(home_dir+"/.cnvrg/config.yml")
      FileUtils.touch [home_dir+"/.cnvrg/config.yml"]
    end
    compression_path = "#{File.expand_path('~')}/.cnvrg/tmp"

    begin
      config = YAML.load_file(home_dir+"/.cnvrg/config.yml")
      if !config
        config = {owner: "", username: "", version_last_check: get_start_day(), api: url, compression_path: compression_path, }

      end
    rescue
      config = {owner: "", username: "", version_last_check: get_start_day(), api: url, compression_path: compression_path  }
    end
    owner = config.to_h[:owner]

    say "Setting default api to be: #{url}", Thor::Shell::Color::BLUE
    if config.empty?
      config = {owner: "", username: "", version_last_check: get_start_day(), api: url, compression_path: compression_path }
    else
      if !config.to_h[:compression_path].nil?
        compression_path = config.to_h[:compression_path]
      end
      config = {owner: config.to_h[:owner], username: config.to_h[:username], version_last_check: config.to_h[:version_last_check], api: url, compression_path: compression_path}
    end
    # res = Cnvrg::API.request("/users/#{owner}/custom_api", 'POST', {custom_api: url})
    # if Cnvrg::CLI.is_response_success(res, false)

    checks = Helpers.checkmark


    File.open(home_dir+"/.cnvrg/config.yml", "w+") { |f| f.write config.to_yaml }
    say "#{checks} Done", Thor::Shell::Color::GREEN
      # else
      #   say "Couldn't set default api, contact [email protected]", Thor::Shell::Color::RED
      #   exit(1)
      #
      # end

  rescue => e
    say "Couldn't set default api, contact [email protected]", Thor::Shell::Color::RED
  end
end

#set_compression_path(*compression_path) ⇒ Object



371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
# File 'lib/cnvrg/cli.rb', line 371

def set_compression_path(*compression_path)
  begin
    if (compression_path.nil? or compression_path.empty?) and options["reset"]
      compression_path = ["#{File.expand_path('~')}/.cnvrg/tmp"]
    end
    compression_path = compression_path.join(" ")
    if !Dir.exist? compression_path
      say "Couldn't find #{compression_path}, please make sure it exist", Thor::Shell::Color::RED
      exit(0)
    end

    home_dir = File.expand_path('~')
    path = "#{home_dir}/.cnvrg/config.yml"
    if !File.exist?(path)
      say "Couldn't find ~/.cnvrg/config.yml file, please logout and login again", Thor::Shell::Color::RED

      exit(0)
    end
    config = YAML.load_file(path)
    config_new = {owner: config.to_h[:owner], username: config.to_h[:username],
                  version_last_check: config.to_h[:version_last_check], api: config.to_h[:api], compression_path: compression_path}
    File.open(home_dir+"/.cnvrg/config.yml", "w+") { |f| f.write config_new.to_yaml }
    checks = Helpers.checkmark
    say "#{checks} Done", Thor::Shell::Color::GREEN

  rescue SignalException
    say "\nAborting"
    exit(1)
  end
end

#set_default_ownerObject



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

def set_default_owner
  begin
    path = File.expand_path('~')+"/.cnvrg/config.yml"
    if !File.exist?(path)
      say "Couldn't find ~/.cnvrg/config.yml file, please logout and login again", Thor::Shell::Color::RED

      exit(0)
    end
    config = YAML.load_file(path)

    username = config.to_h[:username]
    res = Cnvrg::API.request("/users/#{username}/get_possible_owners", 'GET')
    if Cnvrg::CLI.is_response_success(res)
      owner = username
      result = res["result"]
      owners = result["owners"]
      urls = result["urls"]
      choose_owner = result["username"]
      if owners.empty?
      else
        owners << choose_owner
        chosen = false
        while !chosen
          owners_id = owners.each_with_index.map { |x, i| "#{i+1}. #{x}" }
          choose_owner = ask("Choose default owner:\n"+owners_id.join("\n")+"\n")

          if choose_owner =~ /[[:digit:]]/
            ow_index = choose_owner.to_i-1
            if ow_index<0 or ow_index >= owners.size
              say "No such owner, please choose again", Thor::Shell::Color::BLUE
              chosen = false
              next
            end
            choose_owner = owners[choose_owner.to_i-1]
            chosen = true

          else

            owners_lower = owners.map { |o| o.downcase }
            ow_index = owners_lower.index(choose_owner.downcase)
            if ow_index.nil?
              say "Could not find owner named #{choose_owner}", Thor::Shell::Color::RED
            else
              chosen = true
            end
          end

        end


      end
      if set_owner(choose_owner, result["username"], urls[ow_index])
        say "Setting default owner: #{choose_owner}", Thor::Shell::Color::GREEN
      else
        say "Setting default owenr has failed, try to run cnvrg --config-default-owner", Thor::Shell::Color::RED
      end
    end
  rescue SignalException
    say "\nAborting"
    exit(1)
  end
end

#set_image(docker_image) ⇒ Object



638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
# File 'lib/cnvrg/cli.rb', line 638

def set_image(docker_image)
  verify_logged_in(false)
  log_start(__method__, args, options)
  working_dir = is_cnvrg_dir
  local_images = Docker::Image.all
  docker_image_local = local_images.map { |x| x.info["RepoTags"] }.flatten.select { |y| y.include? docker_image }.flatten
  if docker_image_local.size == 0

    if yes? "Image wasn't found locally, pull image from cnvrg repository?", Thor::Shell::Color::YELLOW
      image = pull(docker_image)
      if image
        say "downloaded image: #{docker_image}"
        @image = Images.new(working_dir, docker_image)
      else
        say "Could not set image, image was not found", Thor::Shell::Color::RED
        exit(1)
      end
    else
      say "Could nset image, image was not found", Thor::Shell::Color::RED
      exit(1)

    end
  elsif docker_image_local.size == 1
    say "found image: #{docker_image_local[0]}, setting it up..", Thor::Shell::Color::BLUE
    @image = Images.new(working_dir, docker_image_local[0])
  elsif docker_image_local.size >1
    say "found #{docker_image_local.size} images, choose the image name you want to use", Thor::Shell::Color::BLUE
    image_name = ask "#{docker_image_local.join("\n")}\n", Thor::Shell::Color::BLUE
    image_name = image_name.strip
    @image = Images.new(working_dir, image_name)
  end
  @image.update_image_activity(nil, nil)

end

#set_remote_api_url(owner, current_user, url) ⇒ Object



278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/cnvrg/cli.rb', line 278

def set_remote_api_url(owner, current_user, url)
  home_dir = File.expand_path('~')
  if !url.end_with? "/api"
    url = url+"/api"
  end
  begin
    if !File.directory? home_dir+"/.cnvrg"
      FileUtils.mkdir_p([home_dir+"/.cnvrg", home_dir+"/.cnvrg/tmp"])
    end
    if !File.exist?(home_dir+"/.cnvrg/config.yml")
      FileUtils.touch [home_dir+"/.cnvrg/config.yml"]
    end
    config = YAML.load_file(home_dir+"/.cnvrg/config.yml")

    compression_path = "#{home_dir}/.cnvrg/tmp"
    config = {owner: owner, username: current_user, version_last_check: get_start_day(), api: url, compression_path: compression_path}
    File.open(home_dir+"/.cnvrg/config.yml", "w+") { |f| f.write config.to_yaml }
    say "Done"
  rescue
    say "ERROR", Thor::Shell::Color::RED
  end
end

#set_remote_login(current_user, owner, url, email, secret) ⇒ Object



251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/cnvrg/cli.rb', line 251

def (current_user,owner,url, email, secret)
  netrc = Netrc.read
  netrc[Cnvrg::Helpers.netrc_domain] = email, secret
  netrc.save
  home_dir = File.expand_path('~')
  if !url.end_with? "/api"
    url = url+"/api"
  end
  begin
    if !File.directory? home_dir+"/.cnvrg"
      FileUtils.mkdir_p([home_dir+"/.cnvrg", home_dir+"/.cnvrg/tmp"])
    end
    if !File.exist?(home_dir+"/.cnvrg/config.yml")
      FileUtils.touch [home_dir+"/.cnvrg/config.yml"]
    end
    config = YAML.load_file(home_dir+"/.cnvrg/config.yml")

    compression_path = "#{home_dir}/.cnvrg/tmp"
    config = {owner: owner, username: current_user, version_last_check: get_start_day(), api: url, compression_path: compression_path}
    File.open(home_dir+"/.cnvrg/config.yml", "w+") { |f| f.write config.to_yaml }
    say "Done"
  rescue
    say "ERROR", Thor::Shell::Color::RED
  end
end

#show_librariesObject



3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
# File 'lib/cnvrg/cli.rb', line 3443

def show_libraries
  begin
    verify_logged_in(true)
    log_start(__method__, args, options)
    system = options["system"] || false


    project_dir = is_cnvrg_dir()

    image = is_project_with_docker(project_dir)
    if image and image.is_docker
      container = image.get_container
      if !container
        say "Couldn't create container with image #{image.image_name}:#{image.image_tag}", Thor::Shell::Color::RED
        exit(1)
      end
    else
      say "Project is not configured with any image", Thor::Shell::Color::RED
      exit(1)

    end

    say "Showing python installed libraries", Thor::Shell::Color::BLUE
    pip_arr = image.get_installed_packages("python")
    printf "%-40s %-30s\n", "name", "version"
    printf "%-40s %-30s\n", "====", "======="

    pip_arr.each do |p|

      printf "%-40s %-30s\n", "#{p.split("==")[0]}", "#{p.split("==")[1]}"
    end
    if system

      say "Showing system installed libraries", Thor::Shell::Color::BLUE
      dpkg_arr = image.get_installed_packages("system")
      printf "%-40s %-30s\n", "name", "version"
      printf "%-40s %-30s\n", "====", "======="
      dpkg_arr.each do |p|
        printf "%-40s %-30s\n", "#{p.split("==")[0]}", "#{p.split("==")[1]}"

      end
    end
  rescue => e
    log_end(-1, e.message)
    say "Error occurred, aborting"
    if container
      container.stop()
    end
  rescue SignalException
    log_end(-1)
    say "Aborting"
    exit(1)
  end
end

#snap_dataObject



882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
# File 'lib/cnvrg/cli.rb', line 882

def snap_data
  begin
    verify_logged_in(false)
    log_start(__method__, args, options)

    owner = CLI.get_owner
    path = Dir.pwd
    @dataset = Dataset.new(path)

    log_end(0)

  rescue SignalException
    log_end(-1)

    say "\nAborting"
    exit(1)
  end
end

#statusObject



1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
# File 'lib/cnvrg/cli.rb', line 1620

def status
  begin
    verify_logged_in()
    log_start(__method__, args, options)
    @project = Project.new(get_project_home)
    new_branch = options["new_branch"] || false
    force = options["force"] || false

    result = @project.compare_idx(new_branch,force:force)["result"]
    commit = result["commit"]
    result = result["tree"]
    log_message("Comparing local changes with remote version:", Thor::Shell::Color::BLUE)

    if result["added"].empty? and result["updated_on_local"].empty? and result["updated_on_server"].empty? and result["deleted"].empty? and result["conflicts"].empty?
      log_message("Project is up to date", Thor::Shell::Color::GREEN)
      return true
    end
    if result["added"].size > 0
      log_message("Added files:\n", Thor::Shell::Color::BLUE)
      result["added"].each do |a|
        log_message("\t\tA:\t#{a}", Thor::Shell::Color::GREEN)
      end
    end

    if result["deleted"].size > 0
      log_message("Deleted files:\n", Thor::Shell::Color::BLUE)
      result["deleted"].each do |a|
        log_message("\t\tD:\t#{a}", Thor::Shell::Color::GREEN)
      end
    end
    if result["updated_on_local"].size > 0
      log_message("Local changes:\n", Thor::Shell::Color::BLUE)
      result["updated_on_local"].each do |a|
        log_message("\t\tM:\t#{a}", Thor::Shell::Color::GREEN)
      end
    end

    if result["updated_on_server"].size > 0
      log_message("Remote changes:\n", Thor::Shell::Color::BLUE)
      result["updated_on_server"].each do |a|
        log_message("\t\tM:\t#{a}", Thor::Shell::Color::GREEN)
      end
    end

    if result["conflicts"].size > 0
      log_message("Conflicted changes:\n", Thor::Shell::Color::BLUE)
      result["conflicts"].each do |a|
        log_message("\t\tC:\t#{a}", Thor::Shell::Color::RED)
      end
    end
  rescue SignalException
    say "\nAborting"
    exit(1)
  end
end

#stop_container(container_id) ⇒ Object



4252
4253
4254
4255
4256
4257
# File 'lib/cnvrg/cli.rb', line 4252

def stop_container(container_id)
  container = Docker::Container.get(container_id)
  container.stop()
  container.remove()

end

#sync(direct = true) ⇒ Object



2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
# File 'lib/cnvrg/cli.rb', line 2331

def sync(direct=true)
  verify_logged_in(true) if direct
  log_start(__method__, args, options)
  log_message('Checking for new updates from remote version', Thor::Shell::Color::BLUE, options["verbose"])
  log_message('Syncing project', Thor::Shell::Color::BLUE, !options["verbose"])
  if !options[:force]
    invoke :download, [], :new_branch => options["new_branch"], :verbose => options["verbose"], :sync => true
  end


  invoke :upload, [link=false, sync=true, direct=direct], :new_branch => options["new_branch"], :verbose => options["verbose"], :sync => true,
         :ignore => options[:ignore], :force=> options[:force]


end

#sync_image(docker = false) ⇒ Object



4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
# File 'lib/cnvrg/cli.rb', line 4086

def sync_image(docker=false)
  verify_logged_in(true)
  log_start(__method__, args, options)
  is_public = options["is_public"] || false
  is_base = options["is_base"] || false
  message = options["message"] || ""
  image_id = commit_image

  if docker
    message = "before running experiment"
    image = is_project_with_docker(Dir.pwd)
    if image and image.is_docker
      container = image.get_container
      if !container

        upload_image(image_id, is_public, is_base, message)
      else
        command = ["/bin/bash", "-lc", "cnvrg upload_image #{image_id} #{is_public} #{is_base} #{message}"]
        puts "Running in contianer"
        container.exec(command, detach: false)
      end
    end

  else
    upload_image(image_id, is_public, is_base, message)
  end

end

#tensor_port_container(container_id) ⇒ Object



4245
4246
4247
4248
# File 'lib/cnvrg/cli.rb', line 4245

def tensor_port_container(container_id)
  container = Docker::Container.get(container_id)
  say container.json["HostConfig"]["PortBindings"]["6006/tcp"][0]["HostPort"]
end

#testObject



163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/cnvrg/cli.rb', line 163

def test
  # image_settings = {
  #     'Image' => "cnvrg:latest",
  #     'User' => 'ds',
  #     'Cmd' => '/home/ds/run_ipython.sh',
  #     'ExposedPorts' => {
  #         '80/tcp' => {},
  #     },
  #     'HostConfig' => {
  #         'PortBindings' => {
  #             '80/tcp' => [
  #                 {'HostPort' => "7654", 'HostIp' => 'localhost'}
  #             ],
  #         },
  #     },
  # }
  # container = Docker::Container.get('b4d64bf83f41')
  # s = "/leah/1/2/3/4/5"
  # command = ["/bin/bash","-lc","sed -i 's#c.NotebookApp.base_url = .*#c.NotebookApp.base_url = \"#{s}\"#' /home/ds/.jupyter/jupyter_notebook_config.py"]
  # puts container.exec(command, tty: true)
end


1456
1457
1458
1459
1460
1461
1462
# File 'lib/cnvrg/cli.rb', line 1456

def unlink
  verify_logged_in(false)
  log_start(__method__, args, options)
  working_dir = is_cnvrg_dir()
  list_to_del = [working_dir+"/.cnvrgignore", working_dir+"/.cnvrg"]
  FileUtils.rm_rf list_to_del
end

#upload(link = false, sync = false, direct = false, ignore_list = "") ⇒ Object



1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
# File 'lib/cnvrg/cli.rb', line 1707

def upload(link=false, sync=false, direct=false, ignore_list="")

  begin
    verify_logged_in(true)
    log_start(__method__, args, options)

    @project = Project.new(get_project_home)

    @files = Cnvrg::Files.new(@project.owner, @project.slug)
    ignore = options[:ignore] || ""
    force = options[:force] || false

    if ignore.nil? or ignore.empty?
      ignore = ignore_list
    end
    data_ignore = data_dir_include()
    if !data_ignore.nil?
      if ignore.nil? or ignore.empty?
        ignore = data_ignore
      else
        ignore ="#{ignore},#{data_ignore}"
      end
    end
    if !@project.update_ignore_list(ignore)
      log_message("Couldn't append new ignore files to .cnvrgignore", Thor::Shell::Color::YELLOW)
    end
    new_branch = options["new_branch"] || false

    if options["sync"] or sync
      new_branch_exp = @project.get_new_branch
      if new_branch_exp
        new_branch = new_branch_exp
      end
    end

    result = @project.compare_idx(new_branch,force:force)
    commit = result["result"]["commit"]
    if !link
      if ((commit != @project.last_local_commit and !@project.last_local_commit.nil? and !result["result"]["tree"]["updated_on_server"].empty?) and !force )

        log_message("Remote server has an updated version, please run `cnvrg download` first, or alternatively: `cnvrg sync`", Thor::Shell::Color::BLUE)
        exit(1)
      end

      log_message("Comparing local changes with remote version:", Thor::Shell::Color::BLUE, (options["verbose"]))
    end
    result = result["result"]["tree"]
    # if result["added"].any? {|x| x.include? ".conflict"} or !result["conflicts"].empty?
    #   all = result["added"].select {|x| x.include? ".conflict"} +result["conflicts"].flatten
    #   if all.size == 1
    #     num = "conflict"
    #   else
    #     num =  "conflicts"
    #   end
    #   say "Project contains #{all.size} #{num}:", Thor::Shell::Color::RED
    #   say "#{all.join("\n")}"
    #   say "Please fix #{num}, and retry", Thor::Shell::Color::RED
    #   exit(1)
    #
    # end
    check = Helpers.checkmark()
    if result["added"].empty? and result["updated_on_local"].empty? and result["deleted"].empty?
      log_message("#{check} Project is up to date", Thor::Shell::Color::GREEN, (((options["sync"] or sync) and !direct) ? false : true))
      return true
    end
    update_count = 0
    update_total = result["added"].size + result["updated_on_local"].size + result["deleted"].size
    successful_updates = []
    successful_deletions = []
    if options["verbose"]
      if update_total == 1
        log_message("Updating #{update_total} file", Thor::Shell::Color::BLUE)
      else
        log_message("Updating #{update_total} files", Thor::Shell::Color::BLUE)
      end
    else
      log_message("Syncing files", Thor::Shell::Color::BLUE, ((options["sync"] or sync)) ? false : true)

    end
    # Start commit
    commit_sha1 = @files.start_commit(new_branch,force:force)["result"]["commit_sha1"]

    # upload / update
    begin

      parallel_options = {
          :progress => {
              :title => "Upload Progress",
              :progress_mark => '=',
              :format => "%b>>%i| %p%% %t",
              :starting_at => 0,
              :total => (result["added"] + result["updated_on_local"]).size,
              :autofinish => true
          },
          in_processes: ParallelProcesses,
          in_thread: ParallelThreads,
          isolation: true
      }
      if (result["added"] + result["updated_on_local"]).size > 0

        begin
          upload_result = Parallel.map((result["added"] + result["updated_on_local"]), parallel_options) do |f|
            absolute_path = "#{@project.local_path}/#{f}"
            relative_path = f.gsub(/^#{@project.local_path + "/"}/, "")
            if File.directory?(absolute_path)
              log_message("uploading dir: #{f}", Thor::Shell::Color::BLUE, options["verbose"])

              resDir = @files.create_dir(absolute_path, relative_path, commit_sha1)
              if resDir
                f
                # progressbar.increment
                update_count += 1
                successful_updates<< relative_path
              else
                log_message("Failed to upload directory: #{ relative_path }", Thor::Shell::Color::RED)

                raise Parallel::Kill
              end

            else
              log_message("uploading: #{f}", Thor::Shell::Color::BLUE, options["verbose"])

              res = @files.upload_file(absolute_path, relative_path, commit_sha1)
              if res
                f
                update_count += 1

                successful_updates<< relative_path
              else
                log_message("Failed to upload: #{ File.basename(absolute_path) }", Thor::Shell::Color::RED)

                raise Parallel::Kill

              end
            end
          end
        rescue SignalException
          log_message("Couldn't upload, Rolling Back all changes.", Thor::Shell::Color::RED)
          @files.rollback_commit(commit_sha1)

          exit(1)
        end
      end


      successful_updates = upload_result.to_a


      # delete

      deleted = update_deleted(result["deleted"])
      begin

        deleted_result = Parallel.map(deleted, in_processes: ParallelProcesses, in_thread: ParallelThreads) do |f|

          relative_path = f.gsub(/^#{@project.local_path + "/"}/, "")
          if relative_path.end_with?("/")
            log_message("deleting dir: #{f}", Thor::Shell::Color::RED, options["verbose"])

            if @files.delete_dir(f, relative_path, commit_sha1)
              f
            else
              log_message("Failed to delete directory: #{ f }", Thor::Shell::Color::RED)

            end
          else
            log_message("deleteing file: #{f}", Thor::Shell::Color::RED, options["verbose"])

            if @files.delete_file(f, relative_path, commit_sha1)
              f
            else
              log_message("Failed to delete file: #{ f }", Thor::Shell::Color::RED)

            end
          end
        end
      rescue Interrupt
        log_message("Couldn't upload, Rolling Back all changes.", Thor::Shell::Color::RED)
        @files.rollback_commit(commit_sha1)

        exit(1)

      end


      successful_deletions += successful_deletions.select { |x| not x.nil? }


      successful_updates = successful_updates.select { |x| not x.nil? }

      update_count = successful_updates.size

    rescue SignalException
      @files.rollback_commit(commit_sha1)
      say "User aborted, Rolling Back all changes.", Thor::Shell::Color::RED
      exit(0)
    rescue => e
      @files.rollback_commit(commit_sha1)
      log_message("Exception while trying to upload, Rolling back", Thor::Shell::Color::RED)
      log_error(e)
      exit(0)
    end
    if !result["deleted"].nil? and !result["deleted"].empty?
      update_count += result["deleted"].size
    end

    if update_count == update_total
      res = @files.end_commit(commit_sha1,force:force)
      if (Cnvrg::CLI.is_response_success(res, false))
        # save idx
        begin
          @project.update_idx_with_files_commits!((successful_deletions+successful_updates), res["result"]["commit_time"])

          @project.update_idx_with_commit!(commit_sha1)
        rescue => e
          @files.rollback_commit(commit_sha1)
          log_message("Couldn't commit updates, Rolling Back all changes.", Thor::Shell::Color::RED)
          log_error(e)
          exit(1)

        end
        image = is_project_with_docker(Dir.pwd)
        if image and image.is_docker
          image.update_image_activity(commit_sha1, nil)
        end

        if options["verbose"]
          log_message("#{check} Done", Thor::Shell::Color::BLUE)
          if successful_updates.size >0
            successful_updates.flatten!
            log_message("Updated:", Thor::Shell::Color::GREEN)
            suc = successful_updates.map { |x| x=Helpers.checkmark() +" "+x }
            log_message(suc.join("\n"), Thor::Shell::Color::GREEN)
          end
          if successful_deletions.size >0
            successful_deletions.flatten!

            log_message("Deleted:", Thor::Shell::Color::GREEN)
            del = successful_updates.map { |x| x=Helpers.checkmark() +" "+x }
            log_message(del.join("\n"), Thor::Shell::Color::GREEN)
          end
          log_message("Total of #{update_count} / #{update_total} files.", Thor::Shell::Color::GREEN)
        else
          if (options["sync"] or sync) and direct
            log_message("#{check} Syncing project completed successfully", Thor::Shell::Color::GREEN)

          else
            log_message("#{check} Changes were updated successfully", Thor::Shell::Color::GREEN)

          end

        end

      else
        @files.rollback_commit(commit_sha1)
        log_message("Error: couldn't commit changes,  Rolling Back all changes.", Thor::Shell::Color::RED)
      end
    else
      log_message("Error: uploaded only: #{update_count} / #{update_total}, \n Rolling back", Thor::Shell::Color::RED)

    end
  rescue => e

    log_message("Error occurred, \nAborting", Thor::Shell::Color::RED)
    log_error(e)
    @files.rollback_commit(commit_sha1) unless commit_sha1.nil?
    puts e.message

    exit(1)
  rescue SignalException

    say "\nAborting", Thor::Shell::Color::BLUE
    say "\nRolling back all changes", Thor::Shell::Color::BLUE
    @files.rollback_commit(commit_sha1) unless commit_sha1.nil?
    exit(1)
  end

end

#upload_cnvrg_image(image_path, image_name, secret) ⇒ Object



4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
# File 'lib/cnvrg/cli.rb', line 4500

def upload_cnvrg_image(image_path,image_name,secret)
  begin
  verify_logged_in(false)

  @files = Cnvrg::Files.new("", "")
  say "Uploading cnvrg  image file", Thor::Shell::Color::BLUE

  res = @files.upload_cnvrg_image(image_path, image_name, secret)
  if res
    say "Successfully uploaded cnvrg image file", Thor::Shell::Color::GREEN

  else
    say "Couldn't upload cnvrg image file", Thor::Shell::Color::RED
  end
  rescue => e
    puts e
    puts e.backtrace
  end


end

#upload_data(sync = false, direct = false) ⇒ Object



1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
# File 'lib/cnvrg/cli.rb', line 1035

def upload_data(sync=false, direct=false)

  begin
    verify_logged_in(true)
    log_start(__method__, args, options)
    dataset_dir = is_cnvrg_dir(Dir.pwd)
    @dataset = Dataset.new(dataset_dir)

    @files = Cnvrg::Datafiles.new(@dataset.owner, @dataset.slug)
    ignore = options[:ignore] || []
    if !@dataset.update_ignore_list(ignore)
      log_message("Couldn't append new ignore files to .cnvrgignore", Thor::Shell::Color::YELLOW)
    end
    result = @dataset.compare_idx(false)

    commit = result["result"]["commit"]
    if commit != @dataset.last_local_commit and !@dataset.last_local_commit.nil? and !result["result"]["tree"]["updated_on_server"].empty?

      log_message("Remote server has an updated version, please run `cnvrg download` first, or alternatively: `cnvrg sync`", Thor::Shell::Color::BLUE)
      exit(1)
    end

    log_message("Comparing local changes with remote version:", Thor::Shell::Color::BLUE, options["verbose"] ? true : false)
    result = result["result"]["tree"]
    # if result["added"].any? {|x| x.include? ".conflict"} or !result["conflicts"].empty?
    #   all = result["added"].select {|x| x.include? ".conflict"} +result["conflicts"].flatten
    #   if all.size == 1
    #     num = "conflict"
    #   else
    #     num =  "conflicts"
    #   end
    #   say "Project contains #{all.size} #{num}:", Thor::Shell::Color::RED
    #   say "#{all.join("\n")}"
    #   say "Please fix #{num}, and retry", Thor::Shell::Color::RED
    #   exit(1)
    #
    # end
    check = Helpers.checkmark()

    if result["added"].empty? and result["updated_on_local"].empty? and result["deleted"].empty?
      log_message("#{check} Dataset is up to date", Thor::Shell::Color::GREEN, (((options["sync"] or sync) and !direct) ? false : true))
      return true
    end
    update_count = 0
    update_total = result["added"].size + result["updated_on_local"].size + result["deleted"].size
    successful_updates = []
    successful_deletions = []
    if options["verbose"]
      if update_total == 1
        log_message("Updating #{update_total} file", Thor::Shell::Color::BLUE)
      else
        log_message("Updating #{update_total} files", Thor::Shell::Color::BLUE)
      end
    else
      log_message("Syncing files", Thor::Shell::Color::BLUE, ((options["sync"] or sync)) ? false : true)

    end

    # Start commit

    commit_sha1 = @files.start_commit(false)["result"]["commit_sha1"]
    # upload / update
    begin
      (result["added"] + result["updated_on_local"]).each do |f|
        absolute_path = "#{@dataset.local_path}/#{f}"
        relative_path = f.gsub(/^#{@dataset.local_path + "/"}/, "")
        if File.directory?(absolute_path)
          resDir = @files.create_dir(absolute_path, relative_path, commit_sha1)
          if resDir
            update_count += 1
            successful_updates<< relative_path
          end
        else
          res = @files.upload_file(absolute_path, relative_path, commit_sha1)

          if res
            update_count += 1
            successful_updates<< relative_path
          else
            @files.rollback_commit(commit_sha1)
            log_message("Couldn't upload, Rolling Back all changes.", Thor::Shell::Color::RED)
            exit(0)
          end
        end
      end

      # delete
      deleted = update_deleted(result["deleted"])
      deleted.each do |f|
        relative_path = f.gsub(/^#{@dataset.local_path + "/"}/, "")
        if relative_path.end_with?("/")
          if @files.delete_dir(f, relative_path, commit_sha1)
            # update_count += 1
            successful_updates<< relative_path
          end
        else
          if @files.delete_file(f, relative_path, commit_sha1)
            # update_count += 1
            successful_updates<< relative_path
          end
        end
      end

    rescue SignalException
      @files.rollback_commit(commit_sha1)
      say "User aborted, Rolling Back all changes.", Thor::Shell::Color::RED
      exit(0)
    rescue => e
      log_message("Exception while trying to upload, Rolling back", Thor::Shell::Color::RED)
      log_error(e)
      @files.rollback_commit(commit_sha1)
      exit(0)
    end
    if !result["deleted"].nil? and !result["deleted"].empty?
      update_count += result["deleted"].size
    end
    if update_count == update_total
      res = @files.end_commit(commit_sha1)
      if (Cnvrg::CLI.is_response_success(res, false))
        # save idx
        begin
          @dataset.update_idx_with_files_commits!((successful_deletions+successful_updates), res["result"]["commit_time"])

          @dataset.update_idx_with_commit!(commit_sha1)
        rescue => e
          log_message("Couldn't commit updates, Rolling Back all changes.", Thor::Shell::Color::RED)
          log_error(e)
          @files.rollback_commit(commit_sha1)
          exit(1)

        end
        if options["verbose"]
          log_message("#{check} Done", Thor::Shell::Color::BLUE)
          if successful_updates.size >0
            log_message("Updated:", Thor::Shell::Color::GREEN)
            suc = successful_updates.map { |x| x=Helpers.checkmark() +" "+x }
            log_message(suc.join("\n"), Thor::Shell::Color::GREEN)
          end
          if successful_deletions.size >0
            log_message("Deleted:", Thor::Shell::Color::GREEN)
            del = successful_updates.map { |x| x=Helpers.checkmark() +" "+x }
            log_message(del.join("\n"), Thor::Shell::Color::GREEN)
          end
          log_message("Total of #{update_count} / #{update_total} files.", Thor::Shell::Color::GREEN)
        else
          if (options["sync"] or sync) and direct
            log_message("#{check} Syncing dataset completed successfully", Thor::Shell::Color::GREEN)

          else
            log_message("#{check} Changes were updated successfully", Thor::Shell::Color::GREEN)

          end

        end

      else
        @files.rollback_commit(commit_sha1)
        log_message("Error: Couldn't commit. \nRolling Back all changes.", Thor::Shell::Color::RED)
      end
    else
      log_message("Error: Uploaded only #{update_count}/#{update_total} files, \nRolling back", Thor::Shell::Color::RED)

      @files.rollback_commit(commit_sha1)
    end
  rescue => e
    log_message("Error occurd, \nAborting", Thor::Shell::Color::RED)
    log_error(e)

    @files.rollback_commit(commit_sha1)
    exit(1)
  rescue SignalException

    say "\nAborting", Thor::Shell::Color::BLUE
    say "\nRolling back all changes", Thor::Shell::Color::BLUE
    @files.rollback_commit(commit_sha1)
    exit(1)
  end

end

#upload_data_tar(ignore, verbose, sync, no_compression) ⇒ Object



1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
# File 'lib/cnvrg/cli.rb', line 1222

def upload_data_tar(ignore, verbose, sync, no_compression)

  begin
    verify_logged_in(true)
    log_start(__method__, args, options)
    dataset_dir = is_cnvrg_dir(Dir.pwd)

    @dataset = Dataset.new(dataset_dir)

    @files = Cnvrg::Datafiles.new(@dataset.owner, @dataset.slug)
    if !@dataset.update_ignore_list(ignore)
      log_message("Couldn't append new ignore files to .cnvrgignore", Thor::Shell::Color::RED)
      exit(1)
    end
    log_message("Checking dataset", Thor::Shell::Color::BLUE)
    local_idx = @dataset.generate_idx
    result = @dataset.compare_idx(false, commit=@dataset.last_local_commit, local_idx= local_idx)


    commit = result["result"]["commit"]
    if commit != @dataset.last_local_commit and !@dataset.last_local_commit.nil? and !result["result"]["tree"]["updated_on_server"].empty?

      log_message("Remote server has an updated version, please run `cnvrg data download` first", Thor::Shell::Color::BLUE)
      exit(1)
    end

    log_message("Comparing local changes with remote version:", Thor::Shell::Color::BLUE, verbose)
    result = result["result"]["tree"]
    check = Helpers.checkmark()

    if result["added"].empty? and result["updated_on_local"].empty? and result["deleted"].empty?
      log_message("#{check} Dataset is up to date", Thor::Shell::Color::GREEN, (sync ? false : true))
      return true
    end
    update_count = 0
    update_total = result["added"].size + result["updated_on_local"].size + result["deleted"].size
    successful_updates = []
    successful_deletions = []

    # Start commit
    res = @files.start_commit(false)["result"]
    commit_sha1 =res["commit_sha1"]
    commit_time = res["commit_time"]
    # upload / update
    begin
      (result["added"] + result["updated_on_local"]).each do |f|
        relative_path = f.gsub(/^#{@dataset.local_path + "/"}/, "")
        successful_updates<< relative_path
        update_count += 1
      end

      # delete
      deleted = update_deleted(result["deleted"])
      deleted.each do |f|
        relative_path = f.gsub(/^#{@dataset.local_path + "/"}/, "")
        successful_updates<< relative_path
      end
      @dataset.update_idx_with_files_commits!((successful_deletions+successful_updates), commit_time)

      @dataset.update_idx_with_commit!(commit_sha1)
      log_message("Compressing data", Thor::Shell::Color::BLUE)

      home_dir = File.expand_path('~')
      compression_path = get_compression_path
      tar_path = "#{compression_path}#{@dataset.slug}_#{commit_sha1}.tar.gz"
      tar_files_path = "#{home_dir}/.cnvrg/tmp/#{@dataset.slug}_#{commit_sha1}.txt"
      tar_files = (result["added"] + result["updated_on_local"]).join("\n")
      File.open(tar_files_path, 'w') { |f| f.write tar_files }
      is_tar = create_tar(dataset_dir, tar_path, tar_files_path, no_compression)
      if !is_tar
        log_message("ERROR: Couldn't compress data", Thor::Shell::Color::RED)
        FileUtils.rm_rf([tar_path]) if File.exist? tar_path
        FileUtils.rm_rf([tar_files_path]) if File.exist? tar_files_path
        @files.rollback_commit(commit_sha1)
        log_message("Rolling Back all changes.", Thor::Shell::Color::RED)
        exit(1)
      end
      log_message("Uploading data", Thor::Shell::Color::BLUE)
      log_file = "#{home_dir}/.cnvrg/tmp/upload_#{File.basename(tar_path)}.log"
      res = false
      res = @files.upload_tar_file(tar_path, tar_path, commit_sha1)

      if res
        log_message("Commiting data", Thor::Shell::Color::BLUE)

        cur_idx = @dataset.get_idx.to_h

        res = @files.end_commit_tar(commit_sha1, cur_idx)
        if !Cnvrg::CLI.is_response_success(res, false)
          FileUtils.rm_rf([tar_files_path]) if File.exist? tar_files_path
          FileUtils.rm_rf([tar_path]) if File.exist? tar_path


          @files.rollback_commit(commit_sha1)
          log_message("Can't commit, Rolling Back all changes.", Thor::Shell::Color::RED)
          exit(1)
        end

      else
        if File.exist? log_file
          @files.upload_data_log_file(log_file, log_file, commit_sha1)
        end


        FileUtils.rm_rf([tar_files_path]) if File.exist? tar_files_path
        FileUtils.rm_rf([tar_path]) if File.exist? tar_path


        @files.rollback_commit(commit_sha1)
        log_message("Can't upload, Rolling Back all changes.", Thor::Shell::Color::RED)
        log_message("Upload error log: #{log_file}", Thor::Shell::Color::RED)

        exit(1)
      end


      # delete
      FileUtils.rm_rf([tar_path, tar_files_path])

    rescue SignalException
      FileUtils.rm_rf([tar_files_path]) if File.exist? tar_files_path
      FileUtils.rm_rf([tar_path]) if File.exist? tar_path
      if File.exist? log_file
        @files.upload_data_log_file(log_file, log_file, commit_sha1)
      end


      @files.rollback_commit(commit_sha1)
      say "User aborted, Rolling Back all changes.", Thor::Shell::Color::RED
      exit(0)
    rescue => e
      log_error(e)
      if !Cnvrg::Helpers.internet_connection?
        say "Seems there is no internet connection", Thor::Shell::Color::RED

      end
      if File.exist? log_file
        @files.upload_data_log_file(log_file, log_file, commit_sha1)
      end
      FileUtils.rm_rf([tar_files_path]) if File.exist? tar_files_path
      FileUtils.rm_rf([tar_path]) if File.exist? tar_path

      @files.rollback_commit(commit_sha1)
      log_message("Exception while trying to upload, \nRolling back,\n look at the log for more details", Thor::Shell::Color::RED)
      log_message("Error log: #{log_file}", Thor::Shell::Color::RED)


      exit(0)
    end
    log_message("#{check} Changes were updated successfully", Thor::Shell::Color::GREEN)


  rescue => e

    puts e.message
    puts e.backtrace
    log_message("Error occurred, \nAborting", Thor::Shell::Color::RED)
    log_error(e)
    @files.rollback_commit(commit_sha1)
    exit(1)
  rescue SignalException

    say "\nAborting", Thor::Shell::Color::BLUE
    say "\nRolling back all changes", Thor::Shell::Color::BLUE
    @files.rollback_commit(commit_sha1)
    exit(1)
  end


end

#upload_image(image_id, is_public, is_base, *message) ⇒ Object



4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
# File 'lib/cnvrg/cli.rb', line 4157

def upload_image(image_id, is_public, is_base, *message)
  verify_logged_in(true)
  log_start(__method__, args, options)
  image = Docker::Image.get(image_id)
  project_home = get_project_home
  @project = Project.new(project_home)
  last_local_commit = @project.last_local_commit
  image_name = @project.slug+"#{last_local_commit}"
  path = File.expand_path('~')+"/.cnvrg/tmp/#{image_name}.tar"
  owner = Cnvrg::CLI.get_owner()
  if !message.nil? or !message.empty?
    message = message.join(" ")
  end

  log_message("Saving image's current state", Thor::Shell::Color::BLUE)
  image.save(path)

  begin
    log_message("Compressing image file to upload", Thor::Shell::Color::BLUE)
    gzipRes = system("gzip -f #{path}")
    if !gzipRes

      log_message("Couldn't create tar file from image", Thor::Shell::Color::RED)
      exit(1)
    end
    path = path+".gz"
    @files = Cnvrg::Files.new(owner, "")

    exit_status = $?.exitstatus
    if exit_status == 0
      log_message("Uploading image file", Thor::Shell::Color::BLUE)

      diff =container_changes(Dir.pwd)
      res = @files.upload_image(path, image_name, owner, is_public, is_base, diff[1], diff[0], diff[2], message, image.commit_id)
      if res
        File.delete(path)
        image_loc = is_project_with_docker(Dir.pwd)
        image_loc.update_slug(res["result"]["id"])

        checks = Helpers.checkmark()
        log_message("#{checks} Done", Thor::Shell::Color::GREEN)
      else
        log_message("Couldn't upload image", Thor::Shell::Color::RED)

      end
    else
      log_message("Couldn't create image file for: #{image_name}", Thor::Shell::Color::RED)
      exit(1)
    end
  rescue => e
    log_message("Couldn't upload image file for: #{image_name}", Thor::Shell::Color::RED)
    log_error(e)
  rescue SignalException

    say "Couldn't upload image file for: #{image_name}", Thor::Shell::Color::RED
    exit(1)
  end
end

#upload_logObject



4218
4219
4220
4221
4222
4223
# File 'lib/cnvrg/cli.rb', line 4218

def upload_log()
  log_path = '/home/ds/app/uwsgi.log'
  loglines = File.new(log_path).readlines
  logs = loglines.select { |x| x.start_with? "cnvrg_app:" }.collect { |x| x.strip }

end

#versionObject



188
189
190
191
# File 'lib/cnvrg/cli.rb', line 188

def version
  puts Cnvrg::VERSION

end