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

Instance Method Summary collapse

Instance Method Details

#clone(project_url) ⇒ Object



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'lib/cnvrg/cli.rb', line 263

def clone(project_url)
  begin
    verify_logged_in()
    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"]
    say "Cloning #{project_name}", Thor::Shell::Color::BLUE
    if Dir.exists? project_name or File.exists? project_name
      say "Error: Conflict with dir/file #{project_name}", Thor::Shell::Color::RED
      exit(1)
    end

    if Project.clone_dir(slug, owner, project_name)
      project_home = Dir.pwd+"/"+project_name
      @project = Project.new(project_home)
      @files = Cnvrg::Files.new(@project.owner, slug)
      response = @project.clone
      Cnvrg::CLI.is_response_success response
      idx = {commit: response["result"]["commit"], tree: response["result"]["tree"]}
      File.open(project_name + "/.cnvrg/idx.yml", "w+") { |f| f.write idx.to_yaml }
      successful_changes = []
      say "Downloading files", Thor::Shell::Color::BLUE
      response["result"]["tree"].each 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)
            successful_changes << relative_path
          end
        else
          # blob
          if @files.download_file(f[0], relative_path, project_home)
            successful_changes << relative_path
          end
        end
      end
      say "Done.\nDownloaded total of #{successful_changes.size} files", Thor::Shell::Color::GREEN
    else
      say "Error: Couldn't create directory: #{project_name}", Thor::Shell::Color::RED
      exit(1)
    end
  rescue SignalException
    say "/nAborting"
    exit(1)
  end

end

#commit_notebook(notebook_image_name) ⇒ Object



914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
# File 'lib/cnvrg/cli.rb', line 914

def commit_notebook(notebook_image_name)
  begin
    docker_path = verify_software_installed("docker")

    container_id = get_container_id
    owner = Cnvrg::CLI.get_owner()
    say "Commiting notebook changes to: #{notebook_image_name}", Thor::Shell::Color::BLUE

    commit_res = system("#{docker_path} commit #{container_id} #{notebook_image_name}")
    if commit_res
      checker = Helpers.checkmark()
      say "#{checker} Done.", Thor::Shell::Color::GREEN
    else
      say "Couldn't commit new notebook image ", Thor::Shell::Color::RED

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

#downloadObject



507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
# File 'lib/cnvrg/cli.rb', line 507

def download
  begin
    verify_logged_in()
    project_home = get_project_home
    @project = Project.new(project_home)
    @files = Cnvrg::Files.new(@project.owner, @project.slug)

    res = @project.compare_idx["result"]
    result = res["tree"]
    commit = res["commit"]
    if result["updated_on_server"].empty? and result["conflicts"] and result["deleted"].empty?
      say "Project is up to date", Thor::Shell::Color::GREEN
      return true
    end
    update_count = 0
    update_total = result["updated_on_server"].size + result["conflicts"].size

    successful_changes = []
    if update_total ==1
      say "Downloading #{update_total} file", Thor::Shell::Color::BLUE
    else
      say "Downloading #{update_total} files", Thor::Shell::Color::BLUE

    end

    result["conflicts"].each do |f|
      relative_path = f.gsub(/^#{@project.local_path}/, "")
      if @files.download_file(f, relative_path, project_home, conflict=true)
        successful_changes << relative_path
      end

    end
    result["updated_on_server"].each do |f|
      relative_path = f.gsub(/^#{@project.local_path}/, "")
      if f.end_with? "/"
        # dir
        if @files.download_dir(f, relative_path, project_home)
          successful_changes << relative_path

        end
      else
        # blob
        if @files.download_file(f, relative_path, project_home)
          successful_changes << relative_path
        end
      end

    end
    if update_total == successful_changes.size
      # update idx with latest commit
      @project.update_idx_with_commit!(commit)
      say "Done. Downloaded:", Thor::Shell::Color::GREEN
      say successful_changes.join("\n"), Thor::Shell::Color::GREEN
      say "Total of #{successful_changes.size} / #{update_total} files.", Thor::Shell::Color::GREEN
    end
  rescue SignalException
    say "\nAborting", Thor::Shell::Color::BLUE
    if successful_changes.nil?
      exit(1)
    end
    successful_changes.each do |f|

      abs_path = "#{@project.local_path}/#{f}"
      filename = File.basename abs_path
      say "revoking #{filename}"
      if result["conflicts"].include? f
        @files.revoke_download_file(abs_path,f,filename,true)
      elsif result["updated_on_server"].include? f
        if File.directory? abs_path
          @files.revoke_download_dir(abs_path,f,project_home)
        else
          @files.revoke_download_file(project_home,abs_path,filename)
        end
      end
    end
    exit(1)
  end
end

#download_image(image_name) ⇒ Object



991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
# File 'lib/cnvrg/cli.rb', line 991

def download_image(image_name)
  begin
    owner = Cnvrg::CLI.get_owner()

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

    if Cnvrg::CLI.is_response_success(notebooks_res)

      images = notebooks_res["result"]["images"]
      if images.empty?
        say "Couldn't find any image with name: #{image_name}", Thor::Shell::Color::RED
        exit(1)
      elsif images.size == 1
        image_id = images[0]["slug"]
      else
        printf "%-20s %-20s %-30s %-20s\n", "name", "version", "last updated", "created by"
        images.each_with_index do |u, i|
          time = Time.parse(u["updated_at"])
          update_at = get_local_time(time)
          version = u["version"] || "v1"
          created_by = u["image_file_name"][/^[^\_]*/]
          printf "%-20s %-20s %-30s %-20s\n", u["name"], version, update_at, created_by
        end
        choice = ask("Which version to download for #{image_name}?")
        images.each do |u|
          if u["version"] == choice
            image_id = u["slug"]
          end

        end

      end
    end
    path = Dir.pwd+"/#{owner}_#{image_name}.tar.gz"
    @files = Cnvrg::Files.new(owner, "")

    say "Downloading image file", Thor::Shell::Color::BLUE
    begin
      res = @files.download_image(path, image_id, owner)
      if res
        checks = Helpers.checkmark()
        say "#{checks} Done", Thor::Shell::Color::GREEN
        return true
      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

#exec(*cmd) ⇒ Object



626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
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
731
732
733
734
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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
# File 'lib/cnvrg/cli.rb', line 626

def exec(*cmd)
    log = []
    cpu_average =0
    memory_average = 0
    verify_logged_in()

    project_home = get_project_home
    @project = Project.new(project_home)
    sync_before = options["sync_before"]
    sync_after = options["sync_after"]
    print_log = options["log"]
    title = options["title"]
    email_notification = options["email_notification"]
    upload_output = options["upload_output"]
    time_to_upload = calc_output_time(upload_output)
  begin
    if sync_before
      # Sync before run
      say "Syncing project before running", Thor::Shell::Color::BLUE
      say 'Checking for new updates from remote version', Thor::Shell::Color::BLUE

      download()
      upload()
      say "Done Syncing", Thor::Shell::Color::BLUE
    end

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

    say "Running: #{cmd}\n", Thor::Shell::Color::BLUE

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

    platform = RUBY_PLATFORM
    machine_name = Socket.gethostname
    begin

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

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

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

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

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

              end


              if stderr

                stderr.each do |err|

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

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

              exp_success = false

              say "command \"#{cmd}\" couldn't be executed, verify command is valid", Thor::Shell::Color::RED
            rescue PTY::ChildExited

              exp_success = false
              say "The process exited!", Thor::Shell::Color::RED
            rescue => e

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

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

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

            res = @exp.end(log, exit_status, end_commit, cpu_average, memory_average)
            check = Helpers.checkmark()
            say "#{check} Done. Experiment's result: #{Cnvrg::Helpers.remote_url}/#{@project.owner}/projects/#{@project.slug}/experiments/#{@exp.slug}", Thor::Shell::Color::GREEN
          end
        rescue

          say "Couldn't run #{cmd}, check your input parameters", Thor::Shell::Color::RED
          exit(1)
        end


      end

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

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

    exit(1)
  end
end

#install_notebook_librariesObject



895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
# File 'lib/cnvrg/cli.rb', line 895

def install_notebook_libraries
  begin
    docker_path = verify_software_installed("docker")
    container_id = get_container_id
    say "Opening shell in notebook server\nYou can run pip install [library] to install more tools\ntype exit to finish", Thor::Shell::Color::BLUE
    system("#{docker_path} exec -it #{container_id} bash")
    commit_name = options["commit_name"]
    if !commit_name.empty?
      return commit_notebook(commit_name)
    end
  rescue SignalException
    say "/nAborting"
    exit(1)
  end

end


230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/cnvrg/cli.rb', line 230

def link
  begin
    verify_logged_in()
    sync = options["sync"]
    project_name =File.basename(Dir.getwd)
    say "Linking #{project_name}", Thor::Shell::Color::BLUE
    if File.directory?(Dir.getwd+"/.cnvrg")
      config = YAML.load_file("#{Dir.getwd}/.cnvrg/config.yml")
      say "Directory is already linked to #{config[:project_slug]}", Thor::Shell::Color::RED
      exit(0)
    end
    if Project.link(project_name)
      path = Dir.pwd
      @project = Project.new(path)
      @project.generate_idx()
      if sync
        upload(true)
      end

      url = @project.url
      say "#{project_name}'s location is: #{url}\n", Thor::Shell::Color::BLUE
    else
      say "Error linking project, please contact support.", Thor::Shell::Color::RED
      exit(0)
    end
  rescue SignalException
    say "/nAborting"
    exit(1)
  end
end

#list_imagesObject



1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
# File 'lib/cnvrg/cli.rb', line 1051

def list_images
  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\n", "name", "version", "last updated", "created by"
    res["result"]["images"].each do |u|
      time = Time.parse(u["updated_at"])
      update_at = get_local_time(time)
      version = u["version"] || "v1"
      created_by = u["image_file_name"][/^[^\_]*/]

      printf "%-20s %-20s %-30s %-20s\n", u["name"], version, update_at, created_by
    end
  end
  return res["result"]["images"]
end

#loginObject



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/cnvrg/cli.rb', line 106

def 
  begin
    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
      say '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

      say "Authenticated successfully as #{@email}", Thor::Shell::Color::GREEN
      owners = result["owners"]
      choose_owner = result["username"]

      if owners.empty?
      else
        owners << choose_owner
        choose_owner = ask("Choose default owner:\n"+owners.join("\n")+"\n")

      end
      if set_owner(choose_owner, result["username"])
        say "Setting default owner: #{choose_owner}", Thor::Shell::Color::GREEN
      else
        say "Setting default owenr has failed, logging out", Thor::Shell::Color::RED
        return logout()
      end

    else
      say "Failed to authenticate, wrong email/password", Thor::Shell::Color::RED
      exit false
    end
  rescue SignalException
    say "/nAborting"
    exit(1)
  end
end

#logoutObject



158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/cnvrg/cli.rb', line 158

def logout
  begin
    netrc = Netrc.read
    netrc.delete(Cnvrg::Helpers.netrc_domain)
    netrc.save
    say "Logged out successfully.\n", Thor::Shell::Color::GREEN
  rescue SignalException
    say "/nAborting"
    exit(1)
  end

end

#meObject



173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/cnvrg/cli.rb', line 173

def me
  begin
    verify_logged_in()
    auth = Cnvrg::Auth.new
    if (email = auth.get_email)
      say "Logged in as: #{email}", Thor::Shell::Color::GREEN
    else
      say "You're not logged in.", Thor::Shell::Color::RED
    end
  rescue SignalException
    say "/nAborting"
    exit(1)
  end
end

#new(project_name) ⇒ Object

Projects



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

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

#pull_image(image_name) ⇒ Object



1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
# File 'lib/cnvrg/cli.rb', line 1071

def pull_image(image_name)
  begin

    if download_image(image_name)
      path = Dir.pwd+"/#{owner}_#{image_name}.tar.gz"
      loadRes = system("docker load < #{path}")
      if loadRes.include? "Loaded image"
        say loadRes, Thor::Shell::Color::GREEN
      else
        say loadRes, Thor::Shell::Color::RED
      end

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

end

#run_notebookObject



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
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
# File 'lib/cnvrg/cli.rb', line 802

def run_notebook
  begin
    cur_path = Dir.pwd
    notebook_dir = options["notebook_dir"]
    if notebook_dir.empty?
      notebook_dir = cur_path
    else
      notebook_dir = cur_path+ notebook_dir
    end
    say "Linking notebook directory to: #{notebook_dir}", Thor::Shell::Color::BLUE
    docker = options["docker"]
    try_again = true


    if docker
      docker_path = verify_software_installed("docker")
      image_name = options["image_name"]
      if image_name.empty?
        images_list = `#{docker_path} images`
        if images_list.empty? or images_list.nil?
          say "you don't have any images to run", Thor::Shell::Color::BLUE
        else
          say "Choose image name to run as a container\n", Thor::Shell::Color::BLUE
          say images_list
          image_name = ask("\nwhat is the image name?\n")
        end

      end
      while (try_again) do
        run_docker = `#{docker_path} run -d -p 8888:8888  -v #{notebook_dir}:/home/ds/notebooks -t -i #{image_name} 2>&1`
        if !run_docker.match(/[a-z0-9]{64}/).nil? and !run_docker.include? "Error"
          container_id = get_container_id()
          sleep(3)
          logs = `docker logs #{container_id}`
          url = URI.extract(logs).reject { |x| x if !x.include? "http" }.uniq![0]
          if !url.empty?
            check = Helpers.checkmark()

            say "#{check} Notebook server started successfully, view notebook in url: #{url}", Thor::Shell::Color::GREEN
            try_again= false
          else
            say "Couldn't start notebook server", Thor::Shell::Color::RED
            exit(1)
          end

        elsif run_docker.include? "port is already allocated"
          say "Couldn't start notebook with port 8888, port is taken", Thor::Shell::Color::RED
          port_container = `#{docker_path} ps |grep 8888 |awk '{print $1}'`.strip!
          stop = agree "There is another running notebook server: #{port_container}, do you want to stop it?", limited_to: ['y', 'n'], default: 'y'
          if stop == "y"
            did_stop = system("#{docker_path} stop #{port_container}")
            if !did_stop
              say "Couldn't stop notebook server: #{port_container}", Thor::Shell::Color::RED
              exit(1)

            end
          else
            logs = `#{docker_path} logs #{port_container}`
            url = URI.extract(logs).reject { |x| x if !x.include? "http" }.uniq![0]
            say "Okay, you could find the existing server in: #{url}", Thor::Shell::Color::BLUE
            exit(1)
          end
        else
          say "Couldn't start notebook server", Thor::Shell::Color::RED
          exit(1)

        end
      end
    else
      jup =verify_software_installed("jupyter-notebook")
      logs = `#{jup} --no-browser --ip=0.0.0.0  --notebook-dir=#{notebook_dir}`
      url = URI.extract(logs).reject { |x| x if !x.include? "http" }.uniq![0]
      if !url.empty?
        check = Helpers.checkmark()

        say "#{check} Notebook server started successfully, view notebook in url: #{url}", Thor::Shell::Color::GREEN
      else
        say "Couldn't start notebook server", Thor::Shell::Color::RED
        exit(1)
      end

    end
  rescue SignalException
    say "Aborting"
    exit(1)
  end


end

#set_api_url(url) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/cnvrg/cli.rb', line 41

def set_api_url(url)
  home_dir = File.expand_path('~')
  if !url.end_with? "/api"
    url = url+"/api"
  end
  begin
    if !File.directory? home_dir+"/.cnvrg"
      FileUtils.mkdir_p([home_dir+"/.cnvrg", home_dir+"/.cnvrg/tmp"])
    end
    if !File.exist?(home_dir+"/.cnvrg/config.yml")
      FileUtils.touch [home_dir+"/.cnvrg/config.yml"]
    end
    config = YAML.load_file(home_dir+"/.cnvrg/config.yml")
    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}
    else
      config = {owner: config.to_h[:owner], username: config.to_h[:username], version_last_check: config.to_h[:version_last_check], api: url}
    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
    say "Couldn't set default api, contact [email protected]", Thor::Shell::Color::RED
  end
end

#set_default_ownerObject



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/cnvrg/cli.rb', line 74

def set_default_owner

  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"]
    if result["owners"].size > 1
      owner = ask("Choose default owner:\n"+result["owners"].join("\n")+"\n")

    end
    if set_owner(owner, username)
      say "Setting default owner: #{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
end

#statusObject



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

def status
  begin
    verify_logged_in()
    @project = Project.new(get_project_home)
    result = @project.compare_idx["result"]
    commit = result["commit"]
    result = result["tree"]
    say "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?
      say "Project is up to date", Thor::Shell::Color::GREEN
      return true
    end
    if result["added"].size > 0
      say "Added files:\n", Thor::Shell::Color::BLUE
      result["added"].each do |a|
        say "\t\tA:\t#{a}", Thor::Shell::Color::GREEN
      end
    end

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

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

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

#syncObject



589
590
591
592
593
# File 'lib/cnvrg/cli.rb', line 589

def sync
  say 'Checking for new updates from remote version', Thor::Shell::Color::BLUE
  invoke :download
  invoke :upload
end

#upload(link = false, sync = false) ⇒ Object



372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
# File 'lib/cnvrg/cli.rb', line 372

def upload(link=false, sync=false)

  begin
    verify_logged_in()
    @project = Project.new(get_project_home)

    @files = Cnvrg::Files.new(@project.owner, @project.slug)
    ignore = options[:ignore] || []
    if !@project.update_ignore_list(ignore)
      say "Couldn't append new ignore files to .cnvrgignore", Thor::Shell::Color::YELLOW
    end
    result = @project.compare_idx
    commit = result["result"]["commit"]
    if !link
      if commit != @project.last_local_commit and !@project.last_local_commit.nil? and !result["result"]["tree"]["updated_on_server"].empty?
        say "Remote server has an updated version, please run `cnvrg download` first, or alternatively: `cnvrg sync`", Thor::Shell::Color::YELLOW
        exit(1)
      end
      say "Comparing local changes with remote version:", Thor::Shell::Color::BLUE
    end
    result = result["result"]["tree"]
    if result["added"].empty? and result["updated_on_local"].empty? and result["deleted"].empty?
      say "Project is up to date", Thor::Shell::Color::GREEN
      return true
    end
    update_count = 0
    update_total = result["added"].size + result["updated_on_local"].size + result["deleted"].size
    successful_updates = []
    successful_deletions = []
    if update_total == 1
      say "Updating #{update_total} file", Thor::Shell::Color::BLUE
    else
      say "Updating #{update_total} files", Thor::Shell::Color::BLUE
    end

    # Start commit

    commit_sha1 = @files.start_commit["result"]["commit_sha1"]

    # upload / update
    begin
      (result["added"] + result["updated_on_local"]).each do |f|
        puts f
        absolute_path = "#{@project.local_path}/#{f}"
        relative_path = f.gsub(/^#{@project.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)
            say "Couldn't upload, Rolling Back all changes.", Thor::Shell::Color::RED
            exit(0)
          end
        end
      end

      # delete
      result["deleted"].each do |f|
        relative_path = f.gsub(/^#{@project.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
      puts e
      @files.rollback_commit(commit_sha1)
      say "Exception while trying to upload, Rolling back", Thor::Shell::Color::RED
      exit(0)
    end
    if update_count == update_total
      res = @files.end_commit(commit_sha1)
      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
          @files.rollback_commit(commit_sha1)
          say "Couldn't commit updates, Rolling Back all changes.", Thor::Shell::Color::RED
          exit(1)

        end

        say "Done", Thor::Shell::Color::BLUE
        if successful_updates.size >0
          say "Updated:", Thor::Shell::Color::GREEN
          suc = successful_updates.map { |x| x=Helpers.checkmark() +" "+x }
          say suc.join("\n"), Thor::Shell::Color::GREEN
        end
        if successful_deletions.size >0
          say "Deleted:", Thor::Shell::Color::GREEN
          del = successful_updates.map { |x| x=Helpers.checkmark() +" "+x }
          say del.join("\n"), Thor::Shell::Color::GREEN
        end
        say "Total of #{update_count} / #{update_total} files.", Thor::Shell::Color::GREEN
      else
        @files.rollback_commit(commit_sha1)
        say "Error. Rolling Back all changes.", Thor::Shell::Color::RED
      end
    else
      @files.rollback_commit(commit_sha1)
    end
  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_name) ⇒ Object



938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
# File 'lib/cnvrg/cli.rb', line 938

def upload_image(image_name)
  docker_path = verify_software_installed("docker")
  owner = Cnvrg::CLI.get_owner()
  # verify image exist
  images = `#{docker_path} images |grep #{image_name}`
  if images.empty?
    say "Couldn't find any images named: #{image_name}", Thor::Shell::Color::RED
    exit(1)
  end
  path = File.expand_path('~')+"/.cnvrg/#{owner}_#{image_name}.tar"
  begin
    say "Creating image file to upload", Thor::Shell::Color::BLUE
    if !(File.exist? path or File.exist? path+"gz")
      saveRes = system("#{docker_path} save #{image_name}>#{path}")
      if !saveRes
        say "Couldn't create tar file from image", Thor::Shell::Color::RED
        exit(1)
      end
      gzipRes = system("gzip -f #{path}")
      if !gzipRes
        say "Couldn't create tar file from image", Thor::Shell::Color::RED
        exit(1)
      end
    end

    path = path+".gz"
    @files = Cnvrg::Files.new(owner, "")

    exit_status = $?.exitstatus
    if exit_status == 0
      say "Uploading image file", Thor::Shell::Color::BLUE
      res = @files.upload_image(path, image_name, owner)
      if res
        File.delete(path)
        checks = Helpers.checkmark()
        say "#{checks} Done", Thor::Shell::Color::GREEN
      else
        say "Couldn't upload image", Thor::Shell::Color::RED
      end
    else
      say "Couldn't create image file for: #{image_name}", Thor::Shell::Color::RED
      exit(1)
    end
  rescue SignalException
    say "Couldn't upload image file for: #{image_name}", Thor::Shell::Color::RED
    exit(1)
  end


end

#versionObject



32
33
34
35
# File 'lib/cnvrg/cli.rb', line 32

def version

  puts Cnvrg::VERSION
end