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)


155
156
157
158
# File 'lib/cnvrg/cli.rb', line 155

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

Instance Method Details

#build(*cmd) ⇒ Object



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
4767
4768
4769
4770
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
# File 'lib/cnvrg/cli.rb', line 4734

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



4607
4608
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
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
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 4607

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



1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
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
# File 'lib/cnvrg/cli.rb', line 1665

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"]
    git = response["git"] || false

    commit_to_clone = options["commit"] || nil

    log_message("Cloning #{project_name}", Thor::Shell::Color::BLUE)
    clone_resp = false
    project_home = Dir.pwd

    if remote and !git
      clone_resp = Project.clone_dir_remote(slug, owner, project_name,git)
    elsif git
      if remote
        clone_resp = Project.clone_dir_remote(slug, owner, project_name,git)
      else
        project_home += "/#{project_name}"
        clone_resp = Project.clone_dir(slug, owner, project_name,git)

      end

      # idx_status = Project.new(project_home).generate_idx
      # log_message("Cloned project #{project_name} successfully", Thor::Shell::Color::GREEN)

    else
      if (Dir.exists? project_name)
        # project_name = "#{project_name}_#{rand(1 .. 5000000000)}"
        # puts 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,git)
      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
      idx = {commit: response["result"]["commit"], tree: response["result"]["tree"]}
      File.open(working_dir + "/.cnvrg/idx.yml", "w+") {|f| f.write idx.to_yaml}

      log_message("Downloading files", Thor::Shell::Color::BLUE)
      files = response["result"]["files"]

      if !files.nil?
        begin
          download_result = @files.download_multpile_files_s3(files, project_home)

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

          @files.revoke_clone(project_home)
          return
        end
        Project.verify_cnvrgignore_exist(project_name, remote)
        if !download_result.is_success?
          log_message(download_result.e_msg, download_result.msg_color, false)
          log_message(download_result.e_msg_backtrace, download_result.msg_color, false)

          @files.revoke_clone(project_home)
        end
        log_message(download_result.msg, download_result.msg_color)
      else
        current_commit = response["result"]["commit"]
        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
          successful_changes =[]
          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
          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
        rescue Interrupt
          log_message("Couldn't download, Rolling Back all changes.", Thor::Shell::Color::RED)

          @files.revoke_clone(project_home)
          return
        end
        end


      end

    else

      log_message("Error: Couldn't clone: #{project_name}", Thor::Shell::Color::RED)
      @files.revoke_clone(project_home)

      return
    end
  rescue SignalException
    say "\nAborting"
    @files.revoke_clone(project_home)

    return
  end

end

#clone_data(dataset_url, only_tree = false, commit = nil, query = nil) ⇒ Object



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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
# File 'lib/cnvrg/cli.rb', line 801

def clone_data(dataset_url,only_tree=false,commit=nil,query=nil)
  begin
    verify_logged_in(false)
    log_start(__method__, args, options)
    commit = options["commit"] || commit
    only_tree = options["only_tree"] || only_tree


    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", 'POST',{ commit: commit, query:query})
    Cnvrg::CLI.is_response_success(response,true)
    dataset_name = response["result"]["name"]
    dataset_home = Dir.pwd+"/"+dataset_name
    if (Dir.exists? dataset_name)
      log_message("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
    check = Helpers.checkmark
    if Dataset.clone(owner, dataset_name, slug)
      log_message("Cloning #{dataset_name}", Thor::Shell::Color::BLUE)
      @files = Cnvrg::Datafiles.new(owner, slug)
      log_message("Downloading files", Thor::Shell::Color::BLUE)
      # if not(query.nil? or query.empty?)
      #   @files.download_list_files_in_query(response["result"]["list_files"],dataset_home)

      #   log_message("#{check} Clone finished successfully", Thor::Shell::Color::GREEN)
      #   return

      # end
      commit = response["result"]["commit"]
      files_count = response["result"]["file_count"]
      files = @files.get_clone_chunk(commit: commit)
      downloaded_files = 0
      progressbar = ProgressBar.create(:title => "Download Progress",
                                       :progress_mark => '=',
                                       :format => "%b>>%i| %p%% %t",
                                       :starting_at => 0,
                                       :autofinish => true)
      while files['keys'].length > 0
        @files.download_multiple_files_s3(files, dataset_home)
        downloaded_files += files['keys'].length
        progressbar.progress = (downloaded_files * 100 / files_count)
        files = @files.get_clone_chunk(commit: commit, latest_id: files['latest'])
      end
      if downloaded_files == files_count
        Dataset.verify_cnvrgignore_exist(dataset_name, false)
        @dataset = Dataset.new(dataset_home)
        @dataset.write_idx(nil, commit)
        log_message("#{check} Clone finished successfully", Thor::Shell::Color::GREEN)
      else
        log_message(result.msg, result.msg_color)
      end
    else
      log_message("Error: Couldn't create directory: #{dataset_name}", Thor::Shell::Color::RED)
      exit(1)
    end
  rescue SignalException
    say "\nAborting"
    exit(1)
  end
end

#clone_data_query(dataset_url, query = nil) ⇒ Object



872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
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
# File 'lib/cnvrg/cli.rb', line 872

def clone_data_query(dataset_url,query=nil)
  begin
    verify_logged_in(false)
    log_start(__method__, args, options)
    query = options["query"] || query
    if !query.present?
      log_message("Argument missing : query", Thor::Shell::Color::RED)
      exit(1)
    end

    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}/search/#{query}", 'GET')
    Cnvrg::CLI.is_response_success(response,true)
    dataset_name = response["results"]["name"]
    dataset_slug = response["results"]["slug"]
    # dataset_home = Dir.pwd+"/"+dataset_name
    dataset_home = Dir.pwd

    if Dataset.blank_clone(owner, dataset_name, dataset_slug)
      dataset = Dataset.new(dataset_home)
      log_message("Cloning #{dataset_name}", Thor::Shell::Color::BLUE)
      parallel_options = {
          :progress => {
              :title => "Download Progress",
              :progress_mark => '=',
              :format => "%b>>%i| %p%% %t",
              :starting_at => 0,
              :total => response["results"]["query_files"].size,
              :autofinish => true
          },
          in_threads: ParallelThreads
      }
      begin
        log_message("Downloading files", Thor::Shell::Color::BLUE)
        Parallel.map((response["results"]["query_files"]), parallel_options) do |f|
          relative_path = f["fullpath"].gsub(/^#{dataset_home}/, "")
          relative_path_dir = relative_path.split("/")
          file_name = relative_path_dir.pop()
          relative_path_dir = relative_path_dir.join("/")
          abs_path = dataset_home + "/" + relative_path_dir
          begin
            FileUtils.mkdir_p(abs_path) unless File.exist? (abs_path + "/" + file_name)
          rescue
            log_message("Could not create directory: #{abs_path}", Thor::Shell::Color::RED)
            exit(1)
          end
          begin
            File.write "#{abs_path}/#{file_name}", open(f["s3_url"]).read unless File.exist? (abs_path + "/" + file_name)
          rescue
            log_message("Could not download file: #{f["fullpath"]}", Thor::Shell::Color::RED)
            exit(1)
          end

        end
      rescue Interrupt
        log_message("Couldn't download", Thor::Shell::Color::RED)
        exit(1)
      end
      begin
        dataset.generate_idx()
        check = Helpers.checkmark
        log_message("#{check} Clone finished successfully", Thor::Shell::Color::GREEN)
      rescue
          exit(1)
      end
    end
  rescue SignalException
    say "\nAborting"
    exit(1)
  end
end

#commit_imageObject



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

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



5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
# File 'lib/cnvrg/cli.rb', line 5180

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



5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
# File 'lib/cnvrg/cli.rb', line 5232

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



5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
# File 'lib/cnvrg/cli.rb', line 5098

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



5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
# File 'lib/cnvrg/cli.rb', line 5033

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



5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
# File 'lib/cnvrg/cli.rb', line 5119

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



1508
1509
1510
1511
1512
1513
1514
1515
# File 'lib/cnvrg/cli.rb', line 1508

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



998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
# File 'lib/cnvrg/cli.rb', line 998

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



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
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
# File 'lib/cnvrg/cli.rb', line 3161

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

#delete_data(dataset_slug) ⇒ Object



772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
# File 'lib/cnvrg/cli.rb', line 772

def delete_data(dataset_slug)
  begin
    verify_logged_in(false)
    log_start(__method__, args, options)
      owner = CLI.get_owner
    response = Dataset.delete(dataset_slug, owner)

    if Cnvrg::CLI.is_response_success(response)
      log_message("Successfully deleted dataset: #{dataset_slug}", Thor::Shell::Color::GREEN)
    else
      log_message("Error while tying to delete dataset: #{response["messages"]}", Thor::Shell::Color::RED)


    end

  rescue => e
    log_error(e)
  rescue SignalException

    say "\nAborting"
    exit(1)
  end
end

#deploy(file_to_run, function) ⇒ Object



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

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"] || ""
      title = options['title']

      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
      image = Images.new(working_dir, "cnvrg")
      image_slug = image.image_slug
    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, title)

    if Cnvrg::CLI.is_response_success(res)

        check = Helpers.checkmark()
        log_message("#{check} Deployment process is on: #{Cnvrg::Helpers.remote_url}/#{project.owner}/projects/#{project.slug}/endpoints/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
    sleep(20) # end cycle

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

    exit(1)
  end
end

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



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
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
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
# File 'lib/cnvrg/cli.rb', line 2854

def download(sync = false, ignore_list = "", in_exp=false)
  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, commit: nil, in_exp: in_exp)["result"]
    result = res["tree"]

    commit = res["commit"]
    if result["updated_on_server"].empty? and result["conflicts"].empty? and result["deleted"].empty?
      if !@project.last_local_commit.eql? commit
        @project.update_idx_with_commit!(commit)
      end
      log_message("Project is up to date", Thor::Shell::Color::GREEN, ((options["sync"] or sync) ? false : true))
      return true
    end
    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 relative_path.eql? ".cnvrgignore"
            if @files.download_file_s3(f, relative_path, project_home, commit_sha1 = nil, conflict = false)
              f
            else
              log_message("Couldn't download: #{f}", Thor::Shell::Color::RED)
              raise Parallel::Kill
            end
          else
            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
        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



5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
# File 'lib/cnvrg/cli.rb', line 5293

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



5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
# File 'lib/cnvrg/cli.rb', line 5379

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



1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
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
# File 'lib/cnvrg/cli.rb', line 1014

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_data_new(verbose = false, new_branch = false, sync = false, commit = nil, all_files = true) ⇒ Object



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

def download_data_new(verbose=false, new_branch=false,sync=false, commit=nil,all_files=true)
  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)
    commit_to_download = commit
    local_idx = @dataset.generate_idx
    all_files = all_files
    res = @dataset.compare_idx_download(commit=commit_to_download.presence, local_idx= local_idx,all_files=all_files)
    result = res["result"]["tree"]
    commit = res["result"]["commit"]
    if result["updated_on_server"].empty? and result["conflicts"].empty? and result["deleted"].empty?
      log_message("Dataset is up to date", Thor::Shell::Color::GREEN, ((options["sync"] or sync) ? false : true))
      return true
    end
    update_total = result["updated_on_server"].size + result["conflicts"].size + result["deleted"].size
    successful_changes = 0
    if update_total ==1
      log_message("Downloading #{update_total} file", Thor::Shell::Color::BLUE, !sync)
    elsif update_total == 0
      log_message("Dataset is up to date", Thor::Shell::Color::GREEN, !sync)
      return true
    elsif options["verbose"]
      log_message("Downloading #{update_total} files", Thor::Shell::Color::BLUE)
    else
      log_message("Syncing Dataset", Thor::Shell::Color::BLUE, !sync)
    end
    update_res = @files.download_files_in_chunks(result["updated_on_server"]) if result["updated_on_server"].present?
    conflict_res = @files.download_files_in_chunks(result["conflicts"], conflict: true) if result["conflicts"].present?
    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)
      exit(1)
    end
    if [update_res.is_success?, delete_res.is_success?, (conflict_res.blank? or conflict_res.is_success?)].all?
      # update idx with latest commit
      @dataset.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
      return true
    end
  rescue => e
    log_message("Error occurred, \nAborting", Thor::Shell::Color::BLUE)
    log_error(e)
    exit(1)
  rescue SignalException
    say "\nAborting", Thor::Shell::Color::BLUE
    exit(1)
  end
end

#download_file_data(file_path, *dataset_path) ⇒ Object



2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
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
# File 'lib/cnvrg/cli.rb', line 2692

def download_file_data(file_path, *dataset_path)

  verify_logged_in(true)
  log_start(__method__, args, options)
  begin
    if dataset_path.nil? or dataset_path.empty?
      dataset_path = Dir.pwd
    elsif dataset_path.is_a? Array
      dataset_path = dataset_path[0]
    end
    dataset_dir = is_cnvrg_dir(dataset_path)
    @dataset = Dataset.new(dataset_dir)
    @files = Cnvrg::Datafiles.new(@dataset.owner, @dataset.slug)
    commit_to_download = options["commit"] || nil
    as_link  = options["link"] || false
    download_path = options["path"]
    remote = options["remote"]
    as_json = options["json"]
    if remote
      download_path = "/data/#{@dataset.title}/"

    else
      download_path = dataset_dir
    end
    if !as_json

      log_message("Downloading file", Thor::Shell::Color::BLUE)

    end
    res = @files.download_file_s3(file_path, file_path, download_path, conflict=false, commit_sha1=commit_to_download, as_link=as_link)
    if as_link
      puts res
    else
      if res
        if as_json
          response = {"status":"success"}
          puts response.to_json
        else
          log_message("#{Helpers.checkmark()} File #{file_path} was successfully downloaded", Thor::Shell::Color::GREEN)

        end
      end


    end

  rescue =>e
    log_message("Error occurred, \nAborting", Thor::Shell::Color::BLUE)
    log_error(e)
    exit(1)
  end
end

#download_image(image_name, image_slug) ⇒ Object



5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
# File 'lib/cnvrg/cli.rb', line 5330

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

#download_in_git(commit_sha1) ⇒ Object



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

def download_in_git(commit_sha1)
  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)
    res = @project.git_download_commit(commit_sha1)
    files =  res.try(:fetch, "result").try(:fetch, "files")
    if files.blank?
      log_message("No files to download", Thor::Shell::Color::RED)
      return
    end

    begin
      download_result = @files.download_multiple_files_s3(files, project_home)
      if download_result
        log_message("Done.\nDownloaded  finished successfully", Thor::Shell::Color::GREEN)
      else
        log_message("Error while trying to download\n", Thor::Shell::Color::RED)

      end

        rescue => e
      log_error(e)
      puts e.backtrace
      log_message("Error while trying to download ", Thor::Shell::Color::RED)
      return
    end

  end
end

#download_tags_yamlObject



1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
# File 'lib/cnvrg/cli.rb', line 1552

def download_tags_yaml
  verify_logged_in(false)
  log_start(__method__, args, options)
  dataset_dir = is_cnvrg_dir(Dir.pwd)
  @dataset = Dataset.new(dataset_dir)
  status = @dataset.download_tags_yaml()
  if status
    log_message("Downloaded tags yaml successfully", Thor::Shell::Color::GREEN)
  else
    log_message("Unable to download", Thor::Shell::Color::RED)
  end
end

#end_commit_data(commit) ⇒ Object



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

def end_commit_data(commit)
  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)
    force = options["force"] || false
    resp = @files.end_commit(commit, force, options[:success])
    if (resp and resp["result"])
      if  !options[:success]
        @dataset.set_next_commit(resp["result"]["commit_sha1"])
        @dataset.remove_next_commit
      else
        check = Helpers.checkmark
        @dataset.set_next_commit(commit)
        @dataset.remove_next_commit
        log_message("#{check} Data files were updated successfully", Thor::Shell::Color::GREEN)
      end

      end


  rescue => e
    puts e
  rescue SignalException
    @dataset.set_next_commit(commit)
    log_message("Aborting", Thor::Shell::Color::YELLOW)
    exit(1)
  end

end

#exec(*cmd) ⇒ Object



3372
3373
3374
3375
3376
3377
3378
3379
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
3439
3440
3441
3442
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
3497
3498
3499
3500
3501
3502
3503
3504
3505
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
# File 'lib/cnvrg/cli.rb', line 3372

def exec(*cmd)
  log = []
  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]
  sync_before_terminate = options["sync_before_terminate"]
  periodic_sync = options["periodic_sync"]
  email_notification = options["email_notification"]
  output_dir = options['output_dir'] || "output"
  project_home = get_project_home
  data_query = options["data_query"]
  @project = Project.new(project_home)
  if @project.is_git
    sync_before = false
  end
  # is_new_branch = @project.compare_commit(commit)
  is_new_branch = false
  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, sync_before_terminate, periodic_sync)
      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

          if remote
            if @exp.sync_before_terminate
              spot_status_thread = Thread.new do
                begin
                  loop do
                    log_message('Checking Spot Instance Status', Thor::Shell::Color::YELLOW)
                    restart = @exp.restart_spot_instance()

                    if restart
                      log_message('Spot instance is going to be terminated', Thor::Shell::Color::YELLOW)
                      # sync
                      if @project.is_git
                        output_dir = @exp.output_dir

                        if output_dir.blank?
                          output_dir = "output"
                        end
                        upload(false, false, true, ignore, true, true,output_dir,"Experiment",@exp.slug  )
                      else
                        upload(false, false, true, ignore, true, true,nil,"Experiment",@exp.slug  )
                      end
                        res = @exp.send_restart_request(@project.get_idx.try(:fetch, :commit))
                      while !Cnvrg::CLI.is_response_success(res, false) do
                        sleep(5)
                        res = @exp.send_restart_request(@project.get_idx.try(:fetch, :commit))
                      end
                      exit(0)
                    end
                    sleep(10)
                  end
                rescue => e
                  log_error(e)
                end
              end
            end
          end
          process_running = true
          stats_thread = Thread.new do
            while process_running do
              sleep 30
              begin
                stats = remote ? usage_metrics_in_docker(docker_id) : Helpers.linux? ? {memory: memory_usage, cpu: cpu_usage} : {}
                if is_on_gpu
                  gu = gpu_util
                  stats['gpu'] = gu[0]
                  stats['gpu_util'] = gu[1]
                end
                @exp.send_machine_stats [stats] unless stats.empty?
              rescue => e
                log_error(e)
                log_message("Failed to upload ongoing stats, continuing with experiment", Thor::Shell::Color::YELLOW)
              end
            end
          end
          start_time = Time.now
          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
                if log.size >= 15
                  @exp.upload_temp_log(log) unless log.empty?
                  log = []
                  elsif (start_time + 30.seconds) <= Time.now
                  @exp.upload_temp_log(log) unless log.empty?
                  log = []
                  start_time = Time.now
                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)
              if !log.empty?
                temp_log = log
                @exp.upload_temp_log(temp_log) unless temp_log.empty?
                log -= temp_log
              end
            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, 0, 0)
              log_message("Error occurred,aborting", Thor::Shell::Color::RED)
              log_error(e)
              exit(0)
            end
            ::Process.wait pid
          end
          process_running = false

          if !log.empty?

            temp_log = log
              @exp.upload_temp_log(temp_log) unless temp_log.empty?
            log -= temp_log
          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 sync_after
            # Sync after run
              if @project.is_git
                output_dir = output_dir || @exp.output_dir
                if output_dir.present?
                  upload(false, false, true, ignore, true, true,output_dir,"Experiment",@exp.slug  )
                  # invoke :upload, [false, false, true, ignore, true, true], :output_dir => output_dir, :force=>true, :job_type=>'Experiment', :job_slug=>@exp.slug
                end
              else
                upload(false, false, true, ignore, true, true,nil,"Experiment",@exp.slug  )

                # invoke :upload, [false, false, true, ignore,true, true], :job_type=>'Experiment', :job_slug=>@exp.slug, :force=>true
              end

            end
            end_commit = @project.last_local_commit

            # log_thread.join
            stats_thread.join

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


            if !exp_success

              log_message("Experiment has failed, look at the log for more details or run cnvrg exec --log", Thor::Shell::Color::RED)
            else
              check = Helpers.checkmark()
              log_message("#{check} Done. Experiment's results were updated!", Thor::Shell::Color::GREEN)
            end

        rescue => e
          if container
            container.stop()
          end
          log_message("Couldn't run #{cmd}, check your input parameters", Thor::Shell::Color::RED)
          if @exp
            # log_thread.join
            Thread.kill(stats_thread)
            exit_status = $?.exitstatus
            if exit_status.blank?
              exit_status = "-1"
            end
            res = @exp.end(log, exit_status, end_commit, cpu_average, memory_average)

          end
          log_error(e)
          # Thread.kill(log_thread)
          # Thread.kill(stats_thread)

          exit(1)
        end


      end

    end
  rescue SignalException
    exit_status = -1
    end_commit = @project.last_local_commit
    process_running = false
    # log_thread.join
    stats_thread.join

    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



4995
4996
4997
4998
4999
5000
5001
5002
# File 'lib/cnvrg/cli.rb', line 4995

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_remote(*cmd) ⇒ Object



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
3711
3712
3713
3714
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
3762
3763
3764
3765
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
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
# File 'lib/cnvrg/cli.rb', line 3681

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
    data_query = options["data_query"] || nil
    sync_before = options["sync_before"]
    force = options["force"]
    max_time = options["max_time"]
    if !max_time.nil? and !max_time.empty?
      max_time = max_time.to_i
      if max_time <=0
        log_message("Max time for experiment should be more than 0 minutess", Thor::Shell::Color::RED)
        exit(1)
      end
    end
    periodic_sync = options["periodic_sync"]
    sync_before_terminate = options["sync_before_terminate"]
    dataset_only_tree = options["dataset_only_tree"]
    ds_sync_options = 0
    if dataset_only_tree
      ds_sync_options = 1
    end
    restart_if_stuck = options["restart_if_stuck"]
    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
    output_dir = options["output_dir"] || nil
    git_commit = options["git_commit"]
    git_branch = options["git_branch"]

    options_hash = Hash[options]
    options_hash.except!("schedule", "machine_type", "image", "upload_output", "grid", "data", "data_commit",
                         "local", "small", "medium", "large", "gpu", "gpuxl", "gpuxxl","max_time","dataset_only_tree",
                         "data_query", "git_commit","git_branch", "restart_if_stuck" )
    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)

    if project.is_git and output_dir.blank?
      output_dir  = "output"
    end
    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
    else
      image_slug = image.image_slug
    end
    forced_commit = nil
    if sync_before and !project.is_git
      if force
      sync_result = invoke :sync, [false], :force => force, :return_id=> true
      begin
        forced_commit = JSON(sync_result)["commit_sha1"]
      rescue
        forced_commit = nil
      end
      else
        sync_result = invoke :sync, [false], :force => false
      end




      end


    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)
    if forced_commit and (commit_to_run.nil? or commit_to_run.empty?)
      commit_to_run = forced_commit
    end
    res = exp.exec_remote(command, commit_to_run, instance_type, image_slug, schedule, local_timestamp, grid, path_to_cmd, data, data_commit,
                          periodic_sync, sync_before_terminate, max_time, ds_sync_options,output_dir,data_query, git_commit, git_branch, restart_if_stuck)
    if Cnvrg::CLI.is_response_success(res)
      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, follow here: #{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
    sleep(20) # end cycle

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

    exit(1)
  end
end

#experimentsObject



5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
# File 'lib/cnvrg/cli.rb', line 5461

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



5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
# File 'lib/cnvrg/cli.rb', line 5503

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

#git_clone(slug, owner) ⇒ Object



1619
1620
1621
1622
1623
1624
1625
# File 'lib/cnvrg/cli.rb', line 1619

def git_clone(slug, owner)
  verify_logged_in(false)
  log_start(__method__, args, options)

  clone_resp = Project.clone_dir_remote(slug, owner, slug,true)
  idx_status = Project.new(get_project_home).generate_idx
end

#init_data(public) ⇒ Object



735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
# File 'lib/cnvrg/cli.rb', line 735

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



951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
# File 'lib/cnvrg/cli.rb', line 951

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



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
4559
4560
4561
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
# File 'lib/cnvrg/cli.rb', line 4534

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



4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
# File 'lib/cnvrg/cli.rb', line 4483

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



3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
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
# File 'lib/cnvrg/cli.rb', line 3054

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


652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
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
# File 'lib/cnvrg/cli.rb', line 652

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"]
    git = options["git"] ||  false

    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 = docker,git = git)
      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


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

def link_git(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]
    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"]

    log_message("Linking #{project_name}", Thor::Shell::Color::BLUE)
    clone_resp = Project.clone_dir_remote(slug, owner, project_name, true)
    idx_status = Project.new(get_project_home).generate_idx
    log_message("Linking project #{project_name} successfully", Thor::Shell::Color::GREEN)

    return
  rescue => e
    log_message("Error occurred, \nAborting", Thor::Shell::Color::RED)
    log_error(e)
    return
  rescue SignalException

    say "\nAborting", Thor::Shell::Color::BLUE
    return
  end

end

#list_commitsObject



1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
# File 'lib/cnvrg/cli.rb', line 1593

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



1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
# File 'lib/cnvrg/cli.rb', line 1519

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)
  Cnvrg::CLI.is_response_success(result)

    list = result["result"]["list"]

    print_table(list)


end

#list_dataset_commitsObject



1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
# File 'lib/cnvrg/cli.rb', line 1578

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_files_datasetObject



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

def list_files_dataset()
  begin
    verify_logged_in(true)
    log_start(__method__, args, options)
    commit = options[:commit]
    as_json = options[:json]
    dataset_dir = is_cnvrg_dir(Dir.pwd)
    @dataset = Dataset.new(dataset_dir)

    resp = @dataset.list_files(commit, as_json)
    if (resp and resp["result"])
      if as_json
        puts resp["result"]
      else
        print_table(resp["result"])

      end

    end


  rescue => e
    puts e
  rescue SignalException
    @dataset.set_next_commit(commit)
    log_message("Aborting", Thor::Shell::Color::YELLOW)
    exit(1)
  end

end

#list_imagesObject



5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
# File 'lib/cnvrg/cli.rb', line 5407

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



5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
# File 'lib/cnvrg/cli.rb', line 5434

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



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
504
505
506
507
508
509
510
511
512
513
# File 'lib/cnvrg/cli.rb', line 415

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



518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
# File 'lib/cnvrg/cli.rb', line 518

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



539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
# File 'lib/cnvrg/cli.rb', line 539

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



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

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

#notebookObject



3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
# File 'lib/cnvrg/cli.rb', line 3942

def notebook
  verify_logged_in(true)
  log_start(__method__, args, options)
  local = options["local"]
  notebook_dir = options["notebook_dir"]
  kernel = options["kernel"]
  image = options["image"]
  data = options["data"]
  data_commit = options["data_commit"]
  dataset_only_tree = options["dataset_only_tree"]
  data_query = options["data_query"]
  if !data.present? and data_query.present?
    log_message("Please provide data with data_query", Thor::Shell::Color::RED)
    exit(1)
  end
  if data_query.present? and (data_commit.present? or dataset_only_tree.present?)
    log_message("Please use only one option: --query(-q) or #{data_commit.present? ? '--data_commit' : '--dataset_only_tree'} ", Thor::Shell::Color::RED)
    exit(1)
  end

  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 , :dataset_only_tree => dataset_only_tree, :data_query => data_query
    return

  end


end

#notebook_stop(notebook_slug) ⇒ Object



4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
# File 'lib/cnvrg/cli.rb', line 4445

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



5006
5007
5008
5009
# File 'lib/cnvrg/cli.rb', line 5006

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



5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
# File 'lib/cnvrg/cli.rb', line 5542

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



4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
# File 'lib/cnvrg/cli.rb', line 4885

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

#queriesObject



1541
1542
1543
1544
1545
1546
1547
1548
# File 'lib/cnvrg/cli.rb', line 1541

def queries
  verify_logged_in(false)
  log_start(__method__, args, options)
  dataset_dir = is_cnvrg_dir(Dir.pwd)
  @dataset = Dataset.new(dataset_dir)
  result = @dataset.search_queries()
  print_table(result)
end

#query_files(query) ⇒ Object



1566
1567
1568
1569
1570
1571
1572
1573
1574
# File 'lib/cnvrg/cli.rb', line 1566

def query_files(query)
  verify_logged_in(false)
  log_start(__method__, args, options)
  dataset_dir = is_cnvrg_dir(Dir.pwd)
  @dataset = Dataset.new(dataset_dir)
  query = options["query"] || query
  result = @dataset.get_query_file(query)
  print_table(result)
end

#remote_notebookObject



4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
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
# File 'lib/cnvrg/cli.rb', line 4093

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"]
  dataset_only_tree = options["dataset_only_tree"]
  ds_sync_options = 0
  if dataset_only_tree
    ds_sync_options = 1
  end

  data_query = nil
  if data.present?
    data_query = options["data_query"]
  end

  if data_commit.present? and data_query.present?
    log_message("Please use only one option: --query(-q) or --data_commit ", Thor::Shell::Color::RED)
    exit(1)
  end

  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,ds_sync_options,data_query)
    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



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
4038
4039
4040
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
4080
4081
4082
# File 'lib/cnvrg/cli.rb', line 3988

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



1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
# File 'lib/cnvrg/cli.rb', line 1891

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



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
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
# File 'lib/cnvrg/cli.rb', line 3279

def run(*cmd)
  verify_logged_in(true)
  log_start(__method__, args, options)
  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"]
  sync_before_terminate = options["sync_before_terminate"]
  periodic_sync = options["periodic_sync"]
  force = options["force"]
  max_time = options["max_time"]
  dataset_only_tree = options["dataset_only_tree"]
  custom_machine = options["machine"]
  output_dir = options["output_dir"]
  data_query = options["data_query"]
  if !data.present? and data_query.present?
    log_message("Please provide data with data_query", Thor::Shell::Color::RED)
    exit(1)
  end
  if data_query.present? and (data_commit.present? or dataset_only_tree.present?)
    log_message("Please use only one option: --query(-q) or #{data_commit.present? ? '--data_commit' : '--dataset_only_tree'} ", Thor::Shell::Color::RED)
    exit(1)
  end
  git_commit = options["git_commit"]
  git_branch = options["git_branch"]
  restart_if_stuck = options["restart_if_stuck"]

  options_hash = Hash[options]

  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, :output_dir=>output_dir, :data_query=>data_query
    return
  else
    if !periodic_sync.nil? and !periodic_sync.empty?
      if /^\d{2}$/ === periodic_sync
        if !["15","30","45","60"].include? periodic_sync
          log_message("periodic sync can only be every 15m, 30m, 45m or 60m", Thor::Shell::Color::RED)
          exit(1)
        end
      else
        log_message("periodic sync has to be one of the following values: 15m, 30m, 45m or 60m", Thor::Shell::Color::RED)
        exit(1)

      end
    end
    instances = { "small" => options["small"], "medium" => options["medium"], "large" => options["large"],
                  "gpu" => options["gpu"], "gpuxl" => options["gpuxl"], "gpuxxl" => options["gpuxxl"],
                 options["machine"] => !options["machine"].blank? }
    instance_type = get_instance_type(instances)
    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, :sync_before_terminate => sync_before_terminate,
            :max_time => max_time,
           :periodic_sync => periodic_sync, :dataset_only_tree=> dataset_only_tree,
           :output_dir=>output_dir, :data_query=>data_query, :git_commit =>git_commit, :git_branch=> git_branch, :restart_if_stuck =>restart_if_stuck
    return
  end

end

#run_notebookObject



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
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
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
4408
4409
4410
4411
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
# File 'lib/cnvrg/cli.rb', line 4274

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



4148
4149
4150
4151
4152
4153
4154
4155
4156
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
# File 'lib/cnvrg/cli.rb', line 4148

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



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

def set_api_url(url)
  log_handler()
  log_start(__method__, args, options)
  home_dir = File.expand_path('~')
  if !url.end_with? "/api"
    url = url + "/api"
  end
  verify_ssl = options["verify_ssl"]
  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 ,verify_ssl: verify_ssl }
      end


    rescue
      config = {owner: "", username: "", version_last_check: get_start_day(), api: url, compression_path: compression_path ,verify_ssl: verify_ssl }
    end

    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, verify_ssl: verify_ssl }
    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, verify_ssl: verify_ssl}
    end

    checks = Helpers.checkmark
    File.open(home_dir+"/.cnvrg/config.yml", "w+") { |f| f.write config.to_yaml }

    say "#{checks} Done", Thor::Shell::Color::GREEN

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

#set_compression_path(*compression_path) ⇒ Object



381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# File 'lib/cnvrg/cli.rb', line 381

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



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'lib/cnvrg/cli.rb', line 315

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



5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
# File 'lib/cnvrg/cli.rb', line 5625

def set_image(docker_image)
  verify_logged_in(true)
  log_start(__method__, args, options)
  working_dir = is_cnvrg_dir
  project = Project.new(working_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
        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)
        exit(1)
      end
    else
      log_message("Could not create a new project with docker, image was not found", Thor::Shell::Color::RED)
      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_name = image_name.strip
    @image = Images.new(working_dir, image_name)
  end
  @image.update_image_activity(project.last_local_commit, nil)
end

#set_remote_api_url(owner, current_user, url) ⇒ Object



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# File 'lib/cnvrg/cli.rb', line 288

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



250
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
276
277
278
279
280
281
282
283
284
# File 'lib/cnvrg/cli.rb', line 250

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
      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

#showObject



3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
# File 'lib/cnvrg/cli.rb', line 3135

def show
  path = options['path']
  commit = options['commit']
    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)
  begin

    file = @files.show_file_s3(path, commit)

    if file
      puts file
    else
      say "Couldn't find file"
    end
  end
end

#show_librariesObject



4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
# File 'lib/cnvrg/cli.rb', line 4211

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



977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
# File 'lib/cnvrg/cli.rb', line 977

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

#start_commit_dataObject



1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
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
# File 'lib/cnvrg/cli.rb', line 1974

def start_commit_data()
  begin
    verify_logged_in(true)
    log_start(__method__, args, options)
    dataset_dir = is_cnvrg_dir(Dir.pwd)
    direct = options[:direct]
    new_branch = options["new_branch"] || false
    force = options["force"] || false
    commit_sha1 = nil
    @dataset = Dataset.new(dataset_dir)
    @files = Cnvrg::Datafiles.new(@dataset.owner, @dataset.slug)
    next_commit = @dataset.get_next_commit() #if there was a partial commit..
    if next_commit.present? #keep from existing commit.
      resp = @files.get_commit(next_commit)
      if resp["result"]["status"].eql? "new"
        resp = @files.start_commit(new_branch,force)
        commit_sha1 = resp["result"]["commit_sha1"]
        @dataset.set_next_commit(commit_sha1)
      else
        commit_sha1 = resp["result"]["commit_sha1"]
      end
    else
      resp = @files.start_commit(new_branch,force)
      commit_sha1 = resp["result"]["commit_sha1"]
      @dataset.set_next_commit(commit_sha1)
    end
    if direct
      puts commit_sha1
    end
    return commit_sha1
  rescue => e
    puts e
      if commit_sha1.present?
        @dataset.set_next_commit(commit_sha1)
      end
  rescue SignalException
    log_message("Aborting..", Thor::Shell::Color::YELLOW)
    if commit_sha1.present?
      @dataset.set_next_commit(commit_sha1)
    end
    exit(1)
  end

end

#statusObject



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

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



5020
5021
5022
5023
5024
5025
# File 'lib/cnvrg/cli.rb', line 5020

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

end

#sync(direct = true) ⇒ Object



3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
# File 'lib/cnvrg/cli.rb', line 3224

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"])
  job_slug = options['job_slug']
  job_type = options['job_type']
  in_exp = options["in_exp"] || (job_slug.present? and job_type.present?)
  run_download = true
  if options[:force] or options[:files].present? or options[:output_dir].present? or in_exp
    run_download =false
  end
  if run_download
    invoke :download, [true, "", in_exp ], :new_branch => options["new_branch"], :verbose => options["verbose"], :sync => true
  end
  invoke :upload, [false, true,  direct, "",options['exp_slug'] ], :new_branch => options["new_branch"], :verbose => options["verbose"], :sync => true,
         :ignore => options[:ignore], :force => options[:force], :message => options[:message], :deploy => options["deploy"], :return_id => options["return_id"],
         :files => options["files"], :output_dir => options["output_dir"], :job_slug => job_slug, :job_type => job_type


end

#sync_data_new(new_branch, force, verbose, commit, all_files, tags, parallel, chunk_size, init) ⇒ Object



1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
# File 'lib/cnvrg/cli.rb', line 1922

def sync_data_new(new_branch, force, verbose, commit, all_files, tags ,parallel, chunk_size, init)
  verify_logged_in(true)
  log_start(__method__, args, options)
  log_message('Syncing dataset', Thor::Shell::Color::BLUE, !options["verbose"])
  if !force and !init
    invoke :download_data_new,[verbose,true, commit, all_files], :new_branch=>new_branch, :direct=>false, :force =>force
  end
  invoke :upload_data_new,[new_branch,  verbose,true,force, tags, chunk_size], :new_branch=>new_branch,
         :direct=>false, :force =>force, :sync =>true, :tags =>tags, :parallel => parallel

end

#sync_image(docker = false) ⇒ Object



4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
# File 'lib/cnvrg/cli.rb', line 4854

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



5013
5014
5015
5016
# File 'lib/cnvrg/cli.rb', line 5013

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

#testObject



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

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


1608
1609
1610
1611
1612
1613
1614
# File 'lib/cnvrg/cli.rb', line 1608

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 = "", in_exp = false, force = false, output_dir = "output", job_type = nil, job_slug = nil) ⇒ Object



2364
2365
2366
2367
2368
2369
2370
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
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
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
# File 'lib/cnvrg/cli.rb', line 2364

def upload(link = false, sync = false, direct = false, ignore_list = "", in_exp = false, force = false,output_dir="output",job_type=nil,job_slug=nil )
  begin
    # we are passing "force" twice.. doesnt really make sense :\\
    verify_logged_in(true)
    log_start(__method__, args, options)
    @project = Project.new(get_project_home)
    commit_msg = options["message"]
    if commit_msg.nil? or commit_msg.empty?
      commit_msg = ""
    end
    return_id = options["return_id"]
    @files = Cnvrg::Files.new(@project.owner, @project.slug)
    ignore = options[:ignore] || ""
    force = options[:force] || force || false
    spec_files_to_upload = options["files"]
    check = Helpers.checkmark()

    if !spec_files_to_upload.blank?
      spec_files_to_upload = spec_files_to_upload.split(",")
    end
    if @project.is_git
    git_output_dir = options["output_dir"] || output_dir
    if git_output_dir.present?
      if git_output_dir.ends_with? "/"
        git_output_dir = git_output_dir[0..-2]
      end
      spec_files_to_upload = Dir.glob("#{git_output_dir}/**/*", File::FNM_DOTMATCH).flatten
      spec_files_to_upload = spec_files_to_upload.select{|x| !x.ends_with? "/."}
      if spec_files_to_upload.blank?
        log_message("#{check} Project is up to date", Thor::Shell::Color::GREEN, (((options["sync"] or sync) and !direct) ? false : true))
          return true
      end
      force = true
    end
    end


    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

    result = @project.compare_idx(new_branch, force: force, deploy: options["deploy"],in_exp:in_exp, specific_files: spec_files_to_upload)
    commit = result["result"]["commit"]
    if !link
      if (result["result"]["new_version_exist"] and !force) or ((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)
        return false
      end

      log_message("Comparing local changes with remote version:", Thor::Shell::Color::BLUE, (options["verbose"]))
    end
    result = result["result"]["tree"]


    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
    if in_exp
      exp_start_commit = @project.last_local_commit
    else
      exp_start_commit = nil
    end
    job_type = options['job_type'] || job_type
    job_slug = options['job_slug'] || job_slug
    commit_sha1 = @files.start_commit(new_branch, force: force, exp_start_commit:exp_start_commit,
                                      job_type: job_type, job_slug: job_slug)["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)

          return false
        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)

        return false

      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
      return false
    rescue => e
      @files.rollback_commit(commit_sha1)
      log_message("Exception while trying to upload, Rolling back", Thor::Shell::Color::RED)
      log_error(e)
      return false
    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, message: commit_msg)
      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)
          return false

        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 return_id
            print_res = {
                'success' => "true",
                'commit_sha1' => res["result"]["commit_id"]
            }
            puts JSON[print_res]
            return JSON[print_res]
          end
          if (options["sync"] or sync) and direct
            log_message("#{check} Syncing project completed successfully", Thor::Shell::Color::GREEN)
            return true

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

          end

        end

      else
        @files.rollback_commit(commit_sha1)
        if return_id
          print_res = {
              'success' => "false",
              'message' => 'couldn\'t commit changes,  Rolling Back all changes.'
          }
          puts JSON[print_res]
        else
          log_message("Error: couldn't commit changes,  Rolling Back all changes.", Thor::Shell::Color::RED)

        end
        return false
      end
    else
      @files.rollback_commit(commit_sha1)
      if return_id
        print_res = {
            'success' => "false",
            'message' => "uploaded only: #{update_count} / #{update_total}, \n Rolling back"

        }
        puts JSON[print_res]
      else
      log_message("Error: uploaded only: #{update_count} / #{update_total}, \n Rolling back", Thor::Shell::Color::RED)
      end
      return false

    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
    return false

  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?
    return false
  end

end

#upload_cnvrg_image(image_path, image_name, secret) ⇒ Object



5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
# File 'lib/cnvrg/cli.rb', line 5268

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



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
1214
1215
1216
1217
1218
1219
1220
1221
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
# File 'lib/cnvrg/cli.rb', line 1132

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,false)
      if (Cnvrg::CLI.is_response_success(res, false))
        # save idx
        begin
          list_files = []
          list_files.concat successful_deletions
          list_files.concat successful_updates

          @dataset.update_idx_with_files_commits!(list_files, 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_files(new_commit, *files) ⇒ Object



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
2190
2191
2192
2193
2194
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
2271
2272
2273
2274
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
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
# File 'lib/cnvrg/cli.rb', line 2100

def upload_data_files(new_commit, *files)

  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)
    next_commit = @dataset.get_next_commit()
    if new_commit.blank? and next_commit.blank?
      log_message("You must specify commit, run start_commit to create new commit", Thor::Shell::Color::RED)
      exit(1)
    end

    force = options[:force] || false
    chunk_size = options[:chunk_size]
    chunk_size = [chunk_size, 1].max
    new_branch = options["new_branch"] || false
    force = options["force"] || false
    parallel_threads = options["parallel"]  || ParallelThreads
    new_tree = {}
    progressbar = ProgressBar.create(:title => "Upload Progress",
                                     :progress_mark => '=',
                                     :format => "%b>>%i| %p%% %t",
                                     :starting_at => 0,
                                     :autofinish => true)
    all_files = @dataset.list_all_files
    files_count = all_files.count
    finished_chunks = 0
    files_uploaded = 0
    chunked_files  = all_files.each_slice(chunk_size)
    chunked_files.each_with_index do |list_files,i|
      log_message("generating chunk #{i} / #{chunked_files.size}", Thor::Shell::Color::BLUE, false)
      temp_tree = @dataset.generate_chunked_idx(list_files, threads: parallel_threads)

      log_message("uploading chunk #{i} / #{chunked_files.size}", Thor::Shell::Color::BLUE, false)
      files_uploaded += @files.upload_multiple_files(next_commit, temp_tree, threads: parallel_threads, force: force)
      temp_tree.each do |k,v|
        if v.present?
          new_tree[k] = {sha1: v.try(:fetch, :sha1, nil), commit_time: nil}
        else
          new_tree[k] = nil
        end
      end
      @dataset.write_idx(new_tree, next_commit)
      finished_chunks += 1
      progressbar.progress = [(finished_chunks * chunk_size*100) / files_count, 100].min
    end
    return files_uploaded > 0
  rescue Exception => e
    log_error(e)
    return false
  end

  #   local_idx = @dataset.generate_idx
  #   result = @dataset.compare_idx(new_branch, [email protected]_local_commit, local_idx= local_idx, force=force, next_commit= next_commit)

  #   commit_sha1 = result["result"]["commit"]
  #     if commit_sha1 != @dataset.last_local_commit and [email protected]_local_commit.nil? and !result["result"]["tree"]["updated_on_server"].empty?
  #       @dataset.remove_next_commit()
  #       @files.delete_commit(next_commit)
  #       log_message("Remote server has an updated version, please run `cnvrg data download` first or cnvrg data upload --new_branch", Thor::Shell::Color::BLUE)
  #       exit(1)
  #     end
  #   check = Helpers.checkmark()


  #   commit_time = result["result"]["commit_time"]
  #   already_uploaded = result["result"]["uploaded"]
  #   dirs_uploaded = []
  #   files_uploaded = []
  #   files_uploaded_names = []
  #   if !already_uploaded.nil? and !already_uploaded.empty?

  #     dirs_uploaded = already_uploaded["dirs"]
  #     files_uploaded = already_uploaded["blobs"]
  #     if !files_uploaded.nil? and !files_uploaded.empty?
  #       files_uploaded_names = already_uploaded["blobs"].keys
  #     end

  #   end

  #   result = result["result"]["tree"]
  #   if result["added"].empty? and result["updated_on_local"].empty? and result["deleted"].empty?
  #     @files.delete_commit(next_commit)

  #     log_message("#{check} Dataset is up to date", Thor::Shell::Color::GREEN, true)
  #     return false
  #   end
  #   log_message("Creating new commit for dataset: #{@dataset.slug}", Thor::Shell::Color::BLUE) unless  options[:sync]


  #   # 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_threads: ParallelThreads,
  #         isolation: true
  #     }
  #     successful_updates = []
  #     update_count =0
  #     update_total = (result["added"] + result["updated_on_local"] + result["deleted"]).size

  #     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 = "#{@dataset.local_path}/#{f}"
  #           relative_path = f.gsub(/^#{@dataset.local_path + "/"}/, "")
  #           if File.directory?(absolute_path)
  #             if dirs_uploaded.include? f
  #               #Already uploaded and didn't finish commit
  #               log_message("Already uploaded dir: #{f}", Thor::Shell::Color::BLUE, options["verbose"])

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

  #             resDir = @files.create_dir(absolute_path, relative_path, commit_sha1)
  #             if resDir
  #               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
  #             if files_uploaded_names.include? f
  #               log_message("Already uploaded file: #{f}", Thor::Shell::Color::BLUE, options["verbose"])

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

  #             res = @files.upload_file(absolute_path, relative_path, commit_sha1)
  #             if res
  #               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("Exception while trying to upload, look at the log for more details", Thor::Shell::Color::RED)


  #         exit(1)
  #       end
  #     end

  #   end
  #     successful_updates = upload_result.to_a + dirs_uploaded + files_uploaded_names
  #   successful_deletions =[]


  #     # delete

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

  #       deleted_result = Parallel.map(deleted, in_threads: ParallelThreads) do |f|

  #         relative_path = f.gsub(/^#{@dataset.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)
  #             successful_deletions << f
  #           else
  #             log_message("Failed to delete directory: #{ f }", Thor::Shell::Color::RED)
  #             raise Parallel::Kill

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

  #           if @files.delete_file(f, relative_path, commit_sha1)
  #             successful_deletions << f

  #           else
  #             log_message("Failed to delete file: #{ f }", Thor::Shell::Color::RED)
  #             raise Parallel::Kill


  #           end
  #         end
  #       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
  #     say "User aborted", Thor::Shell::Color::RED
  #     exit(0)
  #   rescue => e
  #     log_message("Exception while trying to upload, look at the log for more details", 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
  #     begin
  #       @dataset.update_idx_with_files_commits!((successful_deletions+successful_updates), commit_time)

  #       return true
  #     rescue => e
  #       log_message("Exception while trying to upload, look at the log for more details", Thor::Shell::Color::RED)

  #       exit(1)

  #     end

  #   end
  # rescue => e

  #   log_message("Exception while trying to upload, look at the log for more details", Thor::Shell::Color::RED)
  #   log_error(e)

  #   exit(1)
  # rescue SignalException

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

end

#upload_data_new(new_branch, verbose, sync, force, tags, chunk_size) ⇒ Object



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

def upload_data_new(new_branch,  verbose,sync,force, tags, chunk_size)
  commit = invoke :start_commit_data,[], :new_branch=> new_branch, :direct=>false, :force =>force
  upload_res = invoke :upload_data_files,[commit],:new_branch=>new_branch, :verbose =>verbose, :force =>force, :sync =>sync, :chunk_size => chunk_size
  invoke :end_commit_data,[commit] , :new_branch=>new_branch,  :force =>force, :success => upload_res

  if tags
    log_message('Uploading Tags', Thor::Shell::Color::BLUE)
    dataset_dir = is_cnvrg_dir(Dir.pwd)
    @dataset = Dataset.new(dataset_dir)
    begin
      tag_file = File.open(options[:tags], "r+")
      status = @dataset.upload_tags_via_yml(tag_file)
    rescue
      log_message('Tags file not found', Thor::Shell::Color::RED)
      return
    end
    if status
      log_message('Tags are successfully uploaded', Thor::Shell::Color::GREEN)
    else
      log_message('There was some error in uploading Tags', Thor::Shell::Color::RED)
    end
  end

  if upload_res
    invoke :end_commit_data,[commit] , :new_branch=>new_branch,  :force =>force
  end

end

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



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
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
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
# File 'lib/cnvrg/cli.rb', line 1323

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)
    ignore_list = @dataset.get_ignore_list()
    local_idx = @dataset.generate_idx(ignore_list)

    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)

      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"
      files_to_upload = result["added"] + result["updated_on_local"]
      if File.exist? (@dataset.local_path + "/.cnvrgignore")
        files_to_upload << ".cnvrgignore"
      end
      tar_files = (files_to_upload).join("\n")
      File.open(tar_files_path, 'w') {|f| f.write tar_files}
      ignore_files_path = nil
      if !ignore_list.nil?
        ignore_files_path = "#{home_dir}/.cnvrg/tmp/#{@dataset.slug}_#{commit_sha1}_ignore.txt"
        File.open(ignore_files_path, 'w') {|f| f.write ignore_list.join("\n")}
      end
      is_tar = create_tar(dataset_dir, tar_path, tar_files_path, no_compression, ignore_files_path)
      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
        FileUtils.rm_rf([ignore_files_path]) if !ignore_files_path.nil? and File.exist? ignore_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



4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
# File 'lib/cnvrg/cli.rb', line 4925

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



4986
4987
4988
4989
4990
4991
# File 'lib/cnvrg/cli.rb', line 4986

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



190
191
192
193
# File 'lib/cnvrg/cli.rb', line 190

def version
  puts Cnvrg::VERSION

end