Merge branch 'master' into 1932-job-output-persistent
authorTom Clegg <tom@curoverse.com>
Fri, 28 Mar 2014 00:25:07 +0000 (20:25 -0400)
committerTom Clegg <tom@curoverse.com>
Fri, 28 Mar 2014 00:25:07 +0000 (20:25 -0400)
Conflicts:
doc/user/tutorials/tutorial-firstscript.html.textile.liquid
doc/user/tutorials/tutorial-new-pipeline.html.textile.liquid
sdk/cli/bin/arv-run-pipeline-instance
services/api/db/schema.rb

88 files changed:
apps/workbench/README.textile
apps/workbench/app/controllers/users_controller.rb
apps/workbench/app/models/user.rb
apps/workbench/app/views/layouts/application.html.erb
apps/workbench/app/views/pipeline_instances/_show_components.html.erb
apps/workbench/app/views/users/_show_admin.html.erb
apps/workbench/app/views/users/_tables.html.erb
apps/workbench/config/routes.rb
apps/workbench/doc/README_FOR_APP [deleted file]
apps/workbench/test/integration/api_client_authorizations_test.rb [deleted file]
apps/workbench/test/integration/logins_test.rb
apps/workbench/test/integration/smoke_test.rb [new file with mode: 0644]
apps/workbench/test/integration_helper.rb
doc/README.textile
doc/_config.yml
doc/_includes/_webring.liquid
doc/api/schema/ApiClient.html.textile.liquid
doc/api/schema/ApiClientAuthorization.html.textile.liquid
doc/api/schema/AuthorizedKey.html.textile.liquid
doc/api/schema/Collection.html.textile.liquid
doc/api/schema/Commit.html.textile.liquid
doc/api/schema/CommitAncestor.html.textile.liquid
doc/api/schema/Group.html.textile.liquid
doc/api/schema/Human.html.textile.liquid
doc/api/schema/Job.html.textile.liquid
doc/api/schema/JobTask.html.textile.liquid
doc/api/schema/KeepDisk.html.textile.liquid
doc/api/schema/Link.html.textile.liquid
doc/api/schema/Log.html.textile.liquid
doc/api/schema/Node.html.textile.liquid
doc/api/schema/PipelineInstance.html.textile.liquid
doc/api/schema/PipelineTemplate.html.textile.liquid
doc/api/schema/Repository.html.textile.liquid
doc/api/schema/Specimen.html.textile.liquid
doc/api/schema/Trait.html.textile.liquid
doc/api/schema/User.html.textile.liquid
doc/api/schema/VirtualMachine.html.textile.liquid
doc/gen_api_schema_docs.py
doc/images/dax-reading-book.png [new file with mode: 0644]
doc/index.html.liquid
doc/sdk/cli/index.html.textile.liquid [new file with mode: 0644]
doc/sdk/index.html.textile.liquid
doc/sdk/perl/index.html.textile.liquid [new file with mode: 0644]
doc/sdk/ruby/index.html.textile.liquid [new file with mode: 0644]
doc/user/copying/agpl-3.0.html
doc/user/reference/job-and-pipeline-reference.html.textile.liquid [new file with mode: 0644]
doc/user/topics/keep.html.textile.liquid
doc/user/topics/running-pipeline-command-line.html.textile.liquid
doc/user/topics/tutorial-gatk-variantfiltration.html.textile.liquid
doc/user/topics/tutorial-job1.html.textile.liquid
doc/user/topics/tutorial-parallel.html.textile.liquid
doc/user/tutorials/running-external-program.html.textile.liquid
doc/user/tutorials/tutorial-firstscript.html.textile.liquid
doc/user/tutorials/tutorial-new-pipeline.html.textile.liquid
doc/user/tutorials/tutorial-pipeline-workbench.html.textile.liquid
sdk/cli/bin/arv
sdk/cli/bin/arv-run-pipeline-instance
sdk/cli/bin/crunch-job
services/api/app/controllers/arvados/v1/jobs_controller.rb
services/api/app/controllers/arvados/v1/schema_controller.rb
services/api/app/controllers/arvados/v1/users_controller.rb
services/api/app/models/commit.rb
services/api/app/models/job.rb
services/api/app/models/user.rb
services/api/config/application.default.yml
services/api/config/application.yml.example
services/api/config/environment.rb
services/api/config/routes.rb
services/api/db/migrate/20140317135600_add_nondeterministic_column_to_job.rb [new file with mode: 0644]
services/api/db/migrate/20140319160547_separate_repository_from_script_version.rb [new file with mode: 0644]
services/api/db/migrate/20140321191343_add_repository_column_to_job.rb [new file with mode: 0644]
services/api/db/schema.rb
services/api/script/crunch-dispatch.rb
services/api/script/rails
services/api/script/setup-new-user.rb [new file with mode: 0755]
services/api/test/fixtures/collections.yml
services/api/test/fixtures/jobs.yml
services/api/test/fixtures/links.yml
services/api/test/fixtures/repositories.yml [new file with mode: 0644]
services/api/test/functional/arvados/v1/commits_controller_test.rb [new file with mode: 0644]
services/api/test/functional/arvados/v1/git_setup.rb [new file with mode: 0644]
services/api/test/functional/arvados/v1/job_reuse_controller_test.rb [new file with mode: 0644]
services/api/test/functional/arvados/v1/jobs_controller_test.rb
services/api/test/functional/arvados/v1/schema_controller_test.rb
services/api/test/functional/arvados/v1/users_controller_test.rb
services/api/test/test.git.tar [new file with mode: 0644]
services/keep/keep.go [new file with mode: 0644]
services/keep/keep_test.go [new file with mode: 0644]

index e249b1338bb76a93a1c50330e66a8b9f97a93adb..ea01724b075befb352c6e7ccc9950ce7436a6ec5 100644 (file)
@@ -8,6 +8,8 @@ The Workbench application includes a series of integration tests.  When you run
 
 In addition to bundled gems, running the integration tests requires "PhantomJS":http://phantomjs.org/download.html to test JavaScript elements.  The simplest way to get started is to download one of the binary builds provided, and install the executable into one of the directories in your @$PATH@.
 
+If you install the Workbench Bundle in deployment mode, you must also install the API server Bundle in deployment mode, and vice versa.  If your Bundle installs have mismatched modes, the integration tests will fail with "Gem not found" errors.
+
 h2. Writing tests
 
 Integration tests are written with Capybara, which drives a fully-featured Web browser to interact with Workbench exactly as a user would.
index 35c9660d6ccdf55a29b165efecd3cb402ceb9e96..fc4953e30ccf7f56c7769ab4e772715813cbce21 100644 (file)
@@ -1,7 +1,7 @@
 class UsersController < ApplicationController
   skip_before_filter :find_object_by_uuid, :only => [:welcome, :activity]
   skip_around_filter :thread_with_mandatory_api_token, :only => :welcome
-  before_filter :ensure_current_user_is_admin, only: :sudo
+  before_filter :ensure_current_user_is_admin, only: [:sudo, :unsetup]
 
   def welcome
     if current_user
@@ -137,4 +137,12 @@ class UsersController < ApplicationController
       f.html { render template: 'users/home' }
     end
   end
+
+  def unsetup
+    if current_user.andand.is_admin
+      @object.unsetup
+    end
+    show
+  end
+
 end
index cc9b9bb058cea3e2696eaf37a85559fde93d1431..6c889e602d1e8e31c5746d0625131b516da8ea90 100644 (file)
@@ -38,4 +38,11 @@ class User < ArvadosBase
   def friendly_link_name
     [self.first_name, self.last_name].compact.join ' '
   end
+
+  def unsetup
+    self.private_reload($arvados_api_client.api(self.class,
+                                                "/#{self.uuid}/unsetup",
+                                                {}))
+  end
+
 end
index b5c75fc64f9020b7e8faa624c8b0de5b7e74ea36..63cf67c263f8b0f5eeb20be7c5add52e3acf0a31 100644 (file)
         -->
 
         <li class="dropdown notification-menu">
-          <a href="#" class="dropdown-toggle" data-toggle="dropdown">
+          <a href="#" class="dropdown-toggle" data-toggle="dropdown" id="collections-menu">
             <span class="glyphicon glyphicon-paperclip"></span>
             <span class="badge" id="persistent-selection-count"></span>
             <span class="caret"></span>
 
         <% if current_user.is_active %>
         <li class="dropdown notification-menu">
-          <a href="#" class="dropdown-toggle" data-toggle="dropdown">
+          <a href="#" class="dropdown-toggle" data-toggle="dropdown" id="notifications-menu">
             <span class="glyphicon glyphicon-envelope"></span>
             <span class="badge badge-alert notification-count"><%= @notification_count %></span>
             <span class="caret"></span>
index 638fb8e037910d4f63e55786b29a09ed9270e29a..69dd62ec08d088078bfe75fb9ca0d69914384d98 100644 (file)
 <% content_for :js do %>
 setInterval(function(){$('a.refresh').click()}, 15000);
 <% end %>
+
+<% content_for :tab_line_buttons do %>
+  <%= form_tag @object, :method => :put do |f| %>
+    
+    <%= hidden_field @object.class.to_s.underscore.singularize.to_sym, :active, :value => false %>
+
+    <%= button_tag "Stop pipeline", {class: 'btn btn-primary pull-right', id: "run-pipeline-button"} %>
+  <% end %>
+<% end %>
+
 <% end %>
 
 <% else %>
index 6e60b5d64b13ad9122829e05af84b90e056777c4..90afd1132891e3613a49f59d502c87dc1d8fce45 100644 (file)
@@ -5,3 +5,9 @@ account.</p>
 <blockquote>
 <%= button_to "Log in as #{@object.full_name}", sudo_user_url(id: @object.uuid), class: 'btn btn-primary' %>
 </blockquote>
+
+<p>As an admin, you can deactivate and reset this user. This will remove all repository/VM permissions for the user. If you "setup" the user again, the user will have to sign the user agreement again.</p>
+
+<blockquote>
+<%= button_to "Deactivate #{@object.full_name}", unsetup_user_url(id: @object.uuid), class: 'btn btn-primary', confirm: "Are you sure you want to deactivate #{@object.full_name}?"%>
+</blockquote>
index bb38c7c0faf1fa48d735e860052a2595119f5b45..9e1c220fd66d928a4b2630a23d32d5f7b75a93ad 100644 (file)
@@ -35,7 +35,7 @@
 
            <td>
              <small>
-               <% if j.success %>
+               <% if j.success and j.output %>
 
                  <a href="<%= collection_path(j.output) %>">
                    <% Collection.limit(1).where(uuid: j.output).each do |c| %>
         <span class="glyphicon glyphicon-search"></span>
         <% end %>
       </span>
-    </div>  
+    </div>
     <% end %>
   </div>
   <% if not current_user.andand.is_active or @my_collections.empty? %>
        <p>
          Your account must be activated by an Arvados administrator.  If this
          is your first time accessing Arvados and would like to request
-         access, or you believe you are seeing the page in error, please 
-         <%= link_to "contact us", Rails.configuration.activation_contact_link %>.  
+         access, or you believe you are seeing the page in error, please
+         <%= link_to "contact us", Rails.configuration.activation_contact_link %>.
          You should receive an email at the address you used to log in when
-         your account is activated.  In the mean time, you can 
+         your account is activated.  In the mean time, you can
          <%= link_to "learn more about Arvados", "https://arvados.org/projects/arvados/wiki/Introduction_to_Arvados" %>,
          and <%= link_to "read the Arvados user guide", "http://doc.arvados.org/user" %>.
        </p>
index 0981d2ea37689e7b99635ed8bd1747e4fb409f93..6504df07ff89a117f49994a7cdf6237750d1f885 100644 (file)
@@ -23,6 +23,7 @@ ArvadosWorkbench::Application.routes.draw do
     get 'welcome', :on => :collection
     get 'activity', :on => :collection
     post 'sudo', :on => :member
+    post 'unsetup', :on => :member
   end
   resources :logs
   resources :factory_jobs
diff --git a/apps/workbench/doc/README_FOR_APP b/apps/workbench/doc/README_FOR_APP
deleted file mode 100644 (file)
index fe41f5c..0000000
+++ /dev/null
@@ -1,2 +0,0 @@
-Use this README file to introduce your application and point to useful places in the API for learning more.
-Run "rake doc:app" to generate API documentation for your models, controllers, helpers, and libraries.
diff --git a/apps/workbench/test/integration/api_client_authorizations_test.rb b/apps/workbench/test/integration/api_client_authorizations_test.rb
deleted file mode 100644 (file)
index 6312034..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-require 'integration_helper'
-
-class ApiClientAuthorizationsTest < ActionDispatch::IntegrationTest
-  test "try loading Manage API tokens page" do
-    Capybara.current_driver = Capybara.javascript_driver
-    visit page_with_token('admin_trustedclient')
-    click_link 'user-menu'
-    click_link 'Manage API tokens'
-    assert_equal 200, status_code
-  end
-end
index 84170dd33b6b8b98c9f68fb43ae3569901aa2689..185d9cb017f55ee66412d7df5e616bc96d55a881 100644 (file)
@@ -3,7 +3,7 @@ require 'test_helper'
 class LoginsTest < ActionDispatch::IntegrationTest
   test "login with api_token works after redirect" do
     visit page_with_token('active_trustedclient')
-    assert page.has_text? 'Recent jobs'
+    assert page.has_text?('Recent jobs'), "Missing 'Recent jobs' from page"
     assert_no_match(/\bapi_token=/, current_path)
   end
 
diff --git a/apps/workbench/test/integration/smoke_test.rb b/apps/workbench/test/integration/smoke_test.rb
new file mode 100644 (file)
index 0000000..700c8e6
--- /dev/null
@@ -0,0 +1,39 @@
+require 'integration_helper'
+require 'uri'
+
+class SmokeTest < ActionDispatch::IntegrationTest
+  def assert_visit_success(allowed=[200])
+    assert_includes(allowed, status_code,
+                    "#{current_url} returned #{status_code}, not one of " +
+                    allowed.inspect)
+  end
+
+  def all_links_in(find_spec, text_regexp=//)
+    find(find_spec).all('a').collect { |tag|
+      if tag[:href].nil? or tag[:href].empty? or (tag.text !~ text_regexp)
+        nil
+      else
+        url = URI(tag[:href])
+        url.host.nil? ? url.path : nil
+      end
+    }.compact
+  end
+
+  test "all first-level links succeed" do
+    visit page_with_token('active_trustedclient', '/')
+    assert_visit_success
+    click_link 'user-menu'
+    urls = [all_links_in('.arvados-nav'),
+            all_links_in('.navbar', /^Manage /)].flatten
+    seen_urls = ['/']
+    while not (url = urls.shift).nil?
+      next if seen_urls.include? url
+      visit url
+      seen_urls << url
+      assert_visit_success
+      # Uncommenting the line below lets you crawl the entire site for a
+      # more thorough test.
+      # urls += all_links_in('body')
+    end
+  end
+end
index 8e317ba4e238ae179e3d10c3ee82ca42ffcf311d..86162834c7ccc40b11c4b42fc65b5a04839c1acb 100644 (file)
@@ -51,11 +51,20 @@ class IntegrationTestRunner < MiniTest::Unit
       _system('bundle', 'exec', 'rake', 'db:test:load')
       _system('bundle', 'exec', 'rake', 'db:fixtures:load')
       _system('bundle', 'exec', 'rails', 'server', '-d')
-      timeout = Time.now.tv_sec + 5
-      while (not File.exists? SERVER_PID_PATH) and (Time.now.tv_sec < timeout)
+      timeout = Time.now.tv_sec + 10
+      begin
         sleep 0.2
+        begin
+          server_pid = IO.read(SERVER_PID_PATH).to_i
+          good_pid = (server_pid > 0) and (Process.kill(0, pid) rescue false)
+        rescue Errno::ENOENT
+          good_pid = false
+        end
+      end while (not good_pid) and (Time.now.tv_sec < timeout)
+      if not good_pid
+        raise RuntimeError, "could not find API server Rails pid"
       end
-      IO.read(SERVER_PID_PATH).to_i
+      server_pid
     end
     begin
       super(args)
index 23a82fe5b115e25468666e23980008d497ef7d50..f88d30435c20ff1af435e8e37f9340f80a03622d 100644 (file)
@@ -18,6 +18,12 @@ h2. 1. Generate HTML pages
 arvados/doc$ rake
 </pre>
 
+Alternately, to make the documentation browsable on the local filesystem:
+
+<pre>
+arvados/doc$ rake generate baseurl=$PWD/.site
+</pre>
+
 h2. 2. Preview HTML pages
 
 <pre>
index 8d4fd5e115e361527131b3b01904310e63c304db..1fadc55d7d18ca90eaf8062cec9e157074480c45 100644 (file)
@@ -40,6 +40,7 @@ navbar:
     - Reference:
       - user/reference/api-tokens.html.textile.liquid
       - user/reference/sdk-cli.html.textile.liquid
+      - user/reference/job-and-pipeline-reference.html.textile.liquid
     - Arvados License:
       - user/copying/copying.html.textile.liquid
       - user/copying/agpl-3.0.html
@@ -52,6 +53,12 @@ navbar:
       - sdk/python/sdk-python.html.textile.liquid
       - sdk/python/python.html.textile.liquid
       - sdk/python/crunch-utility-libraries.html.textile.liquid
+    - Perl:
+      - sdk/perl/index.html.textile.liquid
+    - Ruby:
+      - sdk/ruby/index.html.textile.liquid
+    - CLI:
+      - sdk/cli/index.html.textile.liquid
   api:
     - Concepts:
       - api/index.html.textile.liquid
index edcfedf2e00c0571ff5c4be51280ae6a07824777..7cb9468d4efda636c17316922433fa5ca12d11da 100644 (file)
@@ -8,9 +8,9 @@
       {% if nx == 1 %}
         <hr>
         {% if prev != "" %}
-          <a href="{{ site.baseurl }}{{ prev.url }}" class="pull-left">Previous: {{ prev.title }}</a></li>
+          <a href="{{ site.baseurl }}{{ prev.url }}" class="pull-left">Previous: {{ prev.title }}</a>
         {% endif %}
-        <a href="{{ site.baseurl }}{{ p.url }}" class="pull-right">Next: {{ p.title }}</a></li>            
+        <a href="{{ site.baseurl }}{{ p.url }}" class="pull-right">Next: {{ p.title }}</a>
         {% assign nx = 0 %}
         {% assign n = 1 %}
       {% endif %}
@@ -24,6 +24,6 @@
 {% endfor %}
 {% if n == 0 && prev != "" %}
   <hr>
-  <a href="{{ site.baseurl }}{{ prev.url }}" class="pull-left">Previous: {{ prev.title }}</a></li>  
+  <a href="{{ site.baseurl }}{{ prev.url }}" class="pull-left">Previous: {{ prev.title }}</a>
   {% assign n = 1 %}
 {% endif %}
\ No newline at end of file
index 402d9ab7d6ded136545730262e7866ded83cb496..914537d207b4a0c5418bb9f8ae984c0fe831d807 100644 (file)
@@ -13,7 +13,7 @@ An **ApiClient** represents a client program that has issued a request to the AP
 
 h2. Methods
 
-See "REST methods for working with Arvados resources":/api/methods.html
+See "REST methods for working with Arvados resources":{{site.baseurl}}/api/methods.html
 
 API endpoint base: @https://{{ site.arvados_api_host }}/arvados/v1/api_clients@
 
@@ -29,7 +29,7 @@ Side effects of creating an ApiClient.
 
 h2. Resources
 
-Each ApiClient has, in addition to the usual "attributes of Arvados resources":/api/resources.html:
+Each ApiClient has, in addition to the usual "attributes of Arvados resources":{{site.baseurl}}/api/resources.html:
 
 table(table table-bordered table-condensed).
 |_. Attribute|_. Type|_. Description|_. Example|
index 2c0945b20364e3a2f231d2dc8bb60408623a80a7..d4bbd59525c65c32c9ea05f5d224c204a03fe3e6 100644 (file)
@@ -12,7 +12,7 @@ A **ApiClientAuthorization** represents the API authorization token that has bee
 
 h2. Methods
 
-See "REST methods for working with Arvados resources":/api/methods.html
+See "REST methods for working with Arvados resources":{{site.baseurl}}/api/methods.html
 
 API endpoint base: @https://{{ site.arvados_api_host }}/arvados/v1/api_client_authorizations@
 
index cb3443db42d683e2cfb57e61022637604be233c6..f3dd8478380ec274d87d8951363af5bda9b23dab 100644 (file)
@@ -3,7 +3,6 @@ layout: default
 navsection: api
 navmenu: Schema
 title: AuthorizedKey
-
 ...
 
 
@@ -12,7 +11,7 @@ A **AuthorizedKey** represents...
 
 h2. Methods
 
-See "REST methods for working with Arvados resources":/api/methods.html
+See "REST methods for working with Arvados resources":{{site.baseurl}}/api/methods.html
 
 API endpoint base: @https://{{ site.arvados_api_host }}/arvados/v1/authorized_keys@
 
@@ -28,7 +27,7 @@ Side effects of creating a AuthorizedKey.
 
 h2. Resources
 
-Each AuthorizedKey has, in addition to the usual "attributes of Arvados resources":/api/resources.html:
+Each AuthorizedKey has, in addition to the usual "attributes of Arvados resources":{{site.baseurl}}/api/resources.html:
 
 table(table table-bordered table-condensed).
 |_. Attribute|_. Type|_. Description|_. Example|
index ff08d816db33c55fab5c5997269a5bc7a5a7fc1d..2aa558a051eb8b8ab07d6b4253e67b7aed75f8e3 100644 (file)
@@ -8,12 +8,12 @@ title: Collection
 
 
 
-This resource concerns metadata, usage accounting, and integrity checks for data stored on the cloud.  Reading and writing the data _per se_ is achieved by the "Keep":/user/tutorials/tutorial-keep.html storage system.
+This resource concerns metadata, usage accounting, and integrity checks for data stored on the cloud.  Reading and writing the data _per se_ is achieved by the "Keep":{{site.baseurl}}/user/tutorials/tutorial-keep.html storage system.
 
 
 h2. Methods
 
-See "REST methods for working with Arvados resources":/api/methods.html
+See "REST methods for working with Arvados resources":{{site.baseurl}}/api/methods.html
 
 API endpoint base: @https://{{ site.arvados_api_host }}/arvados/v1/links@
 
@@ -31,7 +31,7 @@ Clients can request checks of data integrity and storage redundancy.
 
 h2. Resource
 
-Each collection has, in addition to the usual "attributes of Arvados resources":/api/resources.html:
+Each collection has, in addition to the usual "attributes of Arvados resources":{{site.baseurl}}/api/resources.html:
 
 table(table table-bordered table-condensed).
 |_. Attribute|_. Type|_. Description|_. Example|
index 0c33859b083a63affafb5b2bdba7e02dafe602a2..36de53fa875bc310b528c425d0bc3030863ec0a2 100644 (file)
@@ -12,7 +12,7 @@ A **Commit** represents...
 
 h2. Methods
 
-See "REST methods for working with Arvados resources":/api/methods.html
+See "REST methods for working with Arvados resources":{{site.baseurl}}/api/methods.html
 
 API endpoint base: @https://{{ site.arvados_api_host }}/arvados/v1/commits@
 
@@ -28,7 +28,7 @@ Side effects of creating a Commit.
 
 h2. Resources
 
-Each Commit has, in addition to the usual "attributes of Arvados resources":/api/resources.html:
+Each Commit has, in addition to the usual "attributes of Arvados resources":{{site.baseurl}}/api/resources.html:
 
 table(table table-bordered table-condensed).
 |_. Attribute|_. Type|_. Description|_. Example|
index c1bc47264a90e6408135b8fd57e2a7022f1d4f21..b488785fa2f116702c1cee260ffe293a0b5d449d 100644 (file)
@@ -12,7 +12,7 @@ A **CommitAncestor** represents...
 
 h2. Methods
 
-See "REST methods for working with Arvados resources":/api/methods.html
+See "REST methods for working with Arvados resources":{{site.baseurl}}/api/methods.html
 
 API endpoint base: @https://{{ site.arvados_api_host }}/arvados/v1/commit_ancestors@
 
@@ -28,7 +28,7 @@ Side effects of creating a CommitAncestor.
 
 h2. Resources
 
-Each CommitAncestor has, in addition to the usual "attributes of Arvados resources":/api/resources.html:
+Each CommitAncestor has, in addition to the usual "attributes of Arvados resources":{{site.baseurl}}/api/resources.html:
 
 table(table table-bordered table-condensed).
 |_. Attribute|_. Type|_. Description|_. Example|
index 607e26b97d367d31d92135a1ad4c3a0c60e55b89..e0e092ec9d796b3a216200ee3ef5412151912076 100644 (file)
@@ -12,7 +12,7 @@ A **Group** represents...
 
 h2. Methods
 
-See "REST methods for working with Arvados resources":/api/methods.html
+See "REST methods for working with Arvados resources":{{site.baseurl}}/api/methods.html
 
 API endpoint base: @https://{{ site.arvados_api_host }}/arvados/v1/groups@
 
@@ -28,7 +28,7 @@ Side effects of creating a Group.
 
 h2. Resources
 
-Each Group has, in addition to the usual "attributes of Arvados resources":/api/resources.html:
+Each Group has, in addition to the usual "attributes of Arvados resources":{{site.baseurl}}/api/resources.html:
 
 table(table table-bordered table-condensed).
 |_. Attribute|_. Type|_. Description|_. Example|
index 5ddb6e41ab9397bb2b1f8ef7f3692dd3f8652eea..66bc5f19690e5cfa228608fe0f37e793037ec9b0 100644 (file)
@@ -12,7 +12,7 @@ A **Human** represents...
 
 h2. Methods
 
-See "REST methods for working with Arvados resources":/api/methods.html
+See "REST methods for working with Arvados resources":{{site.baseurl}}/api/methods.html
 
 API endpoint base: @https://{{ site.arvados_api_host }}/arvados/v1/humans@
 
@@ -28,7 +28,7 @@ Side effects of creating a Human.
 
 h2. Resources
 
-Each Human has, in addition to the usual "attributes of Arvados resources":/api/resources.html:
+Each Human has, in addition to the usual "attributes of Arvados resources":{{site.baseurl}}/api/resources.html:
 
 table(table table-bordered table-condensed).
 |_. Attribute|_. Type|_. Description|_. Example|
index 77579ffdb5096fa3d44af710218b52c364cb8ea8..47f878583289adbcd2e7613e688924f77d09c89b 100644 (file)
@@ -15,7 +15,7 @@ Applications submit compute jobs when:
 
 h2. Methods
 
-See "REST methods for working with Arvados resources":/api/methods.html
+See "REST methods for working with Arvados resources":{{site.baseurl}}/api/methods.html
 
 API endpoint base: @https://{{ site.arvados_api_host }}/arvados/v1/jobs@
 
@@ -37,11 +37,11 @@ where[owner_uuid]=xyzzy-tpzed-a4lcehql0dv2u25
 
 &rarr; Job resource list
 
-This method is equivalent to the "index method":/api/methods.html#index, except that the results are restricted to queued jobs (i.e., jobs that have not yet been started or cancelled) and order defaults to queue priority.
+This method is equivalent to the "index method":{{site.baseurl}}/api/methods.html#index, except that the results are restricted to queued jobs (i.e., jobs that have not yet been started or cancelled) and order defaults to queue priority.
 
 h2. Resource
 
-Each job has, in addition to the usual "attributes of Arvados resources":/api/resources.html:
+Each job has, in addition to the usual "attributes of Arvados resources":{{site.baseurl}}/api/resources.html:
 
 table(table table-bordered table-condensed).
 |_. Attribute|_. Type|_. Description|_. Notes|
index 4e7aee97cdaf3c792af16192ed77c32bcaad51cc..67c16ff62ea0b4ccbd2caebd36012e0f8f7dfe21 100644 (file)
@@ -22,13 +22,13 @@ Job tasks have particular update semantics:
 
 h2. Methods
 
-See "REST methods for working with Arvados resources":/api/methods.html
+See "REST methods for working with Arvados resources":{{site.baseurl}}/api/methods.html
 
 API endpoint base: @https://{{ site.arvados_api_host }}/arvados/v1/job_tasks@
 
 h2. Resources
 
-Each JobTask has, in addition to the usual "attributes of Arvados resources":/api/resources.html:
+Each JobTask has, in addition to the usual "attributes of Arvados resources":{{site.baseurl}}/api/resources.html:
 
 table(table table-bordered table-condensed).
 |_. Attribute|_. Type|_. Description|_. Example|
index abfb368b060eecb3cda994eaaea39a3f1ad635a1..8779b1fe25ced7fb5c3742b38fd8e2fe41f84db1 100644 (file)
@@ -12,7 +12,7 @@ A **KeepDisk** represents...
 
 h2. Methods
 
-See "REST methods for working with Arvados resources":/api/methods.html
+See "REST methods for working with Arvados resources":{{site.baseurl}}/api/methods.html
 
 API endpoint base: @https://{{ site.arvados_api_host }}/arvados/v1/keep_disks@
 
@@ -28,7 +28,7 @@ Side effects of creating a KeepDisk.
 
 h2. Resources
 
-Each KeepDisk has, in addition to the usual "attributes of Arvados resources":/api/resources.html:
+Each KeepDisk has, in addition to the usual "attributes of Arvados resources":{{site.baseurl}}/api/resources.html:
 
 table(table table-bordered table-condensed).
 |_. Attribute|_. Type|_. Description|_. Example|
index 1191f875b3a5441480809d2bf9f14698e3047a00..355605578759982a245360a2f58b27118897e117 100644 (file)
@@ -16,13 +16,13 @@ For links that don't make sense to share between API clients, a _link_class_ tha
 
 h2. Methods
 
-See "REST methods for working with Arvados resources":/api/methods.html
+See "REST methods for working with Arvados resources":{{site.baseurl}}/api/methods.html
 
 API endpoint base: @https://{{ site.arvados_api_host }}/arvados/v1/links@
 
 h2. Resource
 
-Each link has, in addition to the usual "attributes of Arvados resources":/api/resources.html:
+Each link has, in addition to the usual "attributes of Arvados resources":{{site.baseurl}}/api/resources.html:
 
 table(table table-bordered table-condensed).
 |_. Attribute|_. Type|_. Description|
index c9530f490415f968fda19c43945332b112cce408..3f00339a9c2570853a8083f46d0e3d64fcdde0f2 100644 (file)
@@ -12,7 +12,7 @@ title: Log
 
 h2. Methods
 
-See "REST methods for working with Arvados resources":/api/methods.html
+See "REST methods for working with Arvados resources":{{site.baseurl}}/api/methods.html
 
 API endpoint base: @https://{{ site.arvados_api_host }}/arvados/v1/logs@
 
@@ -26,7 +26,7 @@ At the time of this writing, the Arvados system uses Logs only to record interac
 
 h2. Resources
 
-Each Log has, in addition to the usual "attributes of Arvados resources":/api/resources.html:
+Each Log has, in addition to the usual "attributes of Arvados resources":{{site.baseurl}}/api/resources.html:
 
 table(table table-bordered table-condensed).
 |_. Attribute|_. Type|_. Description|_. Example|
index a067fbe465c39537755279120b03370e87f39955..6a4331aa0ce4d57e5d9513dd04ce52e8790ba23f 100644 (file)
@@ -12,7 +12,7 @@ A **Node** represents...
 
 h2. Methods
 
-See "REST methods for working with Arvados resources":/api/methods.html
+See "REST methods for working with Arvados resources":{{site.baseurl}}/api/methods.html
 
 API endpoint base: @https://{{ site.arvados_api_host }}/arvados/v1/nodes@
 
@@ -28,7 +28,7 @@ Side effects of creating a Node.
 
 h2. Resources
 
-Each Node has, in addition to the usual "attributes of Arvados resources":/api/resources.html:
+Each Node has, in addition to the usual "attributes of Arvados resources":{{site.baseurl}}/api/resources.html:
 
 table(table table-bordered table-condensed).
 |_. Attribute|_. Type|_. Description|_. Example|
index ecb9520fdbb9971470e95a814e9cb4fe58142131..bd1009d9d87453c79562ece76e12678f30da31f4 100644 (file)
@@ -12,7 +12,7 @@ A **PipelineInstance** represents...
 
 h2. Methods
 
-See "REST methods for working with Arvados resources":/api/methods.html
+See "REST methods for working with Arvados resources":{{site.baseurl}}/api/methods.html
 
 API endpoint base: @https://{{ site.arvados_api_host }}/arvados/v1/pipeline_instances@
 
@@ -28,7 +28,7 @@ Side effects of creating a PipelineInstance.
 
 h2. Resources
 
-Each PipelineInstance has, in addition to the usual "attributes of Arvados resources":/api/resources.html:
+Each PipelineInstance has, in addition to the usual "attributes of Arvados resources":{{site.baseurl}}/api/resources.html:
 
 table(table table-bordered table-condensed).
 |_. Attribute|_. Type|_. Description|_. Example|
index d100c06988ef059b29ef0ca0d3e71798e507d2ee..c8681c3565f95b74a0fa801483ea1493ef608ae9 100644 (file)
@@ -12,7 +12,7 @@ A **PipelineTemplate** represents...
 
 h2. Methods
 
-See "REST methods for working with Arvados resources":/api/methods.html
+See "REST methods for working with Arvados resources":{{site.baseurl}}/api/methods.html
 
 API endpoint base: @https://{{ site.arvados_api_host }}/arvados/v1/pipeline_templates@
 
@@ -28,7 +28,7 @@ Side effects of creating a PipelineTemplate.
 
 h2. Resources
 
-Each PipelineTemplate has, in addition to the usual "attributes of Arvados resources":/api/resources.html:
+Each PipelineTemplate has, in addition to the usual "attributes of Arvados resources":{{site.baseurl}}/api/resources.html:
 
 table(table table-bordered table-condensed).
 |_. Attribute|_. Type|_. Description|_. Example|
index 8c751d71937d451f91d5ef3b634a8f3242055ae3..7c23eff7b2a56290dcfc85ca0f8ae7c279f6c263 100644 (file)
@@ -12,7 +12,7 @@ A **Repository** represents...
 
 h2. Methods
 
-See "REST methods for working with Arvados resources":/api/methods.html
+See "REST methods for working with Arvados resources":{{site.baseurl}}/api/methods.html
 
 API endpoint base: @https://{{ site.arvados_api_host }}/arvados/v1/repositories@
 
@@ -28,7 +28,7 @@ Side effects of creating a Repository.
 
 h2. Resources
 
-Each Repository has, in addition to the usual "attributes of Arvados resources":/api/resources.html:
+Each Repository has, in addition to the usual "attributes of Arvados resources":{{site.baseurl}}/api/resources.html:
 
 table(table table-bordered table-condensed).
 |_. Attribute|_. Type|_. Description|_. Example|
index f841f0ed483df15874de6a38982d463baa27598e..4add1a4e0f71eb90064c25b426bb52c389348b48 100644 (file)
@@ -12,7 +12,7 @@ A **Specimen** represents...
 
 h2. Methods
 
-See "REST methods for working with Arvados resources":/api/methods.html
+See "REST methods for working with Arvados resources":{{site.baseurl}}/api/methods.html
 
 API endpoint base: @https://{{ site.arvados_api_host }}/arvados/v1/specimens@
 
@@ -28,7 +28,7 @@ Side effects of creating a Specimen.
 
 h2. Resources
 
-Each Specimen has, in addition to the usual "attributes of Arvados resources":/api/resources.html:
+Each Specimen has, in addition to the usual "attributes of Arvados resources":{{site.baseurl}}/api/resources.html:
 
 table(table table-bordered table-condensed).
 |_. Attribute|_. Type|_. Description|_. Example|
index d35cebeb1c4f954d749415ba527320397ac99e30..fcb975626fea2e8ada0530fd935c240aeb8e4666 100644 (file)
@@ -12,7 +12,7 @@ A **Trait** represents...
 
 h2. Methods
 
-See "REST methods for working with Arvados resources":/api/methods.html
+See "REST methods for working with Arvados resources":{{site.baseurl}}/api/methods.html
 
 API endpoint base: @https://{{ site.arvados_api_host }}/arvados/v1/traits@
 
@@ -28,7 +28,7 @@ Side effects of creating a Trait.
 
 h2. Resources
 
-Each Trait has, in addition to the usual "attributes of Arvados resources":/api/resources.html:
+Each Trait has, in addition to the usual "attributes of Arvados resources":{{site.baseurl}}/api/resources.html:
 
 table(table table-bordered table-condensed).
 |_. Attribute|_. Type|_. Description|_. Example|
index a75cf7e2f02ebc0860b8de1317ede0ae1a2cdad0..461147c140144f51794d724cacf7d0626f80881d 100644 (file)
@@ -12,7 +12,7 @@ A **User** represents...
 
 h2. Methods
 
-See "REST methods for working with Arvados resources":/api/methods.html
+See "REST methods for working with Arvados resources":{{site.baseurl}}/api/methods.html
 
 API endpoint base: @https://{{ site.arvados_api_host }}/arvados/v1/users@
 
@@ -28,7 +28,7 @@ Side effects of creating a User.
 
 h2. Resources
 
-Each User has, in addition to the usual "attributes of Arvados resources":/api/resources.html:
+Each User has, in addition to the usual "attributes of Arvados resources":{{site.baseurl}}/api/resources.html:
 
 table(table table-bordered table-condensed).
 |_. Attribute|_. Type|_. Description|_. Example|
index f6dd561082b86176cabe441ac0fd6cfd5f9de1a7..6aa9c2b413c5bf5fd52cd37a1a815464436ee70b 100644 (file)
@@ -12,7 +12,7 @@ A **VirtualMachine** represents...
 
 h2. Methods
 
-See "REST methods for working with Arvados resources":/api/methods.html
+See "REST methods for working with Arvados resources":{{site.baseurl}}/api/methods.html
 
 API endpoint base: @https://{{ site.arvados_api_host }}/arvados/v1/virtual_machines@
 
@@ -28,7 +28,7 @@ Side effects of creating a VirtualMachine.
 
 h2. Resources
 
-Each VirtualMachine has, in addition to the usual "attributes of Arvados resources":/api/resources.html:
+Each VirtualMachine has, in addition to the usual "attributes of Arvados resources":{{site.baseurl}}/api/resources.html:
 
 table(table table-bordered table-condensed).
 |_. Attribute|_. Type|_. Description|_. Example|
index 632a67f4e7115ab83037a3c6adc15473a4617f86..239bedaae37fc40268689d89316e68fa43128f81 100755 (executable)
@@ -33,7 +33,6 @@ layout: default
 navsection: api
 navmenu: Schema
 title: {resource}
-navorder: {navorder}
 ---
 
 h1. {resource}
@@ -42,7 +41,7 @@ A **{resource}** represents...
 
 h2. Methods
 
-See "REST methods for working with Arvados resources":/api/methods.html
+        See "REST methods for working with Arvados resources":{{{{site.baseurl}}}}/api/methods.html
 
 API endpoint base: @https://{{{{ site.arvados_api_host }}}}/arvados/v1/{res_api_endpoint}@
 
diff --git a/doc/images/dax-reading-book.png b/doc/images/dax-reading-book.png
new file mode 100644 (file)
index 0000000..d10d3be
Binary files /dev/null and b/doc/images/dax-reading-book.png differ
index f9f51d67608a9d5687f6102daed8acb201460179..a4255b65d29c1f3dd64fd23cb98ed042806f8f06 100644 (file)
@@ -13,7 +13,7 @@ title: Arvados | Documentation
         <p>manuals, guides, and references</p>
       </div>
       <div class="col-sm-6">
-        <img src="images/dax.png" style="max-height: 10em"></img>
+        <img src="images/dax-reading-book.png" style="max-height: 10em" alt="Dax reading a book" />
       </div>
     </div>
   </div>
@@ -39,7 +39,7 @@ title: Arvados | Documentation
       </p>
       <p>
         <a href="{{ site.baseurl }}/install/index.html">Install Guide</a> &mdash; How to install Arvados on a cloud platform.
-      </p>      
+      </p>
     </div>
   </div>
 </div>
diff --git a/doc/sdk/cli/index.html.textile.liquid b/doc/sdk/cli/index.html.textile.liquid
new file mode 100644 (file)
index 0000000..3b63079
--- /dev/null
@@ -0,0 +1,61 @@
+---
+layout: default
+navsection: sdk
+navmenu: CLI
+title: "Command line SDK"
+
+...
+
+The @arv@ CLI tool provides a generic set of wrappers so you can make API calls easily. It performs some validation before connecting to the API server: for example, it refuses to do an API call if a required parameter is missing.
+
+It also provides access to Keep storage services with the @arv keep@ subcommand.
+
+h3. Usage
+
+See the "command line interface":{{site.baseurl}}/user/reference/sdk-cli.html page in the user guide.
+
+h3. Installation
+
+If you are logged in to an Arvados VM, the @arv@ should be installed.
+
+To use @arv@ elsewhere, you can either install the @arvados-cli@ gem via RubyGems or build and install the package using the arvados source tree.
+
+h4. Prerequisites: Ruby &gt;= 2.0.0 and curl libraries
+
+You can use "RVM":http://rvm.io/rvm/install to install and manage Ruby versions.
+
+<notextile>
+<pre>
+$ <code class="userinput">sudo apt-get install curl</code>
+$ <code class="userinput">sudo sh -c 'curl -sSL https://get.rvm.io | bash -s stable'</code>
+$ <code class="userinput">source /etc/profile.d/rvm.sh</code>
+</pre>
+</notextile>
+
+Install curl libraries with your system's package manager. For example, with Debian or Ubuntu:
+
+<notextile>
+<pre>
+$ <code class="userinput">sudo apt-get install libcurl3 libcurl3-gnutls libcurl4-openssl-dev</code>
+</pre>
+</notextile>
+
+h4. Option 1: install with RubyGems
+
+<notextile>
+<pre>
+$ <code class="userinput">sudo gem install arvados-cli</code>
+</pre>
+</notextile>
+
+h4. Option 2: build and install from source
+
+<notextile>
+<pre>
+$ <code class="userinput">git clone https://github.com/curoverse/arvados.git</code>
+$ <code class="userinput">cd arvados/sdk/cli</code>
+$ <code class="userinput">gem build arvados-cli.gemspec</code>
+$ <code class="userinput">sudo gem install arvados-cli-*.gem</code>
+</pre>
+</notextile>
+
index b7a4ecd6c61f371b6a5920fc51d0a2cb875660de..061e96421a1769f148351fa87cdc48101963bf48 100644 (file)
@@ -6,4 +6,12 @@ title: "Arvados SDK Reference"
 
 This section documents how to access the Arvados API and Keep using various programming languages.
 
-* "Python SDK":python/sdk-python.html
+* "Python SDK":{{site.baseurl}}/sdk/python/sdk-python.html
+* "Perl SDK":{{site.baseurl}}/sdk/perl/index.html
+* "Ruby SDK":{{site.baseurl}}/sdk/ruby/index.html
+* "Command line SDK":{{site.baseurl}}/sdk/cli/index.html ("arv")
+
+SDKs not yet implemented:
+
+* Rails SDK: Workbench uses an ActiveRecord-like interface to Arvados. This hasn't yet been extracted from Workbench and packaged as a gem.
+* R and Java: We plan to support these, but they have not been implemented yet.
diff --git a/doc/sdk/perl/index.html.textile.liquid b/doc/sdk/perl/index.html.textile.liquid
new file mode 100644 (file)
index 0000000..288bc31
--- /dev/null
@@ -0,0 +1,99 @@
+---
+layout: default
+navsection: sdk
+navmenu: Perl
+title: "Perl SDK"
+
+...
+
+The Perl SDK provides a generic set of wrappers so you can make API calls easily.
+
+It should be treated as alpha/experimental. Currently, limitations include:
+* Verbose syntax.
+* No native Keep client.
+* No CPAN package.
+
+h3. Installation
+
+<notextile>
+<pre>
+$ <code class="userinput">sudo apt-get install libjson-perl libio-socket-ssl-perl libwww-perl</code>
+$ <code class="userinput">git clone https://github.com/curoverse/arvados.git</code>
+$ <code class="userinput">cd arvados/sdk/perl</code>
+$ <code class="userinput">perl Makefile.PL</code>
+$ <code class="userinput">sudo make install</code>
+</pre>
+</notextile>
+
+h4. Test installation
+
+If the SDK is installed, @perl -MArvados -e ''@ should produce no errors.
+
+If your @ARVADOS_API_HOST@ and @ARVADOS_API_TOKEN@ environment variables are set up correctly (see "api-tokens":{{site.baseurl}}/user/reference/api-tokens.html for details), the following test script should work:
+
+<notextile>
+<pre>$ <code class="userinput">perl &lt;&lt;'EOF'
+use Arvados;
+my $arv = Arvados-&gt;new('apiVersion' => 'v1');
+my $me = $arv-&gt;{'users'}-&gt;{'current'}-&gt;execute;
+print ("arvados.v1.users.current.full_name = '", $me-&gt;{'full_name'}, "'\n");
+EOF</code>
+arvados.v1.users.current.full_name = 'Your Name'
+</pre>
+</notextile>
+
+h3. Examples
+
+Set up an API client user agent:
+
+<notextile>
+<pre><code class="userinput">my $arv = Arvados->new('apiVersion' => 'v1');
+</code></pre>
+</notextile>
+
+Get the User object for the current user:
+
+<notextile>
+<pre><code class="userinput">my $current_user = $arv->{'users'}->{'current'}->execute;
+</code></pre>
+</notextile>
+
+Get the UUID of an object that was retrieved using the SDK:
+
+<notextile>
+<pre><code class="userinput">my $current_user_uuid = $current_user->{'uuid'}
+</code></pre>
+</notextile>
+
+Retrieve an object by ID:
+
+<notextile>
+<pre><code class="userinput">my $some_user = $arv->{'users'}->{'get'}->execute('uuid' => $current_user_uuid);
+</code></pre>
+</notextile>
+
+Create an object:
+
+<notextile>
+<pre><code class="userinput">my $test_link = $arv->{'links'}->{'create'}->execute('link' => { 'link_class' => 'test', 'name' => 'test' });
+</code></pre>
+</notextile>
+
+Update an object:
+
+<notextile>
+<pre><code class="userinput">my $test_link = $arv->{'links'}->{'update'}->execute(
+        'uuid' => $test_link->{'uuid'},
+        'link' => { 'properties' => { 'foo' => 'bar' } });
+</code></pre>
+</notextile>
+
+Get a list of objects:
+
+<notextile>
+<pre><code class="userinput">my $repos = $arv->{'repositories'}->{'list'}->execute;
+print ("UUID of first repo returned is ", $repos->{'items'}->[0], "\n");
+</code></pre>
+</notextile>
+
+The SDK retrieves the list of API methods from the server at run time. Therefore, the set of available methods is determined by the server version rather than the SDK version.
diff --git a/doc/sdk/ruby/index.html.textile.liquid b/doc/sdk/ruby/index.html.textile.liquid
new file mode 100644 (file)
index 0000000..1a455b1
--- /dev/null
@@ -0,0 +1,125 @@
+---
+layout: default
+navsection: sdk
+navmenu: Ruby
+title: "Ruby SDK"
+
+...
+
+The Ruby SDK provides a generic set of wrappers so you can make API calls easily.
+
+h3. Installation
+
+If you are logged in to an Arvados VM, the Ruby SDK should be installed.
+
+To use it elsewhere, you can either install the @arvados@ gem via RubyGems or build and install the package using the arvados source tree.
+
+h4. Prerequisites: Ruby &gt;= 2.0.0
+
+You can use "RVM":http://rvm.io/rvm/install to install and manage Ruby versions.
+
+h4. Option 1: install with RubyGems
+
+<notextile>
+<pre>
+$ <code class="userinput">sudo gem install arvados</code>
+</pre>
+</notextile>
+
+h4. Option 2: build and install from source
+
+<notextile>
+<pre>
+$ <code class="userinput">git clone https://github.com/curoverse/arvados.git</code>
+$ <code class="userinput">cd arvados/sdk/cli</code>
+$ <code class="userinput">gem build arvados.gemspec</code>
+$ <code class="userinput">sudo gem install arvados-*.gem</code>
+</pre>
+</notextile>
+
+h4. Test installation
+
+If the SDK is installed, @ruby -r arvados -e 'puts "OK!"'@ should produce no errors.
+
+If your @ARVADOS_API_HOST@ and @ARVADOS_API_TOKEN@ environment variables are set up correctly (see "api-tokens":{{site.baseurl}}/user/reference/api-tokens.html for details), the following test script should work:
+
+<notextile>
+<pre>$ <code class="userinput">ruby -r arvados &lt;&lt;'EOF'
+arv = Arvados.new api_version: 'v1'
+my_full_name = arv.user.current[:full_name]
+puts "arvados.v1.users.current.full_name = '#{my_full_name}'"
+EOF</code>
+arvados.v1.users.current.full_name = 'Your Name'
+</pre>
+</notextile>
+
+h3. Examples
+
+Import the module (we skipped this step above by using "ruby -r arvados"):
+
+<notextile>
+<pre><code class="userinput">require 'arvados'
+</code></pre>
+</notextile>
+
+Set up an API client user agent:
+
+<notextile>
+<pre><code class="userinput">arv = Arvados.new(apiVersion: 'v1')
+</code></pre>
+</notextile>
+
+Get the User object for the current user:
+
+<notextile>
+<pre><code class="userinput">current_user = arv.user.current
+</code></pre>
+</notextile>
+
+Get the UUID of an object that was retrieved using the SDK:
+
+<notextile>
+<pre><code class="userinput">current_user_uuid = current_user[:uuid]
+</code></pre>
+</notextile>
+
+Retrieve an object by ID:
+
+<notextile>
+<pre><code class="userinput">some_user = arv.user.get(uuid: current_user_uuid)
+</code></pre>
+</notextile>
+
+Create an object:
+
+<notextile>
+<pre><code class="userinput">new_link = arv.link.create(link: {link_class: 'test', name: 'test'})
+</code></pre>
+</notextile>
+
+Update an object:
+
+<notextile>
+<pre><code class="userinput">updated_link = arv.link.update(uuid: new_link[:uuid],
+                               link: {properties: {foo: 'bar'}})
+</code></pre>
+</notextile>
+
+Delete an object:
+
+<notextile>
+<pre><code class="userinput">arv.link.delete(uuid: new_link[:uuid])
+</code></pre>
+</notextile>
+
+Get a list of objects:
+
+<notextile>
+<pre><code class="userinput">repos = arv.repository.list
+first_repo = repos[:items][0]
+puts "UUID of first repo returned is #{first_repo[:uuid]}"</code>
+UUID of first repo returned is qr1hi-s0uqq-b1bnybpx3u5temz
+</pre>
+</notextile>
+
+The SDK retrieves the list of API methods from the server at run time. Therefore, the set of available methods is determined by the server version rather than the SDK version.
index 8b04e0a2e9cd6c5c61bb0ab2295ea584fde00443..aad493a6acff1031f8dc9202d77b42e1373156f0 100644 (file)
@@ -7,7 +7,7 @@ title: "GNU Affero General Public License"
 <p style="text-align: center;">Version 3, 19 November 2007</p>
 
 <p>Copyright &copy; 2007 Free Software Foundation,
-Inc. &lt;<a href="http://fsf.org/">http://fsf.org/</a>&gt;
+Inc. &lt;<a href="http://www.fsf.org/">http://fsf.org/</a>&gt;
  <br />
  Everyone is permitted to copy and distribute verbatim copies
  of this license document, but changing it is not allowed.</p>
diff --git a/doc/user/reference/job-and-pipeline-reference.html.textile.liquid b/doc/user/reference/job-and-pipeline-reference.html.textile.liquid
new file mode 100644 (file)
index 0000000..56f4aec
--- /dev/null
@@ -0,0 +1,223 @@
+---
+layout: default
+navsection: userguide
+title: "Job and Pipeline Reference"
+...
+
+h2. Submitting jobs
+
+table(table table-bordered table-condensed).
+|_. Attribute               |_. Type|_. Accepted values                            |_. Required|_. Description|
+|script                 |string     |filename                                      |yes        |The actual script that will be run by crunch.  Must be the name of an executable file in the crunch_scripts/ directory at the git revision specified by script_version.|
+|script_version         |string     |git branch, tag, or version hash              |yes        |The code version to run, which is available in the specified repository.  May be a git hash or tag to specify an exact version, or a branch.  If it is a branch, use the branch head.|
+|repository             |string     |name of git repository hosted by Arvados      |yes        |The repository to search for script_version.|
+|script_parameters      |object     |any JSON object                               |yes        |The input parameters for the job, with the parameter names as keys mapping to parameter values.|
+|minimum_script_version |string     |git branch, tag, or version hash              |no         |The minimum acceptable script version when deciding whether to re-use a past job.|
+|exclude_script_versions|array of strings|git branch, tag, or version hash|no         |Script versions to exclude when deciding whether to re-use a past job.|
+|nondeterministic       |boolean    |                                              |no         |If true, never re-use a past job, and flag this job so it will never be considered for re-use.|
+|no_reuse               |boolean    |                                              |no         |If true, do not re-use a past job, but this job may be re-used.|
+
+When a job is executed, the 'script_version' field is resolved to an exact git revision and the git hash for that revision is recorded in 'script_version'.  If 'script_version' can't be resolved, the job submission will be rejected.
+
+h3. Reusing jobs
+
+Because Arvados records the exact version of the script, input parameters, and runtime environment [1] that was used to run the job, if the script is deterministic (meaning that the same code version is guaranteed to produce the same outputs from the same inputs) then it is possible to re-use the results of past jobs, and avoid re-running the computation to save time.  Arvados uses the following algorithm to determine if a past job can be re-used:
+
+notextile. <div class="spaced-out">
+
+# If 'nondeterministic' or 'no_reuse' are true, always create a new job.
+# Find a list of acceptable values for 'script_version'.  If 'minimum_script_version' is specified, this is the set of all revisions in the git commit graph between 'minimum_script_version' and 'script_version' (inclusive) [2].  If 'minimum_script_version' is not specified, only 'script_version' is added to the list.  If 'exclude_script_versions' is specified, the listed versions are excluded from the list.
+# Select jobs have the same 'script' and 'script_parameters' attributes, and where the 'script_version' attribute is in the list of acceptable versions.  Exclude failed jobs or where 'nondeterministic' is true.
+# If there is more than one candidate job, check that all selected past jobs actually did produce the same output.
+# If everything passed, re-use one of the selected past jobs (if there is more than one match, which job will be returned is undefined).  Otherwise create a new job.
+
+fn1. As of this writing, versioning the runtime environment is still under development.
+
+fn2. This may include parallel branches if there is more than one path between 'minimum_script_version' and 'script_version' in the git commit graph.  Use 'exclude_script_versions' to blacklist specific versions.
+
+</div>
+
+h3. Examples
+
+Run the script "crunch_scripts/hash.py" in the repository "you" using the "master" branch head.  Arvados is allowed to re-use a previous job if the script_version of the past job is the same as the "master" branch head (i.e. there have not been any subsequent commits to "master").
+
+<pre>
+{
+  "script": "hash.py",
+  "repository": "you",
+  "script_version": "master",
+  "script_parameters": {
+    "input": "c1bad4b39ca5a924e481008009d94e32+210"
+  }
+}
+</pre>
+
+Run using exactly the version "d00220fb38d4b85ca8fc28a8151702a2b9d1dec5". Arvados is allowed to re-use a previous job if the script_version of that job is also "d00220fb38d4b85ca8fc28a8151702a2b9d1dec5".
+
+<pre>
+{
+  "script": "hash.py",
+  "repository": "you",
+  "script_version": "d00220fb38d4b85ca8fc28a8151702a2b9d1dec5",
+  "script_parameters": {
+    "input": "c1bad4b39ca5a924e481008009d94e32+210"
+  }
+}
+</pre>
+
+Arvados is allowed to re-use a previous job if the script_version of the past job is between "earlier_version_tag" and the head of the "master" branch (inclusive), but not "blacklisted_version_tag".  If there are no previous jobs, run the job using the head of the "master" branch as specified in "script_version".
+
+<pre>
+{
+  "script": "hash.py",
+  "repository": "you",
+  "minimum_script_version": "earlier_version_tag",
+  "script_version": "master",
+  "exclude_script_versions", ["blacklisted_version_tag"],
+  "script_parameters": {
+    "input": "c1bad4b39ca5a924e481008009d94e32+210"
+  }
+}
+</pre>
+
+Run the script "crunch_scripts/monte-carlo.py" in the repository "you" using the "master" branch head.  Because it is marked as "nondeterministic", never re-use previous jobs, and never re-use this job.
+
+<pre>
+{
+  "script": "monte-carlo.py",
+  "repository": "you",
+  "script_version": "master",
+  "nondeterministic": true,
+  "script_parameters": {
+    "input": "c1bad4b39ca5a924e481008009d94e32+210"
+  }
+}
+</pre>
+
+h2. Pipelines
+
+Pipelines consist of a set of "components".  Each component is an Arvados job submission, so when a component job is submitted, Arvados may re-use past jobs based on the rules described above.
+
+table(table table-bordered table-condensed).
+|_. Attribute    |_. Type |_. Accepted values                           |_. Required|_. Description|
+|name            |string  |any                                          |yes        |The human-readable name of the pipeline template.|
+|components      |object  |JSON object containing job submission objects|yes        |The component jobs that make up the pipeline, with the component name as the key. |
+
+h3. Script parameters
+
+When used in a pipeline, each parameter in the 'script_parameters' attribute of a component job can specify that the input parameter must be supplied by the user, or the input parameter should be linked to the output of another component.  To do this, the value of the parameter should be JSON object containing one of the following attributes:
+
+table(table table-bordered table-condensed).
+|_. Attribute    |_. Type |_. Accepted values                               |_. Description|
+|default         |any     |any                                              |The default value for this parameter.|
+|required        |boolean |true or false                                    |Specifies whether the parameter is required to have a value or not.|
+|dataclass       |string  |One of 'Collection', 'File' [3], 'number', or 'text' |Data type of this parameter.|
+|output_of       |string  |the name of another component in the pipeline    |Specifies that the value of this parameter should be set to the 'output' attribute of the job that corresponds to the specified component.|
+
+The 'output_of' parameter is especially important, as this is how components are actually linked together to form a pipeline.  Component jobs that depend on the output of other components do not run until the parent job completes and has produced output.  If the parent job fails, the entire pipeline fails.
+
+fn3. The 'File' type refers to a specific file within a Keep collection in the form 'collection_hash/filename', for example '887cd41e9c613463eab2f0d885c6dd96+83/bob.txt'.
+
+h3. Examples
+
+This a pipeline named "Filter md5 hash values" with two components, "do_hash" and "filter".  The "input" script parameter of the "do_hash" component is required to be filled in by the user, and the expected data type is "Collection".  This also specifies that the "input" script parameter of the "filter" component is the output of "do_hash", so "filter" will not run until "do_hash" completes successfully.  When the pipeline runs, past jobs that meet the criteria described above may be substituted for either or both components to avoid redundant computation.
+
+<pre>
+{
+  "name": "Filter md5 hash values",
+  "components": {
+    "do_hash": {
+      "script": "hash.py",
+      "repository": "you",
+      "script_version": "master",
+      "script_parameters": {
+        "input": {
+          "required": true,
+          "dataclass": "Collection"
+        }
+      },
+    },
+    "filter": {
+      "script": "0-filter.py",
+      "repository": "you",
+      "script_version": "master",
+      "script_parameters": {
+        "input": {
+          "output_of": "do_hash"
+        }
+      },
+    }
+  }
+}
+</pre>
+
+This pipeline consists of three components.  The components "thing1" and "thing2" both depend on "cat_in_the_hat".  Once the "cat_in_the_hat" job is complete, both "thing1" and "thing2" can run in parallel, because they do not depend on each other.
+
+<pre>
+{
+  "name": "Wreck the house",
+  "components": {
+    "cat_in_the_hat": {
+      "script": "cat.py",
+      "repository": "you",
+      "script_version": "master",
+      "script_parameters": { }
+    },
+    "thing1": {
+      "script": "thing1.py",
+      "repository": "you",
+      "script_version": "master",
+      "script_parameters": {
+        "input": {
+          "output_of": "cat_in_the_hat"
+        }
+      },
+    },
+    "thing2": {
+      "script": "thing2.py",
+      "repository": "you",
+      "script_version": "master",
+      "script_parameters": {
+        "input": {
+          "output_of": "cat_in_the_hat"
+        }
+      },
+    },
+  }
+}
+</pre>
+
+This pipeline consists of three components.  The component "cleanup" depends on "thing1" and "thing2".  Both "thing1" and "thing2" are started immediately and can run in parallel, because they do not depend on each other, but "cleanup" cannot begin until both "thing1" and "thing2" have completed.
+
+<pre>
+{
+  "name": "Clean the house",
+  "components": {
+    "thing1": {
+      "script": "thing1.py",
+      "repository": "you",
+      "script_version": "master",
+      "script_parameters": { }
+    },
+    "thing2": {
+      "script": "thing2.py",
+      "repository": "you",
+      "script_version": "master",
+      "script_parameters": { }
+    },
+    "cleanup": {
+      "script": "cleanup.py",
+      "repository": "you",
+      "script_version": "master",
+      "script_parameters": {
+        "mess1": {
+          "output_of": "thing1"
+        },
+        "mess2": {
+          "output_of": "thing2"
+        }
+      }
+    }
+  }
+}
+</pre>
index dae133abee56080005893a717cb680025a01ad98..c4778cda620d13ee33fafd9881fc8e97fe8432c3 100644 (file)
@@ -8,7 +8,7 @@ In Keep, information is stored in *data blocks*.  Data blocks are normally betwe
 
 In order to reassemble the file, Keep stores a *collection* data block which lists in sequence the data blocks that make up the original file.  A collection data block may store the information for multiple files, including a directory structure.
 
-In this example we will use @c1bad4b39ca5a924e481008009d94e32+210@ which we added to Keep in "the first Keep tutorial":{{ site.baseurl }}/users/tutorial/tutorial-keep.html.  First let us examine the contents of this collection using @arv keep get@:
+In this example we will use @c1bad4b39ca5a924e481008009d94e32+210@ which we added to Keep in "the first Keep tutorial":{{ site.baseurl }}/user/tutorials/tutorial-keep.html.  First let us examine the contents of this collection using @arv keep get@:
 
 <notextile>
 <pre><code>~$ <span class="userinput">arv keep get c1bad4b39ca5a924e481008009d94e32+210</span>
index 1b8550febc0f53e66d8b6b97f2a880e72b2ebf66..7940348f0937752299473c62a1f3868af0fa46ae 100644 (file)
@@ -16,7 +16,8 @@ In "Writing a pipeline":{{ site.baseurl }}/user/tutorials/tutorial-firstscript.h
       "script_parameters":{
         "input": "887cd41e9c613463eab2f0d885c6dd96+83"
       },
-      "script_version":"<b>you</b>:master"
+      "repository":"<b>you</b>",
+      "script_version":"master"
     },
     "filter":{
       "script":"0-filter.py",
@@ -25,7 +26,8 @@ In "Writing a pipeline":{{ site.baseurl }}/user/tutorials/tutorial-firstscript.h
           "output_of":"do_hash"
         }
       },
-      "script_version":"<b>you</b>:master"
+      "repository":"<b>you</b>",
+      "script_version":"master"
     }
   }
 }
@@ -112,7 +114,6 @@ Now check the output:
 <pre><code>~$ <span class="userinput">arv keep get 880b55fb4470b148a447ff38cacdd952+54/md5sum.txt</span>
 44b8ae3fde7a8a88d2f7ebd237625b4f var-GS000016015-ASM.tsv.bz2
 ~$ <span class="userinput">arv keep get 490cd451c8108824b8a17e3723e1f236+19/0-filter.txt</span>
-~$
 </code></pre>
 </notextile>
 
index f83c19934a56afb70a3dada213c6bf2fc939ecf4..0248325f61034511acefe6733a9e3d5a8b5f3d8c 100644 (file)
@@ -97,6 +97,7 @@ The Arvados distribution includes an example crunch script ("crunch_scripts/GATK
 ~$ <span class="userinput">cat &gt;the_job &lt;&lt;EOF
 {
  "script":"GATK2-VariantFiltration",
+ "repository":"arvados",
  "script_version":"$src_version",
  "script_parameters":
  {
index 61eaa639a62f7cb34662ae41a86bac9f10d2d4b9..58fe329ca504305b75f80504543a399f08f16769 100644 (file)
@@ -20,9 +20,9 @@ A request to run a crunch job are is described using a JSON object.  For example
 <pre><code>~$ <span class="userinput">cat &gt;the_job &lt;&lt;EOF
 {
  "script": "hash",
- "script_version": "arvados:master",
- "script_parameters":
- {
+ "repository": "arvados",
+ "script_version": "master",
"script_parameters": {
   "input": "c1bad4b39ca5a924e481008009d94e32+210"
  }
 }
@@ -34,7 +34,8 @@ EOF
 * @<<EOF@ tells the shell to direct the following lines into the standard input for @cat@ up until it sees the line @EOF@
 * @>the_job@ redirects standard output to a file called @the_job@
 * @"script"@ specifies the name of the script to run.  The script is searched for in the "crunch_scripts/" subdirectory of the @git@ checkout specified by @"script_version"@.
-* @"script_version"@ specifies the version of the script that you wish to run.  This can be in the form of an explicit @git@ revision hash, or in the form "repository:branch" (in which case it will take the HEAD of the specified branch).  Arvados logs the script version that was used in the run, enabling you to go back and re-run any past job with the guarantee that the exact same code will be used as was used in the previous run.  You can access a list of available @git@ repositories on the Arvados workbench under "Compute %(rarr)&rarr;% Code repositories":http://{{site.arvados_workbench_host}}/repositories .
+* @"repository"@ is the git repository to search for the script version.  You can access a list of available @git@ repositories on the Arvados workbench under "Compute %(rarr)&rarr;% Code repositories":https://{{site.arvados_workbench_host}}//repositories .
+* @"script_version"@ specifies the version of the script that you wish to run.  This can be in the form of an explicit @git@ revision hash, a tag, or a branch (in which case it will take the HEAD of the specified branch).  Arvados logs the script version that was used in the run, enabling you to go back and re-run any past job with the guarantee that the exact same code will be used as was used in the previous run.
 * @"script_parameters"@ are provided to the script.  In this case, the input is the locator for the collection that we inspected in the previous section.
 
 Use @arv job create@ to actually submit the job.  It should print out a JSON object which describes the newly created job:
@@ -86,7 +87,7 @@ The job is now queued and will start running as soon as it reaches the front of
 
 h2. Monitor job progress
 
-Go to the "Workbench dashboard":http://{{site.arvados_workbench_host}}.  Your job should be at the top of the "Recent jobs" table.  This table refreshes automatically.  When the job has completed successfully, it will show <span class="label label-success">finished</span> in the *Status* column.
+Go to the "Workbench dashboard":https://{{site.arvados_workbench_host}}.  Your job should be at the top of the "Recent jobs" table.  This table refreshes automatically.  When the job has completed successfully, it will show <span class="label label-success">finished</span> in the *Status* column.
 
 On the command line, you can access log messages while the job runs using @arv job log_tail_follow@:
 
@@ -96,7 +97,7 @@ This will print out the last several lines of the log for that job.
 
 h2. Inspect the job output
 
-On the "Workbench dashboard":http://{{site.arvados_workbench_host}}, look for the *Output* column of the *Recent jobs* table.  Click on the link under *Output* for your job to go to the files page with the job output.  The files page lists all the files that were output by the job.  Click on the link under the *files* column to view a file, or click on the download icon <span class="glyphicon glyphicon-download-alt"></span> to download the output file.
+On the "Workbench dashboard":https://{{site.arvados_workbench_host}}, look for the *Output* column of the *Recent jobs* table.  Click on the link under *Output* for your job to go to the files page with the job output.  The files page lists all the files that were output by the job.  Click on the link under the *files* column to view a file, or click on the download icon <span class="glyphicon glyphicon-download-alt"></span> to download the output file.
 
 On the command line, you can use @arv job get@ to access a JSON object describing the output:
 
@@ -199,7 +200,7 @@ The log collection consists of one log file named with the job id.  You can acce
 2013-12-16_20:44:38 qr1hi-8i9sb-1pm1t02dezhupss 7575  status: 0 done, 1 running, 0 todo
 2013-12-16_20:44:39 qr1hi-8i9sb-1pm1t02dezhupss 7575 0 child 7681 on compute13.1 exit 0 signal 0 success=true
 2013-12-16_20:44:39 qr1hi-8i9sb-1pm1t02dezhupss 7575 0 success in 1 seconds
-2013-12-16_20:44:39 qr1hi-8i9sb-1pm1t02dezhupss 7575 0 output 
+2013-12-16_20:44:39 qr1hi-8i9sb-1pm1t02dezhupss 7575 0 output
 2013-12-16_20:44:39 qr1hi-8i9sb-1pm1t02dezhupss 7575  wait for last 0 children to finish
 2013-12-16_20:44:39 qr1hi-8i9sb-1pm1t02dezhupss 7575  status: 1 done, 0 running, 1 todo
 2013-12-16_20:44:39 qr1hi-8i9sb-1pm1t02dezhupss 7575  start level 1
index 9d08b6988bbe6bb99d49a0f798aa31958cd5b24a..6dbdb8af23a74176e4d8767031e88c4bdbd857ac 100644 (file)
@@ -40,7 +40,8 @@ You should now be able to run your new script using Crunch, with "script" referr
 <pre><code>~/<b>you</b>/crunch_scripts$ <span class="userinput">cat &gt;~/the_job &lt;&lt;EOF
 {
  "script": "parallel-hash.py",
- "script_version": "<b>you</b>:master",
+ "repository": "<b>you</b>",
+ "script_version": "master",
  "script_parameters":
  {
   "input": "887cd41e9c613463eab2f0d885c6dd96+83"
index b555d77fe4a72d31db8157e4509f8698eaf03e2c..758faa5a9f1fd03ff31c3f30f65cae0fe6c8b968 100644 (file)
@@ -53,7 +53,8 @@ You should now be able to run your new script using Crunch, with "script" referr
           "dataclass": "Collection"
         }
       },
-      "script_version":"<b>you</b>:master"
+      "repository":"<b>you</b>",
+      "script_version":"master"
     }
   }
 }
@@ -62,4 +63,4 @@ EOF
 </code></pre>
 </notextile>
 
-Your new pipeline template will appear on the "Workbench %(rarr)&rarr;% Compute %(rarr)&rarr;% Pipeline&nbsp;templates":http://{{ site.arvados_workbench_host }}/pipeline_instances page.  You can run the "pipeline using workbench":tutorial-pipeline-workbench.html
+Your new pipeline template will appear on the "Workbench %(rarr)&rarr;% Compute %(rarr)&rarr;% Pipeline&nbsp;templates":https://{{ site.arvados_workbench_host }}/pipeline_instances page.  You can run the "pipeline using workbench":tutorial-pipeline-workbench.html
index ad2f0a4df77dfd50c95f18746fa194c4dfbce464..e2d7a8793bd12b91c217eada7a95ced8b941e658 100644 (file)
@@ -22,7 +22,7 @@ First, you should do some basic configuration for git (you only need to do this
 ~$ <span class="userinput">git config --global user.email <b>you</b>@example.com</span></code></pre>
 </notextile>
 
-On the Arvados Workbench, navigate to "Compute %(rarr)&rarr;% Code repositories":http://{{site.arvados_workbench_host}}/repositories .  You should see a repository with your user name listed in the *name* column.  Next to *name* is the column *push_url*.  Copy the *push_url* value associated with your repository.  This should look like <notextile><code>git@git.{{ site.arvados_api_host }}:<b>you</b>.git</code></notextile>.
+On the Arvados Workbench, navigate to "Compute %(rarr)&rarr;% Code repositories":https://{{site.arvados_workbench_host}}/repositories .  You should see a repository with your user name listed in the *name* column.  Next to *name* is the column *push_url*.  Copy the *push_url* value associated with your repository.  This should look like <notextile><code>git@git.{{ site.arvados_api_host }}:<b>you</b>.git</code></notextile>.
 
 Next, on the Arvados virtual machine, clone your git repository:
 
@@ -111,7 +111,8 @@ Next, create a file that contains the pipeline definition:
           "dataclass": "Collection"
         }
       },
-      "script_version":"<b>you</b>:master",
+      "repository":"<b>you</b>",
+      "script_version":"master",
       "output_is_persistent":true
     }
   }
@@ -127,7 +128,8 @@ EOF
 * @"components"@ is a set of scripts that make up the pipeline
 * The component is listed with a human-readable name (@"do_hash"@ in this example)
 * @"script"@ specifies the name of the script to run.  The script is searched for in the "crunch_scripts/" subdirectory of the @git@ checkout specified by @"script_version"@.
-* @"script_version"@ specifies the version of the script that you wish to run.  This can be in the form of an explicit @git@ revision hash, or in the form "repository:branch" (in which case it will take the HEAD of the specified branch).  Arvados logs the script version that was used in the run, enabling you to go back and re-run any past job with the guarantee that the exact same code will be used as was used in the previous run.  You can access a list of available @git@ repositories on the Arvados workbench under "Compute %(rarr)&rarr;% Code repositories":http://{{site.arvados_workbench_host}}//repositories .
+* @"repository"@ is the git repository to search for the script version.  You can access a list of available @git@ repositories on the Arvados workbench under "Compute %(rarr)&rarr;% Code repositories":https://{{site.arvados_workbench_host}}//repositories .
+* @"script_version"@ specifies the version of the script that you wish to run.  This can be in the form of an explicit @git@ revision hash, a tag, or a branch (in which case it will take the HEAD of the specified branch).  Arvados logs the script version that was used in the run, enabling you to go back and re-run any past job with the guarantee that the exact same code will be used as was used in the previous run.  
 * @"script_parameters"@ describes the parameters for the script.  In this example, there is one parameter called @input@ which is @required@ and is a @Collection@.
 * @"output_is_persistent"@ indicates whether the output of the job is considered valuable. If this value is false (or not given), the output will be treated as intermediate data and eventually deleted to reclaim disk space.
 
@@ -138,4 +140,4 @@ Now, use @arv pipeline_template create@ tell Arvados about your pipeline templat
 </code></pre>
 </notextile>
 
-Your new pipeline template will appear on the "Workbench %(rarr)&rarr;% Compute %(rarr)&rarr;% Pipeline&nbsp;templates":http://{{ site.arvados_workbench_host }}/pipeline_instances page.  You can run the "pipeline using workbench":tutorial-pipeline-workbench.html
+Your new pipeline template will appear on the "Workbench %(rarr)&rarr;% Compute %(rarr)&rarr;% Pipeline&nbsp;templates":https://{{ site.arvados_workbench_host }}/pipeline_instances page.  You can run the "pipeline using workbench":tutorial-pipeline-workbench.html
index 6852886523e9556ffec96cb477fbaeff9095b24a..fc98d01aa06f59ee98218193892c0703ceecbbd8 100644 (file)
@@ -43,7 +43,8 @@ Next, create a file that contains the pipeline definition:
           "dataclass": "Collection"
         }
       },
-      "script_version":"<b>you</b>:master",
+      "repository":"<b>you</b>",
+      "script_version":"master",
       "output_is_persistent":false
     },
     "filter":{
@@ -53,7 +54,8 @@ Next, create a file that contains the pipeline definition:
           "output_of":"do_hash"
         }
       },
-      "script_version":"<b>you</b>:master",
+      "repository":"<b>you</b>",
+      "script_version":"master",
       "output_is_persistent":true
     }
   }
@@ -71,5 +73,4 @@ Now, use @arv pipeline_template create@ tell Arvados about your pipeline templat
 </code></pre>
 </notextile>
 
-Your new pipeline template will appear on the "Workbench %(rarr)&rarr;% Compute %(rarr)&rarr;% Pipeline&nbsp;templates":http://{{ site.arvados_workbench_host }}/pipeline_templates page.
-
+Your new pipeline template will appear on the "Workbench %(rarr)&rarr;% Compute %(rarr)&rarr;% Pipeline&nbsp;templates":https://{{ site.arvados_workbench_host }}/pipeline_instances page.
index 52dafb7cce355a3d0fff948836f039e52b6d1b50..46aadd33ed4a30219f5c024ae09b0b535ba72e65 100644 (file)
@@ -6,11 +6,11 @@ title: "Running a pipeline using Workbench"
 
 notextile. <div class="spaced-out">
 
-# Go to "Collections":http://{{ site.arvados_workbench_host }}/collections .
+# Go to "Collections":https://{{ site.arvados_workbench_host }}/collections .
 # On the collections page, go to the search box <span class="glyphicon glyphicon-search"></span> and search for "tutorial".
 # This should yield a collection with the contents "var-GS000016015-ASM.tsv.bz2"
 # Click on the check box to the left of "var-GS000016015-ASM.tsv.bz2".  This puts the collection in your persistent selection list.  Click on the paperclip <span class="glyphicon glyphicon-paperclip"></span> in the upper right to get a dropdown menu listing your current selections.
-# Go to "Pipeline templates":http://{{ site.arvados_workbench_host }}/pipeline_templates .
+# Go to "Pipeline templates":https://{{ site.arvados_workbench_host }}/pipeline_templates .
 # Look for a pipeline named "Tutorial pipeline".
 # Click on the play button <span class="glyphicon glyphicon-play"></span> to the left of "Tutorial pipeline".  This will take you to a new page to configure the pipeline.
 # Under *parameter* look for "input".  Set the value of "input" by clicking on on "none" to get a editing popup.  At the top of the selection list in the editing popup will be the collection that you selected in step 4.
index 89dee6923c5c70ac92b2de7d61c1b3e6c7d010c4..f453675ea8ebb99a3d6fb0a2597afc9e852661d9 100755 (executable)
@@ -89,7 +89,7 @@ begin
 rescue LoadError
   abort <<-EOS
 
-Please install all required gems: 
+Please install all required gems:
 
   gem install activesupport andand curb google-api-client json oj trollop
 
@@ -148,8 +148,13 @@ class ArvadosClient < Google::APIClient
   end
 end
 
-client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
-arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
+begin
+  client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
+  arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
+rescue Exception => e
+  puts "Failed to connect to Arvados API server: #{e}"
+  exit 1
+end
 
 def to_boolean(s)
   !!(s =~ /^(true|t|yes|y|1)$/i)
@@ -170,8 +175,8 @@ def help_methods(discovery_document, resource, method=nil)
   end
   banner += "\n"
   STDERR.puts banner
-  
-  if not method.nil? and method != '--help' then 
+
+  if not method.nil? and method != '--help' then
     Trollop::die ("Unknown method #{method.inspect} " +
                   "for resource #{resource.inspect}")
   end
@@ -194,7 +199,7 @@ def help_resources(discovery_document, resource)
   banner += "\n"
   STDERR.puts banner
 
-  if not resource.nil? and resource != '--help' then 
+  if not resource.nil? and resource != '--help' then
     Trollop::die "Unknown resource type #{resource.inspect}"
   end
   exit 255
@@ -320,7 +325,7 @@ when
     curl.headers['Accept'] = 'text/plain'
     curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
     if ENV['ARVADOS_API_HOST_INSECURE']
-      curl.ssl_verify_peer = false 
+      curl.ssl_verify_peer = false
       curl.ssl_verify_host = false
     end
     if global_opts[:verbose]
@@ -364,5 +369,3 @@ else
     puts results['uuid']
   end
 end
-
-
index 7578abc7b0099f8cbba81aaf4775e0ac15741ec0..090be61ba49c873ac85bdb7c9973794252a8c70a 100755 (executable)
 # [--no-wait] Make only as much progress as possible without entering
 #             a sleep/poll loop.
 #
-# [--no-reuse-finished] Do not reuse existing outputs to satisfy
-#                       pipeline components. Always submit a new job
-#                       or use an existing job which has not yet
-#                       finished.
-#
 # [--no-reuse] Do not reuse existing jobs to satisfy pipeline
 #              components. Submit a new job for every component.
 #
@@ -153,10 +148,6 @@ p = Trollop::Parser.new do
       "Do not wait for jobs to finish. Just look up status, submit new jobs if needed, and exit.",
       :short => :none,
       :type => :boolean)
-  opt(:no_reuse_finished,
-      "Do not reuse existing outputs to satisfy pipeline components. Always submit a new job or use an existing job which has not yet finished.",
-      :short => :none,
-      :type => :boolean)
   opt(:no_reuse,
       "Do not reuse existing jobs to satisfy pipeline components. Submit a new job for every component.",
       :short => :none,
@@ -333,7 +324,7 @@ class JobCache
     if j.is_a? Hash and j[:uuid]
       @cache[j[:uuid]] = j
     else
-      debuglog "create job: #{j[:errors] rescue nil}", 0
+      debuglog "create job: #{j[:errors] rescue nil} with attribute #{attributes}", 0
       nil
     end
   end
@@ -439,84 +430,34 @@ class WhRunPipelineInstance
                               c[:job][:uuid] &&
                               !c[:job][:success].nil?)
         if !c[:job] and
-            c[:script_parameters].select { |pname, p| p.is_a? Hash }.empty?
-          # Job is fully specified (all parameter values are present) but
-          # no particular job has been found.
-
-          debuglog "component #{cname} ready to satisfy."
-
-          c.delete :wait
-          second_place_job = nil # satisfies component, but not finished yet
-
-          (@options[:no_reuse] ? [] : JobCache.
-           where(script: c[:script],
-                 script_parameters: c[:script_parameters],
-                 script_version_descends_from: c[:script_version])
-           ).each do |candidate_job|
-            candidate_params_downcase = Hash[candidate_job[:script_parameters].
-                                             map { |k,v| [k.downcase,v] }]
-            c_params_downcase = Hash[c[:script_parameters].
-                                     map { |k,v| [k.downcase,v] }]
-
-            debuglog "component #{cname} considering job #{candidate_job[:uuid]} version #{candidate_job[:script_version]} parameters #{candidate_params_downcase.inspect}", 3
-
-            unless candidate_params_downcase == c_params_downcase
-              next
-            end
-
-            if c[:script_version] !=
-                candidate_job[:script_version][0,c[:script_version].length]
-              debuglog "component #{cname} would be satisfied by job #{candidate_job[:uuid]} if script_version matched.", 2
-              next
-            end
-
-            unless candidate_job[:success] || candidate_job[:running] ||
-                (!candidate_job[:started_at] && !candidate_job[:cancelled_at])
-              debuglog "component #{cname} would be satisfied by job #{candidate_job[:uuid]} if it were running or successful.", 2
-              next
-            end
-
-            if candidate_job[:success]
-              unless @options[:no_reuse_finished]
-                job = candidate_job
-                $stderr.puts "using #{job[:uuid]} (finished at #{job[:finished_at]}) for component #{cname}"
-                c[:job] = job
-              end
-            else
-              second_place_job ||= candidate_job
-            end
-            break
-          end
-          if not c[:job] and second_place_job
-            job = second_place_job
-            $stderr.puts "using #{job[:uuid]} (running since #{job[:started_at]}) for component #{cname}"
+            c[:script_parameters].select { |pname, p| p.is_a? Hash and p[:output_of]}.empty?
+          # No job yet associated with this component and is component inputs
+          # are fully specified (any output_of script_parameters are resolved
+          # to real value)
+          job = JobCache.create({:script => c[:script],
+                            :script_parameters => c[:script_parameters],
+                            :script_version => c[:script_version],
+                            :repository => c[:repository],
+                            :minimum_script_version => c[:minimum_script_version],
+                            :exclude_script_versions => c[:exclude_minimum_script_versions],
+                            :nondeterministic => c[:nondeterministic],
+                            :no_reuse => @options[:no_reuse],
+                            :output_is_persistent => c[:output_is_persistent] || false})
+          if job
+            debuglog "component #{cname} new job #{job[:uuid]}"
             c[:job] = job
+          else
+            debuglog "component #{cname} new job failed"
           end
-          if not c[:job]
-            debuglog "component #{cname} not satisfied by any existing job."
-            if !@options[:dry_run]
-              debuglog "component #{cname} new job."
-              job = JobCache.create(:script => c[:script],
-                                    :script_parameters => c[:script_parameters],
-                                    :runtime_constraints => c[:runtime_constraints] || {},
-                                    :script_version => c[:script_version] || 'master',
-                                    :output_is_persistent => c[:output_is_persistent] || false)
-              if job
-                debuglog "component #{cname} new job #{job[:uuid]}"
-                c[:job] = job
-              else
-                debuglog "component #{cname} new job failed"
-              end
-            end
-          end
-        else
-          c[:wait] = true
         end
+
         if c[:job] and c[:job][:uuid]
           if (c[:job][:running] or
               not (c[:job][:finished_at] or c[:job][:cancelled_at]))
-            c[:job] = JobCache.get(c[:job][:uuid])
+            # Job is running so update copy of job record
+            c[:job] = JobCache.get(c[:job][:uuid])            
           end
+
           if c[:job][:success]
             # Populate script_parameters of other components waiting for
             # this job
@@ -566,6 +507,7 @@ class WhRunPipelineInstance
             end
           elsif c[:job][:running] ||
               (!c[:job][:started_at] && !c[:job][:cancelled_at])
+            # Job is still running
             moretodo = true
           elsif c[:job][:cancelled_at]
             debuglog "component #{cname} job #{c[:job][:uuid]} cancelled."
index d4afe61d9bcd3994584997d3cda76b4748d6e734..72f47acfce0935f8fc087004fd2d7901171c2f3d 100755 (executable)
@@ -582,7 +582,7 @@ for (my $todo_ptr = 0; $todo_ptr <= $#jobstep_todo; $todo_ptr ++)
     }
     $ENV{"TASK_SLOT_NODE"} = $slot[$childslot]->{node}->{name};
     $ENV{"TASK_SLOT_NUMBER"} = $slot[$childslot]->{cpu};
-    $ENV{"TASK_WORK"} = $ENV{"JOB_WORK"}."/".$slot[$childslot]->{cpu};
+    $ENV{"TASK_WORK"} = $ENV{"JOB_WORK"}."/$id.$$";
     $ENV{"TASK_KEEPMOUNT"} = $ENV{"TASK_WORK"}."/keep";
     $ENV{"TASK_TMPDIR"} = $ENV{"TASK_WORK"}; # deprecated
     $ENV{"CRUNCH_NODE_SLOTS"} = $slot[$childslot]->{node}->{ncpus};
index b7b0e677d63d5b5d2e5389a27a42ab1f709f34ad..b35bc4e44f8f38edb57c659ba2f21e84c12f05d2 100644 (file)
@@ -5,40 +5,53 @@ class Arvados::V1::JobsController < ApplicationController
   skip_before_filter :find_object_by_uuid, :only => :queue
   skip_before_filter :render_404_if_no_object, :only => :queue
 
-  def index
-    return super unless @where.is_a? Hash
-    want_ancestor = @where[:script_version_descends_from]
-    if want_ancestor
-      # Check for missing commit_ancestor rows, and create them if
-      # possible.
-      @objects.
-        dup.
-        includes(:commit_ancestors). # I wish Rails would let me
-                                     # specify here which
-                                     # commit_ancestors I am
-                                     # interested in.
-        each do |o|
-        if o.commit_ancestors.
-            select { |ca| ca.ancestor == want_ancestor }.
-            empty? and !o.script_version.nil?
-          begin
-            o.commit_ancestors << CommitAncestor.find_or_create_by_descendant_and_ancestor(o.script_version, want_ancestor)
-          rescue
+  def create
+    [:repository, :script, :script_version, :script_parameters].each do |r|    
+      if !resource_attrs[r]
+        return render json: {
+          :error => "#{r} attribute must be specified"
+        }, status: :unprocessable_entity      
+      end
+    end
+
+    r = Commit.find_commit_range(current_user,
+                                 resource_attrs[:repository],
+                                 resource_attrs[:minimum_script_version],
+                                 resource_attrs[:script_version],
+                                 resource_attrs[:exclude_script_versions])
+    if !resource_attrs[:nondeterministic] and !resource_attrs[:no_reuse]
+      # Search for jobs where the script_version is in the list of commits
+      # returned by find_commit_range
+      @object = nil
+      Job.readable_by(current_user).where(script: resource_attrs[:script],
+                                          script_version: r).
+        each do |j|
+        if j.nondeterministic != true and 
+            j.success != false and 
+            j.script_parameters == resource_attrs[:script_parameters]
+          # Record the first job in the list
+          if !@object
+            @object = j
+          end
+          # Ensure that all candidate jobs actually did produce the same output
+          if @object.output != j.output
+            @object = nil
+            break
           end
         end
-        o.commit_ancestors.
-          select { |ca| ca.ancestor == want_ancestor }.
-          select(&:is).
-          first
+        if @object
+          return show
+        end
       end
-      # Now it is safe to do an .includes().where() because we are no
-      # longer interested in jobs that have other ancestors but not
-      # want_ancestor.
-      @objects = @objects.
-        includes(:commit_ancestors).
-        where('commit_ancestors.ancestor = ? and commit_ancestors.is = ?',
-              want_ancestor, true)
     end
+    if r
+      resource_attrs[:script_version] = r[0]
+    end
+
+    # Don't pass these on to activerecord
+    resource_attrs.delete(:minimum_script_version)
+    resource_attrs.delete(:exclude_script_versions)
+    resource_attrs.delete(:no_reuse)
     super
   end
 
index f02a56bc62fb19274cc390643f4a232b76fb7be3..1cc84960de5f7d5cb4d1e726c8d4791869411ad1 100644 (file)
@@ -1,29 +1,10 @@
 class Arvados::V1::SchemaController < ApplicationController
+  skip_before_filter :find_objects_for_index
   skip_before_filter :find_object_by_uuid
   skip_before_filter :render_404_if_no_object
   skip_before_filter :require_auth_scope_all
 
-  def show
-    classes = Rails.cache.fetch 'arvados_v1_schema' do
-      Rails.application.eager_load!
-      classes = {}
-      ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |k|
-        classes[k] = k.columns.collect do |col|
-          if k.serialized_attributes.has_key? col.name
-            { name: col.name,
-              type: k.serialized_attributes[col.name].object_class.to_s }
-          else
-            { name: col.name,
-              type: col.type }
-          end
-        end
-      end
-      classes
-    end
-    render json: classes
-  end
-
-  def discovery_rest_description
+  def index
     expires_in 24.hours, public: true
     discovery = Rails.cache.fetch 'arvados_v1_rest_discovery' do
       Rails.application.eager_load!
@@ -37,7 +18,7 @@ class Arvados::V1::SchemaController < ApplicationController
         generatedAt: Time.now.iso8601,
         title: "Arvados API",
         description: "The API to interact with Arvados.",
-        documentationLink: "https://redmine.clinicalfuture.com/projects/arvados/",
+        documentationLink: "http://doc.arvados.org/api/index.html",
         protocol: "rest",
         baseUrl: root_url + "/arvados/v1/",
         basePath: "/arvados/v1/",
index 133df0f62c17125ead845cbb64331b3cb79290a2..c5fc38d89ac2a2b030c25053b6a6948997cdc5e7 100644 (file)
@@ -1,9 +1,10 @@
 class Arvados::V1::UsersController < ApplicationController
   skip_before_filter :find_object_by_uuid, only:
-    [:activate, :event_stream, :current, :system]
+    [:activate, :event_stream, :current, :system, :setup]
   skip_before_filter :render_404_if_no_object, only:
-    [:activate, :event_stream, :current, :system]
-
+    [:activate, :event_stream, :current, :system, :setup]
+  before_filter :admin_required, only: [:setup, :unsetup]
+  
   def current
     @object = current_user
     show
@@ -87,4 +88,56 @@ class Arvados::V1::UsersController < ApplicationController
     end
     show
   end
+
+  # create user object and all the needed links
+  def setup
+    @object = nil
+    if params[:uuid]
+      @object = User.find_by_uuid params[:uuid]
+      if !@object
+        return render_404_if_no_object
+      end
+      object_found = true
+    else
+      if !params[:user]
+        raise ArgumentError.new "Required uuid or user"
+      else
+        if params[:user]['uuid']
+          @object = User.find_by_uuid params[:user]['uuid']
+          if @object
+            object_found = true
+          end
+        end
+
+        if !@object
+          if !params[:user]['email']
+            raise ArgumentError.new "Require user email"
+          end
+
+          if !params[:openid_prefix]
+            raise ArgumentError.new "Required openid_prefix parameter is missing."
+          end
+
+          @object = model_class.create! resource_attrs
+        end
+      end
+    end
+
+    if object_found
+      @response = @object.setup_repo_vm_links params[:repo_name], params[:vm_uuid]
+    else
+      @response = User.setup @object, params[:openid_prefix],
+                    params[:repo_name], params[:vm_uuid]
+    end
+
+    render json: { kind: "arvados#HashList", items: @response }
+  end
+
+  # delete user agreements, vm, repository, login links; set state to inactive
+  def unsetup
+    reload_object_before_update
+    @object.unsetup
+    show
+  end
+
 end
index d7d0571067a70878b0712c169a79be0c3bbc1b35..6239011a1bda462dca713feec0bc18250025e54b 100644 (file)
 class Commit < ActiveRecord::Base
   require 'shellwords'
 
-  # Make sure the specified commit really exists, and return the full
-  # sha1 commit hash.
-  #
-  # Accepts anything "git rev-list" accepts, optionally (and
-  # preferably) preceded by "repo_name:".
-  #
-  # Examples: "1234567", "master", "apps:1234567", "apps:master",
-  # "apps:HEAD"
-
-  def self.find_by_commit_ish(commit_ish)
-    want_repo = nil
-    if commit_ish.index(':')
-      want_repo, commit_ish = commit_ish.split(':',2)
+  def self.git_check_ref_format(e)
+    if !e or e.empty? or e[0] == '-' or e[0] == '$'
+      # definitely not valid
+      false
+    else
+      `git check-ref-format --allow-onelevel #{e.shellescape}`
+      $?.success?
     end
-    repositories.each do |repo_name, repo|
-      next if want_repo and want_repo != repo_name
-      ENV['GIT_DIR'] = repo[:git_dir]
-      IO.foreach("|git rev-list --max-count=1 --format=oneline 'origin/'#{commit_ish.shellescape} 2>/dev/null || git rev-list --max-count=1 --format=oneline ''#{commit_ish.shellescape}") do |line|
-        sha1, message = line.strip.split " ", 2
-        next if sha1.length != 40
-        begin
-          Commit.find_or_create_by_repository_name_and_sha1_and_message(repo_name, sha1, message[0..254])
-        rescue
-          logger.warn "find_or_create failed: repo_name #{repo_name} sha1 #{sha1} message #{message[0..254]}"
-          # Ignore cache failure. Commit is real. We should proceed.
+  end
+
+  def self.find_commit_range(current_user, repository, minimum, maximum, exclude)
+    if (minimum and !git_check_ref_format(minimum)) or !git_check_ref_format(maximum)
+      logger.warn "find_commit_range called with invalid minimum or maximum: '#{minimum}', '#{maximum}'"
+      return nil
+    end
+
+    if minimum and minimum.empty?
+        minimum = nil
+    end
+
+    if !maximum
+      maximum = "HEAD"
+    end
+
+    # Get list of actual repository directories under management
+    on_disk_repos = repositories
+
+    # Get list of repository objects readable by user
+    readable = Repository.readable_by(current_user)
+
+    # filter repository objects on requested repository name
+    if repository
+      readable = readable.where(name: repository)
+    end
+
+    commits = []
+    readable.each do |r|
+      if on_disk_repos[r.name]
+        ENV['GIT_DIR'] = on_disk_repos[r.name][:git_dir]
+
+        # We've filtered for invalid characters, so we can pass the contents of
+        # minimum and maximum safely on the command line
+
+        # Get the commit hash for the upper bound
+        max_hash = nil
+        IO.foreach("|git rev-list --max-count=1 #{maximum.shellescape}") do |line|
+          max_hash = line.strip
+        end
+
+        # If not found or string is invalid, nothing else to do
+        next if !max_hash or !git_check_ref_format(max_hash)
+
+        resolved_exclude = nil
+        if exclude
+          resolved_exclude = []
+          exclude.each do |e|
+            if git_check_ref_format(e)
+              IO.foreach("|git rev-list --max-count=1 #{e.shellescape}") do |line|
+                resolved_exclude.push(line.strip)
+              end
+            else
+              logger.warn "find_commit_range called with invalid exclude invalid characters: '#{exclude}'"
+              return nil
+            end
+          end
+        end
+
+        if minimum
+          # Get the commit hash for the lower bound
+          min_hash = nil
+          IO.foreach("|git rev-list --max-count=1 #{minimum.shellescape}") do |line|
+            min_hash = line.strip
+          end
+
+          # If not found or string is invalid, nothing else to do
+          next if !min_hash or !git_check_ref_format(min_hash)
+
+          # Now find all commits between them
+          IO.foreach("|git rev-list #{min_hash.shellescape}..#{max_hash.shellescape}") do |line|
+            hash = line.strip
+            commits.push(hash) if !resolved_exclude or !resolved_exclude.include? hash
+          end
+
+          commits.push(min_hash) if !resolved_exclude or !resolved_exclude.include? min_hash
+        else
+          commits.push(max_hash) if !resolved_exclude or !resolved_exclude.include? max_hash
         end
-        return sha1
       end
     end
-    nil
+
+    if !commits or commits.empty?
+      nil
+    else
+      commits
+    end
   end
 
   # Import all commits from configured git directory into the commits
@@ -59,6 +124,10 @@ class Commit < ActiveRecord::Base
     end
   end
 
+  def self.refresh_repositories
+    @repositories = nil
+  end
+
   protected
 
   def self.repositories
@@ -70,6 +139,7 @@ class Commit < ActiveRecord::Base
       next if repo.match /^\./
       git_dir = File.join(@gitdirbase,
                           repo.match(/\.git$/) ? repo : File.join(repo, '.git'))
+      next if git_dir == Rails.configuration.git_internal_dir
       repo_name = repo.sub(/\.git$/, '')
       @repositories[repo_name] = {git_dir: git_dir}
     end
index a3fe08fdd9c4874aba1b9b7465ce644f6d6de3b9..e3881ba6e1f4bfdfc492975eac82bcccaeaba1e4 100644 (file)
@@ -37,6 +37,8 @@ class Job < ArvadosModel
     t.add :dependencies
     t.add :log_stream_href
     t.add :log_buffer
+    t.add :nondeterministic
+    t.add :repository
   end
 
   def assert_finished
@@ -57,6 +59,11 @@ class Job < ArvadosModel
       order('priority desc, created_at')
   end
 
+  def self.running
+    self.where('running = ?', true).
+      order('priority desc, created_at')
+  end
+
   protected
 
   def foreign_key_attributes
@@ -71,7 +78,7 @@ class Job < ArvadosModel
       return true
     end
     if new_record? or script_version_changed?
-      sha1 = Commit.find_by_commit_ish(self.script_version) rescue nil
+      sha1 = Commit.find_commit_range(current_user, nil, nil, self.script_version, nil)[0] rescue nil
       if sha1
         self.script_version = sha1
       else
index 0896571939e8cfd7ab9296645f8087036001fea7..c09b67cdb403538ff4d18d29ddf6f60d2bfdb35a 100644 (file)
@@ -109,6 +109,84 @@ class User < ArvadosModel
     end
   end
 
+  def self.setup(user, openid_prefix, repo_name=nil, vm_uuid=nil)
+    login_perm_props = {identity_url_prefix: openid_prefix}
+
+    # Check oid_login_perm
+    oid_login_perms = Link.where(tail_uuid: user.email,
+                                   head_kind: 'arvados#user',
+                                   link_class: 'permission',
+                                   name: 'can_login')
+
+    if !oid_login_perms.any?
+      # create openid login permission
+      oid_login_perm = Link.create(link_class: 'permission',
+                                   name: 'can_login',
+                                   tail_kind: 'email',
+                                   tail_uuid: user.email,
+                                   head_kind: 'arvados#user',
+                                   head_uuid: user.uuid,
+                                   properties: login_perm_props
+                                  )
+      logger.info { "openid login permission: " + oid_login_perm[:uuid] }
+    else
+      oid_login_perm = oid_login_perms.first
+    end
+
+    return [oid_login_perm] + user.setup_repo_vm_links(repo_name, vm_uuid)
+  end 
+
+  # create links
+  def setup_repo_vm_links(repo_name, vm_uuid)
+    repo_perm = create_user_repo_link repo_name
+    vm_login_perm = create_vm_login_permission_link vm_uuid, repo_name
+    group_perm = create_user_group_link
+
+    return [repo_perm, vm_login_perm, group_perm, self].compact
+  end 
+
+  # delete user signatures, login, repo, and vm perms, and mark as inactive
+  def unsetup
+    # delete oid_login_perms for this user
+    oid_login_perms = Link.where(tail_uuid: self.email,
+                                 head_kind: 'arvados#user',
+                                 link_class: 'permission',
+                                 name: 'can_login')
+    oid_login_perms.each do |perm|
+      Link.delete perm
+    end
+
+    # delete repo_perms for this user
+    repo_perms = Link.where(tail_uuid: self.uuid,
+                            head_kind: 'arvados#repository',
+                            link_class: 'permission',
+                            name: 'can_write')
+    repo_perms.each do |perm|
+      Link.delete perm
+    end
+
+    # delete vm_login_perms for this user
+    vm_login_perms = Link.where(tail_uuid: self.uuid,
+                                head_kind: 'arvados#virtualMachine',
+                                link_class: 'permission',
+                                name: 'can_login')
+    vm_login_perms.each do |perm|
+      Link.delete perm
+    end
+
+    # delete any signatures by this user
+    signed_uuids = Link.where(link_class: 'signature',
+                              tail_kind: 'arvados#user',
+                              tail_uuid: self.uuid)
+    signed_uuids.each do |sign|
+      Link.delete sign
+    end
+
+    # mark the user as inactive
+    self.is_active = false
+    self.save!
+  end 
+
   protected
 
   def permission_to_update
@@ -177,4 +255,120 @@ class User < ArvadosModel
     upstream_path.delete start
     merged
   end
+
+  def create_user_repo_link(repo_name)
+    # repo_name is optional
+    if not repo_name
+      logger.warn ("Repository name not given for #{self.uuid}.")
+      return
+    end
+
+    # Check for an existing repository with the same name we're about to use.
+    repo = Repository.where(name: repo_name).first
+
+    if repo
+      logger.warn "Repository exists for #{repo_name}: #{repo[:uuid]}."
+
+      # Look for existing repository access for this repo
+      repo_perms = Link.where(tail_uuid: self.uuid,
+                              head_kind: 'arvados#repository',
+                              head_uuid: repo[:uuid],
+                              link_class: 'permission',
+                              name: 'can_write')
+      if repo_perms.any?
+        logger.warn "User already has repository access " + 
+            repo_perms.collect { |p| p[:uuid] }.inspect
+        return repo_perms.first
+      end
+    end
+
+    # create repo, if does not already exist
+    repo ||= Repository.create(name: repo_name)
+    logger.info { "repo uuid: " + repo[:uuid] }
+
+    repo_perm = Link.create(tail_kind: 'arvados#user',
+                            tail_uuid: self.uuid,
+                            head_kind: 'arvados#repository',
+                            head_uuid: repo[:uuid],
+                            link_class: 'permission',
+                            name: 'can_write')
+    logger.info { "repo permission: " + repo_perm[:uuid] }
+    return repo_perm
+  end
+
+  # create login permission for the given vm_uuid, if it does not already exist
+  def create_vm_login_permission_link(vm_uuid, repo_name)
+    begin
+              
+      # vm uuid is optional
+      if vm_uuid 
+        vm = VirtualMachine.where(uuid: vm_uuid).first
+
+        if not vm
+          logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
+          raise "No vm found for #{vm_uuid}"
+        end
+      else
+        return 
+      end
+
+      logger.info { "vm uuid: " + vm[:uuid] }
+
+      login_perms = Link.where(tail_uuid: self.uuid,
+                              head_uuid: vm[:uuid],
+                              head_kind: 'arvados#virtualMachine',
+                              link_class: 'permission',
+                              name: 'can_login')
+      if !login_perms.any?
+        login_perm = Link.create(tail_kind: 'arvados#user',
+                                 tail_uuid: self.uuid,
+                                 head_kind: 'arvados#virtualMachine',
+                                 head_uuid: vm[:uuid],
+                                 link_class: 'permission',
+                                 name: 'can_login',
+                                 properties: {username: repo_name})
+        logger.info { "login permission: " + login_perm[:uuid] }
+      else
+        login_perm = login_perms.first
+      end
+
+      return login_perm
+    end
+  end
+
+  # add the user to the 'All users' group
+  def create_user_group_link
+    # Look up the "All users" group (we expect uuid *-*-fffffffffffffff).
+    group = Group.where(name: 'All users').select do |g|
+      g[:uuid].match /-f+$/
+    end.first
+
+    if not group
+      logger.warn "No 'All users' group with uuid '*-*-fffffffffffffff'."
+      raise "No 'All users' group with uuid '*-*-fffffffffffffff' is found"
+    else
+      logger.info { "\"All users\" group uuid: " + group[:uuid] }
+
+      group_perms = Link.where(tail_uuid: self.uuid,
+                              head_uuid: group[:uuid],
+                              head_kind: 'arvados#group',
+                              link_class: 'permission',
+                              name: 'can_read')
+
+      if !group_perms.any?
+        group_perm = Link.create(tail_kind: 'arvados#user',
+                                 tail_uuid: self.uuid,
+                                 head_kind: 'arvados#group',
+                                 head_uuid: group[:uuid],
+                                 link_class: 'permission',
+                                 name: 'can_read')
+        logger.info { "group permission: " + group_perm[:uuid] }
+      else 
+        group_perm = group_perms.first
+      end
+
+      return group_perm
+    end
+  end
+
 end
index e46ff5dd187c2777060d1bd9dba16132e875cfa9..298b001c547ae7cba2df994a73982040b022a311 100644 (file)
@@ -45,7 +45,17 @@ common:
   secret_token: ~
   uuid_prefix: <%= Digest::MD5.hexdigest(`hostname`).to_i(16).to_s(36)[0..4] %>
 
-  git_repositories_dir: /var/cache/git
+  # Git repositories must be readable by api server, or you won't be
+  # able to submit crunch jobs. To pass the test suites, put a clone
+  # of the arvados tree in {git_repositories_dir}/arvados.git or
+  # {git_repositories_dir}/arvados/.git
+  git_repositories_dir: /var/lib/arvados/git
+
+  # This is a (bare) repository that stores commits used in jobs.  When a job
+  # runs, the source commits are first fetched into this repository, then this
+  # repository is used to deploy to compute nodes.  This should NOT be a
+  # subdirectory of {git_repositiories_dir}.
+  git_internal_dir: /var/lib/arvados/internal.git
 
   # :none or :slurm_immediate
   crunch_job_wrapper: :none
index 488c4bd3e6cff843ecac18f3a4142ca99d2182cf..9162fc444585d9fa1e59ade9f0df7e144f81cbda 100644 (file)
@@ -37,10 +37,5 @@ test:
   secret_token: <%= rand(2**512).to_s(36) %>
 
 common:
-
-  # Git repositories must be readable by api server, or you won't be
-  # able to submit crunch jobs. To pass the test suites, put a clone
-  # of the arvados tree in {git_repositories_dir}/arvados.git or
-  # {git_repositories_dir}/arvados/.git
-  #
   #git_repositories_dir: /var/cache/git
+  #git_internal_dir: /var/cache/arvados/internal.git
index 402d79f574c5e1dcef3523fd93b7dc528f73be26..4ccec85307319023b1649acdd6a05a217d473afa 100644 (file)
@@ -4,3 +4,9 @@ require 'josh_id'
 
 # Initialize the rails application
 Server::Application.initialize!
+begin
+  Rails.cache.clear
+rescue Errno::ENOENT => e
+  # Cache directory does not exist? Then cache is clear, proceed.
+  Rails.logger.warn "In Rails.cache.clear, ignoring #{e.inspect}"
+end
index dffae7fad1725768af1e00b1fbb37ac60da9f650..4bc5de8c8462f1ffca9e75663652866e5c77fdfe 100644 (file)
@@ -79,7 +79,6 @@ Server::Application.routes.draw do
 
   namespace :arvados do
     namespace :v1 do
-      match '/schema' => 'schema#show'
       match '/nodes/:uuid/ping' => 'nodes#ping', :as => :ping_node
       match '/keep_disks/ping' => 'keep_disks#ping', :as => :ping_keep_disk
       match '/links/from/:tail_uuid' => 'links#index', :as => :arvados_v1_links_from
@@ -90,6 +89,8 @@ Server::Application.routes.draw do
       post '/jobs/:uuid/cancel' => 'jobs#cancel'
       match '/users/:uuid/event_stream' => 'users#event_stream'
       post '/users/:uuid/activate' => 'users#activate'
+      post '/users/setup' => 'users#setup'
+      post '/users/:uuid/unsetup' => 'users#unsetup'
       match '/virtual_machines/get_all_logins' => 'virtual_machines#get_all_logins'
       match '/virtual_machines/:uuid/logins' => 'virtual_machines#logins'
       post '/api_client_authorizations/create_system_auth' => 'api_client_authorizations#create_system_auth'
@@ -129,7 +130,7 @@ Server::Application.routes.draw do
   match '/login', :to => 'user_sessions#login'
   match '/logout', :to => 'user_sessions#logout'
 
-  match '/discovery/v1/apis/arvados/v1/rest', :to => 'arvados/v1/schema#discovery_rest_description'
+  match '/discovery/v1/apis/arvados/v1/rest', :to => 'arvados/v1/schema#index'
 
   match '/static/login_failure', :to => 'static#login_failure', :as => :login_failure
 
diff --git a/services/api/db/migrate/20140317135600_add_nondeterministic_column_to_job.rb b/services/api/db/migrate/20140317135600_add_nondeterministic_column_to_job.rb
new file mode 100644 (file)
index 0000000..574001b
--- /dev/null
@@ -0,0 +1,9 @@
+class AddNondeterministicColumnToJob < ActiveRecord::Migration
+  def up
+    add_column :jobs, :nondeterministic, :boolean
+  end
+
+  def down
+    remove_column :jobs, :nondeterministic
+  end
+end
diff --git a/services/api/db/migrate/20140319160547_separate_repository_from_script_version.rb b/services/api/db/migrate/20140319160547_separate_repository_from_script_version.rb
new file mode 100644 (file)
index 0000000..d87b037
--- /dev/null
@@ -0,0 +1,31 @@
+class SeparateRepositoryFromScriptVersion < ActiveRecord::Migration
+  include CurrentApiClient
+
+  def fixup pt
+    c = pt.components
+    c.each do |k, v|
+      commit_ish = v["script_version"]
+      if commit_ish.andand.index(':')
+        want_repo, commit_ish = commit_ish.split(':',2)
+        v[:repository] = want_repo
+        v[:script_version] = commit_ish
+      end
+    end
+    pt.save!
+  end
+
+  def up
+    act_as_system_user do
+      PipelineTemplate.all.each do |pt|
+        fixup pt
+      end
+      PipelineInstance.all.each do |pt|
+        fixup pt
+      end
+    end
+  end
+
+  def down
+    raise ActiveRecord::IrreversibleMigration
+  end
+end
diff --git a/services/api/db/migrate/20140321191343_add_repository_column_to_job.rb b/services/api/db/migrate/20140321191343_add_repository_column_to_job.rb
new file mode 100644 (file)
index 0000000..e1ebb2e
--- /dev/null
@@ -0,0 +1,9 @@
+class AddRepositoryColumnToJob < ActiveRecord::Migration
+  def up
+    add_column :jobs, :repository, :string
+  end
+
+  def down
+    remove_column :jobs, :repository
+  end
+end
index 5c2fe2925de476ee77e8efe26004f736d5eab47a..8ab6f5faf7a73ee5ab37276070771f439e856953 100644 (file)
@@ -70,7 +70,7 @@ ActiveRecord::Schema.define(:version => 20140324024606) do
   create_table "collections", :force => true do |t|
     t.string   "locator"
     t.string   "owner_uuid"
-    t.datetime "created_at",                          :null => false
+    t.datetime "created_at"
     t.string   "modified_by_client_uuid"
     t.string   "modified_by_user_uuid"
     t.datetime "modified_at"
@@ -80,7 +80,7 @@ ActiveRecord::Schema.define(:version => 20140324024606) do
     t.string   "redundancy_confirmed_by_client_uuid"
     t.datetime "redundancy_confirmed_at"
     t.integer  "redundancy_confirmed_as"
-    t.datetime "updated_at",                          :null => false
+    t.datetime "updated_at"
     t.string   "uuid"
     t.text     "manifest_text"
   end
@@ -104,8 +104,8 @@ ActiveRecord::Schema.define(:version => 20140324024606) do
     t.string   "repository_name"
     t.string   "sha1"
     t.string   "message"
-    t.datetime "created_at",      :null => false
-    t.datetime "updated_at",      :null => false
+    t.datetime "created_at"
+    t.datetime "updated_at"
   end
 
   add_index "commits", ["repository_name", "sha1"], :name => "index_commits_on_repository_name_and_sha1", :unique => true
@@ -133,8 +133,8 @@ ActiveRecord::Schema.define(:version => 20140324024606) do
     t.string   "modified_by_user_uuid"
     t.datetime "modified_at"
     t.text     "properties"
-    t.datetime "created_at",              :null => false
-    t.datetime "updated_at",              :null => false
+    t.datetime "created_at"
+    t.datetime "updated_at"
   end
 
   add_index "humans", ["uuid"], :name => "index_humans_on_uuid", :unique => true
@@ -189,6 +189,8 @@ ActiveRecord::Schema.define(:version => 20140324024606) do
     t.string   "log"
     t.text     "tasks_summary"
     t.text     "runtime_constraints"
+    t.boolean  "nondeterministic"
+    t.string   "repository"
     t.boolean  "output_is_persistent",     :default => false, :null => false
   end
 
@@ -233,7 +235,7 @@ ActiveRecord::Schema.define(:version => 20140324024606) do
   create_table "links", :force => true do |t|
     t.string   "uuid"
     t.string   "owner_uuid"
-    t.datetime "created_at",              :null => false
+    t.datetime "created_at"
     t.string   "modified_by_client_uuid"
     t.string   "modified_by_user_uuid"
     t.datetime "modified_at"
@@ -243,7 +245,7 @@ ActiveRecord::Schema.define(:version => 20140324024606) do
     t.string   "name"
     t.string   "head_uuid"
     t.text     "properties"
-    t.datetime "updated_at",              :null => false
+    t.datetime "updated_at"
     t.string   "head_kind"
   end
 
@@ -306,7 +308,7 @@ ActiveRecord::Schema.define(:version => 20140324024606) do
   create_table "pipeline_instances", :force => true do |t|
     t.string   "uuid"
     t.string   "owner_uuid"
-    t.datetime "created_at",                                 :null => false
+    t.datetime "created_at"
     t.string   "modified_by_client_uuid"
     t.string   "modified_by_user_uuid"
     t.datetime "modified_at"
@@ -315,7 +317,7 @@ ActiveRecord::Schema.define(:version => 20140324024606) do
     t.text     "components"
     t.boolean  "success"
     t.boolean  "active",                  :default => false
-    t.datetime "updated_at",                                 :null => false
+    t.datetime "updated_at"
     t.text     "properties"
   end
 
index 6df9a19d299a5a8a440a99866be774e0bbad9d4c..d9db69f6502a87ca22c5565c149806b6e5da6198 100755 (executable)
@@ -150,27 +150,32 @@ class Dispatcher
         raise "No CRUNCH_JOB_BIN env var, and crunch-job not in path."
       end
 
+      require 'shellwords'
+
+      arvados_internal = Rails.configuration.git_internal_dir
+      if not File.exists? arvados_internal
+        $stderr.puts `mkdir -p #{arvados_internal.shellescape} && cd #{arvados_internal.shellescape} && git init --bare`
+      end
+
+      src_repo = File.join(Rails.configuration.git_repositories_dir, job.repository + '.git')
+      src_repo = File.join(Rails.configuration.git_repositories_dir, job.repository, '.git') unless File.exists? src_repo
+
+      unless src_repo
+        $stderr.puts "dispatch: #{File.join Rails.configuration.git_repositories_dir, job.repository} doesn't exist"
+        sleep 1
+        untake(job)
+        next
+      end
+
+      $stderr.puts `cd #{arvados_internal.shellescape} && git fetch --no-tags #{src_repo.shellescape} && git tag #{job.uuid.shellescape} #{job.script_version.shellescape}`
+
       cmd_args << crunch_job_bin
       cmd_args << '--job-api-token'
       cmd_args << job_auth.api_token
       cmd_args << '--job'
       cmd_args << job.uuid
-
-      commit = Commit.where(sha1: job.script_version).first
-      if commit
-        cmd_args << '--git-dir'
-        if File.exists?(File.
-                        join(Rails.configuration.git_repositories_dir,
-                             commit.repository_name + '.git'))
-          cmd_args << File.
-            join(Rails.configuration.git_repositories_dir,
-                 commit.repository_name + '.git')
-        else
-          cmd_args << File.
-            join(Rails.configuration.git_repositories_dir,
-                 commit.repository_name, '.git')
-        end
-      end
+      cmd_args << '--git-dir'
+      cmd_args << arvados_internal
 
       $stderr.puts "dispatch: #{cmd_args.join ' '}"
 
@@ -324,19 +329,25 @@ class Dispatcher
   end
 
   def update_pipelines
+    expire_tokens = @pipe_auth_tokens.dup
     @todo_pipelines.each do |p|
-      pipe_auth = ApiClientAuthorization.
-        new(user: User.where('uuid=?', p.modified_by_user_uuid).first,
-            api_client_id: 0)
-      pipe_auth.save
-
+      pipe_auth = (@pipe_auth_tokens[p.uuid] ||= ApiClientAuthorization.
+                   create(user: User.where('uuid=?', p.modified_by_user_uuid).first,
+                          api_client_id: 0))
       puts `export ARVADOS_API_TOKEN=#{pipe_auth.api_token} && arv-run-pipeline-instance --run-here --no-wait --instance #{p.uuid}`
+      expire_tokens.delete p.uuid
+    end
+
+    expire_tokens.each do |k, v|
+      v.update_attributes expires_at: Time.now
+      @pipe_auth_tokens.delete k
     end
   end
 
   def run
     act_as_system_user
     @running ||= {}
+    @pipe_auth_tokens ||= { }
     $stderr.puts "dispatch: ready"
     while !$signal[:term] or @running.size > 0
       read_pipes
@@ -358,7 +369,7 @@ class Dispatcher
         unless @todo.empty? or did_recently(:start_jobs, 1.0) or $signal[:term]
           start_jobs
         end
-        unless @todo_pipelines.empty? or did_recently(:update_pipelines, 5.0)
+        unless (@todo_pipelines.empty? and @pipe_auth_tokens.empty?) or did_recently(:update_pipelines, 5.0)
           update_pipelines
         end
       end
index 2167b0431882ef9eeef5acd733dc3b03312c6f34..04550e826c8422f1fab3c1ba56b634e1a0f18fbc 100755 (executable)
@@ -21,11 +21,11 @@ module Rails
                 :config => File.expand_path("config.ru"),
                 :SSLEnable => true,
                 :SSLVerifyClient => OpenSSL::SSL::VERIFY_NONE,
-                :SSLCertName => [["CN", WEBrick::Utils::getservername]]
+                :SSLCertName => [["CN", "#{WEBrick::Utils::getservername} #{Time.now().to_s}"]]
             })
         end
     end
-end 
+end
 ######### /SSL
 
 
diff --git a/services/api/script/setup-new-user.rb b/services/api/script/setup-new-user.rb
new file mode 100755 (executable)
index 0000000..19f5aeb
--- /dev/null
@@ -0,0 +1,66 @@
+#!/usr/bin/env ruby
+
+abort 'Error: Ruby >= 1.9.3 required.' if RUBY_VERSION < '1.9.3'
+
+require 'logger'
+require 'trollop'
+
+log = Logger.new STDERR
+log.progname = $0.split('/').last
+
+opts = Trollop::options do
+  banner ''
+  banner "Usage: #{log.progname} " +
+    "{user_uuid_or_email} {user_and_repo_name} {vm_uuid}"
+  banner ''
+  opt :debug, <<-eos
+Show debug messages.
+  eos
+  opt :openid_prefix, <<-eos, default: 'https://www.google.com/accounts/o8/id'
+If creating a new user record, require authentication from an OpenID \
+with this OpenID prefix *and* a matching email address in order to \
+claim the account.
+  eos
+end
+
+log.level = (ENV['DEBUG'] || opts.debug) ? Logger::DEBUG : Logger::WARN
+    
+if ARGV.count != 3
+  Trollop::die "required arguments are missing"
+end
+
+user_arg, user_repo_name, vm_uuid = ARGV
+
+require 'arvados'
+arv = Arvados.new(api_version: 'v1')
+
+# Look up the given user by uuid or, failing that, email address.
+begin
+  found_user = arv.user.get(uuid: user_arg)
+rescue Arvados::TransactionFailedError
+  found = arv.user.list(where: {email: user_arg})[:items]
+    
+  if found.count == 0 
+    if !user_arg.match(/\w\@\w+\.\w+/)
+      abort "About to create new user, but #{user_arg.inspect} " +
+               "does not look like an email address. Stop."
+    end
+  elsif found.count != 1
+    abort "Found #{found.count} users with email. Stop."
+  else
+    found_user = found.first
+  end
+end
+
+# Invoke user setup method
+if (found_user)
+  user = arv.user.setup uuid: found_user[:uuid], repo_name: user_repo_name,
+        vm_uuid: vm_uuid, openid_prefix: opts.openid_prefix
+else
+  user = arv.user.setup user: {email: user_arg}, repo_name: user_repo_name,
+        vm_uuid: vm_uuid, openid_prefix: opts.openid_prefix
+end
+
+log.info {"user uuid: " + user[:uuid]}
+
+puts user.inspect
index 85b02aee790d2e0a00e92833201b0a592c5a1f08..ce05d18f0dc86288343e6f61eb12fdf8e0d5832b 100644 (file)
@@ -1,5 +1,5 @@
 user_agreement:
-  uuid: b519d9cb706a29fc7ea24dbea2f05851
+  uuid: b519d9cb706a29fc7ea24dbea2f05851+249025
   owner_uuid: qr1hi-tpzed-tpj2ff66551eyym
   created_at: 2013-12-26T19:22:54Z
   modified_by_client_uuid: zzzzz-ozdt8-brczlopd8u8d0jr
index 9780067b352adea69270e51778f3522f0d203cd8..edc64bdf48d4991552772e351e11c5c5b74832bc 100644 (file)
@@ -110,3 +110,24 @@ barbaz:
     running: 0
     done: 1
   runtime_constraints: {}
+
+previous_job_run:
+  uuid: zzzzz-8i9sb-cjs4pklxxjykqqq
+  owner_uuid: zzzzz-tpzed-xurymjxw79nv3jz
+  script: hash
+  script_version: 4fe459abe02d9b365932b8f5dc419439ab4e2577
+  script_parameters:
+    input: fa7aeb5140e2848d39b416daeef4ffc5+45
+    an_integer: "1"
+  success: true
+
+nondeterminisic_job_run:
+  uuid: zzzzz-8i9sb-cjs4pklxxjykyyy
+  owner_uuid: zzzzz-tpzed-xurymjxw79nv3jz
+  script: hash2
+  script_version: 4fe459abe02d9b365932b8f5dc419439ab4e2577
+  script_parameters:
+    input: fa7aeb5140e2848d39b416daeef4ffc5+45
+    an_integer: "1"
+  success: true
+  nondeterministic: true
\ No newline at end of file
index 6cb8c633d88bc25bc6773a3cc0f021f2539fe9a8..4e10b5612c70e11a3b760d1b2ce0888ca3a10b73 100644 (file)
@@ -11,7 +11,7 @@ user_agreement_required:
   link_class: signature
   name: require
   head_kind: arvados#collection
-  head_uuid: b519d9cb706a29fc7ea24dbea2f05851
+  head_uuid: b519d9cb706a29fc7ea24dbea2f05851+249025
   properties: {}
 
 user_agreement_readable:
@@ -27,7 +27,7 @@ user_agreement_readable:
   link_class: permission
   name: can_read
   head_kind: arvados#collection
-  head_uuid: b519d9cb706a29fc7ea24dbea2f05851
+  head_uuid: b519d9cb706a29fc7ea24dbea2f05851+249025
   properties: {}
 
 active_user_member_of_all_users_group:
@@ -75,7 +75,7 @@ user_agreement_signed_by_active:
   link_class: signature
   name: click
   head_kind: arvados#collection
-  head_uuid: b519d9cb706a29fc7ea24dbea2f05851
+  head_uuid: b519d9cb706a29fc7ea24dbea2f05851+249025
   properties: {}
 
 user_agreement_signed_by_inactive:
@@ -91,7 +91,7 @@ user_agreement_signed_by_inactive:
   link_class: signature
   name: click
   head_kind: arvados#collection
-  head_uuid: b519d9cb706a29fc7ea24dbea2f05851
+  head_uuid: b519d9cb706a29fc7ea24dbea2f05851+249025
   properties: {}
 
 spectator_user_member_of_all_users_group:
@@ -222,3 +222,18 @@ barbaz_job_readable_by_spectator:
   head_uuid: zzzzz-8i9sb-cjs4pklxxjykyuq
   properties: {}
 
+foo_repository_readable_by_spectator:
+  uuid: zzzzz-o0j2j-cpy7p41hpk5xxx
+  owner_uuid: zzzzz-tpzed-000000000000000
+  created_at: 2014-01-24 20:42:26 -0800
+  modified_by_client_uuid: zzzzz-ozdt8-brczlopd8u8d0jr
+  modified_by_user_uuid: zzzzz-tpzed-000000000000000
+  modified_at: 2014-01-24 20:42:26 -0800
+  updated_at: 2014-01-24 20:42:26 -0800
+  tail_kind: arvados#user
+  tail_uuid: zzzzz-tpzed-l1s2piq4t4mps8r
+  link_class: permission
+  name: can_read
+  head_kind: arvados#repository
+  head_uuid: zzzzz-2x53u-382brsig8rp3666
+  properties: {}
diff --git a/services/api/test/fixtures/repositories.yml b/services/api/test/fixtures/repositories.yml
new file mode 100644 (file)
index 0000000..ec3755d
--- /dev/null
@@ -0,0 +1,4 @@
+foo:
+  uuid: zzzzz-2x53u-382brsig8rp3666
+  owner_uuid: zzzzz-tpzed-xurymjxw79nv3jz
+  name: foo
diff --git a/services/api/test/functional/arvados/v1/commits_controller_test.rb b/services/api/test/functional/arvados/v1/commits_controller_test.rb
new file mode 100644 (file)
index 0000000..955b1f1
--- /dev/null
@@ -0,0 +1,86 @@
+require 'test_helper'
+load 'test/functional/arvados/v1/git_setup.rb'
+
+class Arvados::V1::CommitsControllerTest < ActionController::TestCase
+  fixtures :repositories, :users
+
+  # See git_setup.rb for the commit log for test.git.tar
+  include GitSetup
+
+  test "test_find_commit_range" do
+    authorize_with :active
+
+  # single
+    a = Commit.find_commit_range(users(:active), nil, nil, '31ce37fe365b3dc204300a3e4c396ad333ed0556', nil)
+    assert_equal ['31ce37fe365b3dc204300a3e4c396ad333ed0556'], a
+
+  #test "test_branch1" do
+    a = Commit.find_commit_range(users(:active), nil, nil, 'master', nil)
+    assert_equal ['077ba2ad3ea24a929091a9e6ce545c93199b8e57'], a
+
+  #test "test_branch2" do
+    a = Commit.find_commit_range(users(:active), 'foo', nil, 'b1', nil)
+    assert_equal ['1de84a854e2b440dc53bf42f8548afa4c17da332'], a
+
+  #test "test_branch3" do
+    a = Commit.find_commit_range(users(:active), 'foo', nil, 'HEAD', nil)
+    assert_equal ['1de84a854e2b440dc53bf42f8548afa4c17da332'], a
+
+  #test "test_single_revision_repo" do
+    a = Commit.find_commit_range(users(:active), "foo", nil, '31ce37fe365b3dc204300a3e4c396ad333ed0556', nil)
+    assert_equal ['31ce37fe365b3dc204300a3e4c396ad333ed0556'], a
+    a = Commit.find_commit_range(users(:active), "bar", nil, '31ce37fe365b3dc204300a3e4c396ad333ed0556', nil)
+    assert_equal nil, a
+
+  #test "test_multi_revision" do
+    a = Commit.find_commit_range(users(:active), nil, '31ce37fe365b3dc204300a3e4c396ad333ed0556', '077ba2ad3ea24a929091a9e6ce545c93199b8e57', nil)
+    assert_equal ['077ba2ad3ea24a929091a9e6ce545c93199b8e57', '4fe459abe02d9b365932b8f5dc419439ab4e2577', '31ce37fe365b3dc204300a3e4c396ad333ed0556'], a
+
+  #test "test_tag" do
+    a = Commit.find_commit_range(users(:active), nil, 'tag1', 'master', nil)
+    assert_equal ['077ba2ad3ea24a929091a9e6ce545c93199b8e57', '4fe459abe02d9b365932b8f5dc419439ab4e2577'], a
+
+  #test "test_multi_revision_exclude" do
+    a = Commit.find_commit_range(users(:active), nil, '31ce37fe365b3dc204300a3e4c396ad333ed0556', '077ba2ad3ea24a929091a9e6ce545c93199b8e57', ['4fe459abe02d9b365932b8f5dc419439ab4e2577'])
+    assert_equal ['077ba2ad3ea24a929091a9e6ce545c93199b8e57', '31ce37fe365b3dc204300a3e4c396ad333ed0556'], a
+
+  #test "test_multi_revision_tagged_exclude" do
+    a = Commit.find_commit_range(users(:active), nil, '31ce37fe365b3dc204300a3e4c396ad333ed0556', '077ba2ad3ea24a929091a9e6ce545c93199b8e57', ['tag1'])
+    assert_equal ['077ba2ad3ea24a929091a9e6ce545c93199b8e57', '31ce37fe365b3dc204300a3e4c396ad333ed0556'], a
+
+    Dir.mktmpdir do |touchdir|
+      # invalid input to maximum
+      a = Commit.find_commit_range(users(:active), nil, nil, "31ce37fe365b3dc204300a3e4c396ad333ed0556 ; touch #{touchdir}/uh_oh", nil)
+      assert !File.exists?("#{touchdir}/uh_oh"), "#{touchdir}/uh_oh should not exist, 'maximum' parameter of find_commit_range is exploitable"
+      assert_equal nil, a
+
+      # invalid input to maximum
+      a = Commit.find_commit_range(users(:active), nil, nil, "$(uname>#{touchdir}/uh_oh)", nil)
+      assert !File.exists?("#{touchdir}/uh_oh"), "#{touchdir}/uh_oh should not exist, 'maximum' parameter of find_commit_range is exploitable"
+      assert_equal nil, a
+
+      # invalid input to minimum
+      a = Commit.find_commit_range(users(:active), nil, "31ce37fe365b3dc204300a3e4c396ad333ed0556 ; touch #{touchdir}/uh_oh", "31ce37fe365b3dc204300a3e4c396ad333ed0556", nil)
+      assert !File.exists?("#{touchdir}/uh_oh"), "#{touchdir}/uh_oh should not exist, 'minimum' parameter of find_commit_range is exploitable"
+      assert_equal nil, a
+
+      # invalid input to minimum
+      a = Commit.find_commit_range(users(:active), nil, "$(uname>#{touchdir}/uh_oh)", "31ce37fe365b3dc204300a3e4c396ad333ed0556", nil)
+      assert !File.exists?("#{touchdir}/uh_oh"), "#{touchdir}/uh_oh should not exist, 'minimum' parameter of find_commit_range is exploitable"
+      assert_equal nil, a
+
+      # invalid input to 'excludes'
+      a = Commit.find_commit_range(users(:active), nil, "31ce37fe365b3dc204300a3e4c396ad333ed0556", "077ba2ad3ea24a929091a9e6ce545c93199b8e57", ["4fe459abe02d9b365932b8f5dc419439ab4e2577 ; touch #{touchdir}/uh_oh"])
+      assert !File.exists?("#{touchdir}/uh_oh"), "#{touchdir}/uh_oh should not exist, 'excludes' parameter of find_commit_range is exploitable"
+      assert_equal nil, a
+
+      # invalid input to 'excludes'
+      a = Commit.find_commit_range(users(:active), nil, "31ce37fe365b3dc204300a3e4c396ad333ed0556", "077ba2ad3ea24a929091a9e6ce545c93199b8e57", ["$(uname>#{touchdir}/uh_oh)"])
+      assert !File.exists?("#{touchdir}/uh_oh"), "#{touchdir}/uh_oh should not exist, 'excludes' parameter of find_commit_range is exploitable"
+      assert_equal nil, a
+
+    end
+
+  end
+
+end
diff --git a/services/api/test/functional/arvados/v1/git_setup.rb b/services/api/test/functional/arvados/v1/git_setup.rb
new file mode 100644 (file)
index 0000000..46f5f70
--- /dev/null
@@ -0,0 +1,27 @@
+require 'fileutils'
+require 'tmpdir'
+
+# Commit log for test.git.tar
+# master is the main branch
+# b1 is a branch off of master
+# tag1 is a tag
+#
+# 1de84a8 * b1
+# 077ba2a * master
+# 4fe459a * tag1
+# 31ce37f * foo
+
+module GitSetup
+  def setup
+    @tmpdir = Dir.mktmpdir()
+    #puts "setup #{@tmpdir}"
+    `cp test/test.git.tar #{@tmpdir} && cd #{@tmpdir} && tar xf test.git.tar`
+    Rails.configuration.git_repositories_dir = "#{@tmpdir}/test"
+    Commit.refresh_repositories
+  end
+
+  def teardown
+    #puts "teardown #{@tmpdir}"
+    FileUtils.remove_entry @tmpdir, true
+  end
+end
diff --git a/services/api/test/functional/arvados/v1/job_reuse_controller_test.rb b/services/api/test/functional/arvados/v1/job_reuse_controller_test.rb
new file mode 100644 (file)
index 0000000..03e577f
--- /dev/null
@@ -0,0 +1,167 @@
+require 'test_helper'
+load 'test/functional/arvados/v1/git_setup.rb'
+
+class Arvados::V1::JobReuseControllerTest < ActionController::TestCase
+  fixtures :repositories, :users, :jobs, :links
+
+  # See git_setup.rb for the commit log for test.git.tar
+  include GitSetup
+
+  test "test_reuse_job" do
+    @controller = Arvados::V1::JobsController.new
+    authorize_with :active
+    post :create, job: {
+      script: "hash",
+      script_version: "4fe459abe02d9b365932b8f5dc419439ab4e2577",
+      repository: "foo",
+      script_parameters: {
+        input: 'fa7aeb5140e2848d39b416daeef4ffc5+45',
+        an_integer: '1'
+      }
+    }
+    assert_response :success
+    assert_not_nil assigns(:object)
+    new_job = JSON.parse(@response.body)
+    assert_equal 'zzzzz-8i9sb-cjs4pklxxjykqqq', new_job['uuid']
+    assert_equal '4fe459abe02d9b365932b8f5dc419439ab4e2577', new_job['script_version']
+  end
+
+  test "test_reuse_job_range" do
+    @controller = Arvados::V1::JobsController.new
+    authorize_with :active
+    post :create, job: {
+      script: "hash",
+      minimum_script_version: "tag1",
+      script_version: "master",
+      repository: "foo",
+      script_parameters: {
+        input: 'fa7aeb5140e2848d39b416daeef4ffc5+45',
+        an_integer: '1'
+      }
+    }
+    assert_response :success
+    assert_not_nil assigns(:object)
+    new_job = JSON.parse(@response.body)
+    assert_equal 'zzzzz-8i9sb-cjs4pklxxjykqqq', new_job['uuid']
+    assert_equal '4fe459abe02d9b365932b8f5dc419439ab4e2577', new_job['script_version']
+  end
+
+  test "test_cannot_reuse_job_different_input" do
+    @controller = Arvados::V1::JobsController.new
+    authorize_with :active
+    post :create, job: {
+      script: "hash",
+      script_version: "4fe459abe02d9b365932b8f5dc419439ab4e2577",
+      repository: "foo",
+      script_parameters: {
+        input: 'fa7aeb5140e2848d39b416daeef4ffc5+45',
+        an_integer: '2'
+      }
+    }
+    assert_response :success
+    assert_not_nil assigns(:object)
+    new_job = JSON.parse(@response.body)
+    assert_not_equal 'zzzzz-8i9sb-cjs4pklxxjykqqq', new_job['uuid']
+    assert_equal '4fe459abe02d9b365932b8f5dc419439ab4e2577', new_job['script_version']
+  end
+
+  test "test_cannot_reuse_job_different_version" do
+    @controller = Arvados::V1::JobsController.new
+    authorize_with :active
+    post :create, job: {
+      script: "hash",
+      script_version: "master",
+      repository: "foo",
+      script_parameters: {
+        input: 'fa7aeb5140e2848d39b416daeef4ffc5+45',
+        an_integer: '2'
+      }
+    }
+    assert_response :success
+    assert_not_nil assigns(:object)
+    new_job = JSON.parse(@response.body)
+    assert_not_equal 'zzzzz-8i9sb-cjs4pklxxjykqqq', new_job['uuid']
+    assert_equal '077ba2ad3ea24a929091a9e6ce545c93199b8e57', new_job['script_version']
+  end
+
+  test "test_cannot_reuse_job_submitted_nondeterministic" do
+    @controller = Arvados::V1::JobsController.new
+    authorize_with :active
+    post :create, job: {
+      script: "hash",
+      script_version: "4fe459abe02d9b365932b8f5dc419439ab4e2577",
+      repository: "foo",
+      script_parameters: {
+        input: 'fa7aeb5140e2848d39b416daeef4ffc5+45',
+        an_integer: '1'
+      },
+      nondeterministic: true
+    }
+    assert_response :success
+    assert_not_nil assigns(:object)
+    new_job = JSON.parse(@response.body)
+    assert_not_equal 'zzzzz-8i9sb-cjs4pklxxjykqqq', new_job['uuid']
+    assert_equal '4fe459abe02d9b365932b8f5dc419439ab4e2577', new_job['script_version']
+  end
+
+  test "test_cannot_reuse_job_past_nondeterministic" do
+    @controller = Arvados::V1::JobsController.new
+    authorize_with :active
+    post :create, job: {
+      script: "hash2",
+      script_version: "4fe459abe02d9b365932b8f5dc419439ab4e2577",
+      repository: "foo",
+      script_parameters: {
+        input: 'fa7aeb5140e2848d39b416daeef4ffc5+45',
+        an_integer: '1'
+      }
+    }
+    assert_response :success
+    assert_not_nil assigns(:object)
+    new_job = JSON.parse(@response.body)
+    assert_not_equal 'zzzzz-8i9sb-cjs4pklxxjykyyy', new_job['uuid']
+    assert_equal '4fe459abe02d9b365932b8f5dc419439ab4e2577', new_job['script_version']
+  end
+
+  test "test_cannot_reuse_job_no_permission" do
+    @controller = Arvados::V1::JobsController.new
+    authorize_with :spectator
+    post :create, job: {
+      script: "hash",
+      script_version: "4fe459abe02d9b365932b8f5dc419439ab4e2577",
+      repository: "foo",
+      script_parameters: {
+        input: 'fa7aeb5140e2848d39b416daeef4ffc5+45',
+        an_integer: '1'
+      }
+    }
+    assert_response :success
+    assert_not_nil assigns(:object)
+    new_job = JSON.parse(@response.body)
+    assert_not_equal 'zzzzz-8i9sb-cjs4pklxxjykqqq', new_job['uuid']
+    assert_equal '4fe459abe02d9b365932b8f5dc419439ab4e2577', new_job['script_version']
+  end
+
+  test "test_cannot_reuse_job_excluded" do
+    @controller = Arvados::V1::JobsController.new
+    authorize_with :active
+    post :create, job: {
+      script: "hash",
+      minimum_script_version: "31ce37fe365b3dc204300a3e4c396ad333ed0556",
+      script_version: "master",
+      repository: "foo",
+      exclude_script_versions: ["tag1"],
+      script_parameters: {
+        input: 'fa7aeb5140e2848d39b416daeef4ffc5+45',
+        an_integer: '1'
+      }
+    }
+    assert_response :success
+    assert_not_nil assigns(:object)
+    new_job = JSON.parse(@response.body)
+    assert_not_equal 'zzzzz-8i9sb-cjs4pklxxjykqqq', new_job['uuid']
+    assert_equal '077ba2ad3ea24a929091a9e6ce545c93199b8e57', new_job['script_version']
+  end
+
+
+end
index 7920bce068ff4002ad68afe1f1422fe8640d302f..a8a4f85b5f1e0ac70aa1c89a4abffa009308a8fd 100644 (file)
@@ -1,12 +1,16 @@
 require 'test_helper'
+load 'test/functional/arvados/v1/git_setup.rb'
 
 class Arvados::V1::JobsControllerTest < ActionController::TestCase
 
+  include GitSetup
+
   test "submit a job" do
     authorize_with :active
     post :create, job: {
       script: "hash",
       script_version: "master",
+      repository: "foo",
       script_parameters: {}
     }
     assert_response :success
@@ -24,6 +28,7 @@ class Arvados::V1::JobsControllerTest < ActionController::TestCase
       script: "hash",
       script_version: "master",
       script_parameters: {},
+      repository: "foo",
       started_at: Time.now,
       finished_at: Time.now,
       running: false,
@@ -228,4 +233,6 @@ class Arvados::V1::JobsControllerTest < ActionController::TestCase
     }
     assert_response 422
   end
+
+
 end
index 71d49dd9da729ea2644411fafafc8be37aa8b0d0..816834b2071471611d4add36fee89124a8743ca8 100644 (file)
@@ -4,7 +4,7 @@ class Arvados::V1::SchemaControllerTest < ActionController::TestCase
 
   test "should get fresh discovery document" do
     MAX_SCHEMA_AGE = 60
-    get :discovery_rest_description
+    get :index
     assert_response :success
     discovery_doc = JSON.parse(@response.body)
     assert_equal 'discovery#restDescription', discovery_doc['kind']
index 6d129d898fc370d0f8b02d0276f7ecfbcf5fd082..b15b99b2bca7c11c38ffdb92860e5731ffbfa04b 100644 (file)
@@ -2,6 +2,11 @@ require 'test_helper'
 
 class Arvados::V1::UsersControllerTest < ActionController::TestCase
 
+  setup do
+    @all_links_at_start = Link.all
+    @vm_uuid = virtual_machines(:testvm).uuid
+  end
+
   test "activate a user after signing UA" do
     authorize_with :inactive_but_signed_user_agreement
     get :current
@@ -38,4 +43,757 @@ class Arvados::V1::UsersControllerTest < ActionController::TestCase
     assert_equal true, me['is_active']
   end
 
+  test "create new user with user as input" do
+    authorize_with :admin
+    post :create, user: {
+      first_name: "test_first_name",
+      last_name: "test_last_name",
+      email: "foo@example.com"
+    }
+    assert_response :success
+    created = JSON.parse(@response.body)
+    assert_equal 'test_first_name', created['first_name']
+    assert_not_nil created['uuid'], 'expected uuid for the newly created user'
+    assert_not_nil created['email'], 'expected non-nil email'
+    assert_nil created['identity_url'], 'expected no identity_url'
+  end
+
+  test "create user with user, vm and repo as input" do
+    authorize_with :admin
+    repo_name = 'test_repo'
+
+    post :setup, {
+      repo_name: repo_name,
+      openid_prefix: 'https://www.google.com/accounts/o8/id',
+      user: {
+        uuid: "this_is_agreeable",        
+        first_name: "in_create_test_first_name",
+        last_name: "test_last_name",
+        email: "foo@example.com"
+      }
+    }
+    assert_response :success
+    response_items = JSON.parse(@response.body)['items']
+
+    created = find_obj_in_resp response_items, 'User', nil
+    assert_equal 'in_create_test_first_name', created['first_name']
+    assert_not_nil created['uuid'], 'expected non-null uuid for the new user'
+    assert_equal 'this_is_agreeable', created['uuid']
+    assert_not_nil created['email'], 'expected non-nil email'
+    assert_nil created['identity_url'], 'expected no identity_url' 
+
+    # arvados#user, repo link and link add user to 'All users' group
+    verify_num_links @all_links_at_start, 3
+
+    verify_link response_items, 'arvados#user', true, 'permission', 'can_login',
+        created['uuid'], created['email'], 'arvados#user', false, 'User'
+
+    verify_link response_items, 'arvados#repository', true, 'permission', 'can_write',
+        repo_name, created['uuid'], 'arvados#repository', true, 'Repository'
+
+    verify_link response_items, 'arvados#group', true, 'permission', 'can_read',
+        'All users', created['uuid'], 'arvados#group', true, 'Group'
+
+    verify_link response_items, 'arvados#virtualMachine', false, 'permission', 'can_login',
+        nil, created['uuid'], 'arvados#virtualMachine', false, 'VirtualMachine'
+
+    # invoke setup again with the same data
+    post :setup, {
+      repo_name: repo_name,
+      vm_uuid: @vm_uuid,
+      openid_prefix: 'https://www.google.com/accounts/o8/id',
+      user: {
+        uuid: "this_is_agreeable",
+        first_name: "in_create_test_first_name",
+        last_name: "test_last_name",
+        email: "foo@example.com"
+      }
+    }
+
+    response_items = JSON.parse(@response.body)['items']
+
+    created = find_obj_in_resp response_items, 'User', nil
+    assert_equal 'in_create_test_first_name', created['first_name']
+    assert_not_nil created['uuid'], 'expected non-null uuid for the new user'
+    assert_equal 'this_is_agreeable', created['uuid']
+    assert_not_nil created['email'], 'expected non-nil email'
+    assert_nil created['identity_url'], 'expected no identity_url'
+
+    # arvados#user, repo link and link add user to 'All users' group
+    verify_num_links @all_links_at_start, 4
+
+    verify_link response_items, 'arvados#repository', true, 'permission', 'can_write',
+        repo_name, created['uuid'], 'arvados#repository', true, 'Repository'
+
+    verify_link response_items, 'arvados#group', true, 'permission', 'can_read',
+        'All users', created['uuid'], 'arvados#group', true, 'Group'
+
+    verify_link response_items, 'arvados#virtualMachine', true, 'permission', 'can_login',
+        @vm_uuid, created['uuid'], 'arvados#virtualMachine', false, 'VirtualMachine'
+  end
+
+  test "setup user with bogus uuid and expect error" do
+    authorize_with :admin
+
+    post :setup, {
+      uuid: 'bogus_uuid',
+      repo_name: 'test_repo',
+      vm_uuid: @vm_uuid
+    }
+    response_body = JSON.parse(@response.body)
+    response_errors = response_body['errors']
+    assert_not_nil response_errors, 'Expected error in response'
+    assert (response_errors.first.include? 'Path not found'), 'Expected 404'
+  end
+
+  test "setup user with bogus uuid in user and expect error" do
+    authorize_with :admin
+
+    post :setup, {
+      user: {uuid: 'bogus_uuid'},
+      repo_name: 'test_repo',
+      vm_uuid: @vm_uuid,
+      openid_prefix: 'https://www.google.com/accounts/o8/id'
+    }
+    response_body = JSON.parse(@response.body)
+    response_errors = response_body['errors']
+    assert_not_nil response_errors, 'Expected error in response'
+    assert (response_errors.first.include? 'ArgumentError: Require user email'),
+      'Expected RuntimeError'
+  end
+
+  test "setup user with no uuid and user, expect error" do
+    authorize_with :admin
+
+    post :setup, {
+      repo_name: 'test_repo',
+      vm_uuid: @vm_uuid,
+      openid_prefix: 'https://www.google.com/accounts/o8/id'
+    }
+    response_body = JSON.parse(@response.body)
+    response_errors = response_body['errors']
+    assert_not_nil response_errors, 'Expected error in response'
+    assert (response_errors.first.include? 'Required uuid or user'),
+        'Expected ArgumentError'
+  end
+
+  test "setup user with no uuid and email, expect error" do
+    authorize_with :admin
+
+    post :setup, {
+      user: {},
+      repo_name: 'test_repo',
+      vm_uuid: @vm_uuid,
+      openid_prefix: 'https://www.google.com/accounts/o8/id'
+    }
+    response_body = JSON.parse(@response.body)
+    response_errors = response_body['errors']
+    assert_not_nil response_errors, 'Expected error in response'
+    assert (response_errors.first.include? '<ArgumentError: Require user email'),
+        'Expected ArgumentError'
+  end
+
+  test "invoke setup with existing uuid, vm and repo and verify links" do
+    authorize_with :inactive
+    get :current
+    assert_response :success
+    inactive_user = JSON.parse(@response.body)
+    
+    authorize_with :admin
+
+    post :setup, {
+      uuid: inactive_user['uuid'],
+      repo_name: 'test_repo',
+      vm_uuid: @vm_uuid
+    }
+
+    assert_response :success
+
+    response_items = JSON.parse(@response.body)['items']
+    resp_obj = find_obj_in_resp response_items, 'User', nil
+
+    assert_not_nil resp_obj['uuid'], 'expected uuid for the new user'
+    assert_equal inactive_user['uuid'], resp_obj['uuid']
+    assert_equal inactive_user['email'], resp_obj['email'], 
+        'expecting inactive user email'
+
+    # expect repo and vm links
+    verify_link response_items, 'arvados#repository', true, 'permission', 'can_write',
+        'test_repo', resp_obj['uuid'], 'arvados#repository', true, 'Repository'
+
+    verify_link response_items, 'arvados#virtualMachine', true, 'permission', 'can_login',
+        @vm_uuid, resp_obj['uuid'], 'arvados#virtualMachine', false, 'VirtualMachine'
+  end
+
+  test "invoke setup with existing uuid in user, verify response" do
+    authorize_with :inactive
+    get :current
+    assert_response :success
+    inactive_user = JSON.parse(@response.body)
+    
+    authorize_with :admin
+
+    post :setup, {
+      user: {uuid: inactive_user['uuid']},
+      openid_prefix: 'https://www.google.com/accounts/o8/id'
+    }
+
+    assert_response :success
+
+    response_items = JSON.parse(@response.body)['items']
+    resp_obj = find_obj_in_resp response_items, 'User', nil
+
+    assert_not_nil resp_obj['uuid'], 'expected uuid for the new user'
+    assert_equal inactive_user['uuid'], resp_obj['uuid']
+    assert_equal inactive_user['email'], resp_obj['email'], 
+        'expecting inactive user email'
+  end
+
+  test "invoke setup with existing uuid but different email, expect original email" do
+    authorize_with :inactive
+    get :current
+    assert_response :success
+    inactive_user = JSON.parse(@response.body)
+    
+    authorize_with :admin
+
+    post :setup, {
+      uuid: inactive_user['uuid'],
+      user: {email: 'junk_email'}
+    }
+
+    assert_response :success
+
+    response_items = JSON.parse(@response.body)['items']
+    resp_obj = find_obj_in_resp response_items, 'User', nil
+
+    assert_not_nil resp_obj['uuid'], 'expected uuid for the new user'
+    assert_equal inactive_user['uuid'], resp_obj['uuid']
+    assert_equal inactive_user['email'], resp_obj['email'], 
+        'expecting inactive user email'
+  end
+
+  test "setup user with valid email and repo as input" do
+    authorize_with :admin
+
+    post :setup, {
+      repo_name: 'test_repo',
+      user: {email: 'foo@example.com'},
+      openid_prefix: 'https://www.google.com/accounts/o8/id'
+    }
+
+    assert_response :success
+    response_items = JSON.parse(@response.body)['items']
+    response_object = find_obj_in_resp response_items, 'User', nil
+    assert_not_nil response_object['uuid'], 'expected uuid for the new user'
+    assert_equal response_object['email'], 'foo@example.com', 'expected given email'
+
+    # three extra links; login link, group link and repo link
+    verify_num_links @all_links_at_start, 3
+  end
+
+  test "setup user with fake vm and expect error" do
+    authorize_with :admin
+
+    post :setup, {
+      repo_name: 'test_repo',
+      vm_uuid: 'no_such_vm',
+      user: {email: 'foo@example.com'},
+      openid_prefix: 'https://www.google.com/accounts/o8/id'
+    }
+
+    response_body = JSON.parse(@response.body)
+    response_errors = response_body['errors']
+    assert_not_nil response_errors, 'Expected error in response'
+    assert (response_errors.first.include? "No vm found for no_such_vm"), 
+          'Expected RuntimeError: No vm found for no_such_vm'
+  end
+
+  test "setup user with valid email, repo and real vm as input" do
+    authorize_with :admin
+
+    post :setup, {
+      repo_name: 'test_repo',
+      openid_prefix: 'https://www.google.com/accounts/o8/id',
+      vm_uuid: @vm_uuid,
+      user: {email: 'foo@example.com'}
+    }
+
+    assert_response :success
+    response_items = JSON.parse(@response.body)['items']
+    response_object = find_obj_in_resp response_items, 'User', nil
+    assert_not_nil response_object['uuid'], 'expected uuid for the new user'
+    assert_equal response_object['email'], 'foo@example.com', 'expected given email'
+
+    # three extra links; login link, group link and repo link
+    verify_num_links @all_links_at_start, 4
+  end
+
+  test "setup user with valid email, no vm and repo as input" do
+    authorize_with :admin
+
+    post :setup, {
+      user: {email: 'foo@example.com'},
+      openid_prefix: 'https://www.google.com/accounts/o8/id'
+    }
+
+    assert_response :success    
+    response_items = JSON.parse(@response.body)['items']
+    response_object = find_obj_in_resp response_items, 'User', nil
+    assert_not_nil response_object['uuid'], 'expected uuid for new user'
+    assert_equal response_object['email'], 'foo@example.com', 'expected given email'
+
+    # two extra links; login link and group link
+    verify_num_links @all_links_at_start, 2
+  end
+
+  test "setup user with email, first name, repo name and vm uuid" do
+    authorize_with :admin
+
+    post :setup, {
+      openid_prefix: 'https://www.google.com/accounts/o8/id',
+      repo_name: 'test_repo',
+      vm_uuid: @vm_uuid,
+      user: {
+        first_name: 'test_first_name',
+        email: 'foo@example.com'
+      }
+    }
+
+    assert_response :success
+    response_items = JSON.parse(@response.body)['items']
+    response_object = find_obj_in_resp response_items, 'User', nil
+    assert_not_nil response_object['uuid'], 'expected uuid for new user'
+    assert_equal response_object['email'], 'foo@example.com', 'expected given email'
+    assert_equal 'test_first_name', response_object['first_name'], 
+        'expecting first name'
+
+    # four extra links; login link, group link, repo link and vm link
+    verify_num_links @all_links_at_start, 4
+  end
+
+  test "setup user twice with email and check two different objects created" do
+    authorize_with :admin
+
+    post :setup, {
+      openid_prefix: 'https://www.google.com/accounts/o8/id',
+      repo_name: 'test_repo',
+      user: {
+        email: 'foo@example.com'
+      }
+    }
+
+    assert_response :success
+    response_items = JSON.parse(@response.body)['items']
+    response_object = find_obj_in_resp response_items, 'User', nil
+    assert_not_nil response_object['uuid'], 'expected uuid for new user'
+    assert_equal response_object['email'], 'foo@example.com', 'expected given email'
+    verify_num_links @all_links_at_start, 3   # openid, group, and repo. no vm
+
+    # create again
+    post :setup, {
+      user: {email: 'foo@example.com'},
+      openid_prefix: 'https://www.google.com/accounts/o8/id'
+    }
+
+    assert_response :success
+    response_items = JSON.parse(@response.body)['items']
+    response_object2 = find_obj_in_resp response_items, 'User', nil
+    assert_not_equal response_object['uuid'], response_object2['uuid'], 
+        'expected same uuid as first create operation'
+    assert_equal response_object['email'], 'foo@example.com', 'expected given email'
+
+    # extra login link only
+    verify_num_links @all_links_at_start, 4
+  end
+
+  test "setup user with openid prefix" do
+    authorize_with :admin
+
+    post :setup, {
+      repo_name: 'test_repo',
+      openid_prefix: 'http://www.example.com/account',
+      user: {
+        first_name: "in_create_test_first_name",
+        last_name: "test_last_name",
+        email: "foo@example.com"
+      }
+    }
+
+    assert_response :success
+
+    response_items = JSON.parse(@response.body)['items']
+    created = find_obj_in_resp response_items, 'User', nil
+
+    assert_equal 'in_create_test_first_name', created['first_name']
+    assert_not_nil created['uuid'], 'expected uuid for new user'
+    assert_not_nil created['email'], 'expected non-nil email'
+    assert_nil created['identity_url'], 'expected no identity_url' 
+
+    # verify links
+    # 3 new links: arvados#user, repo, and 'All users' group.
+    verify_num_links @all_links_at_start, 3
+
+    verify_link response_items, 'arvados#user', true, 'permission', 'can_login',
+        created['uuid'], created['email'], 'arvados#user', false, 'User'
+
+    verify_link response_items, 'arvados#repository', true, 'permission', 'can_write',
+        'test_repo', created['uuid'], 'arvados#repository', true, 'Repository'
+
+    verify_link response_items, 'arvados#group', true, 'permission', 'can_read',
+        'All users', created['uuid'], 'arvados#group', true, 'Group'
+
+    verify_link response_items, 'arvados#virtualMachine', false, 'permission', 'can_login',
+        nil, created['uuid'], 'arvados#virtualMachine', false, 'VirtualMachine'
+  end
+
+  test "invoke setup with no openid prefix, expect error" do
+    authorize_with :admin
+
+    post :setup, {
+      repo_name: 'test_repo',
+      user: {
+        first_name: "in_create_test_first_name",
+        last_name: "test_last_name",
+        email: "foo@example.com"
+      }
+    }
+
+    response_body = JSON.parse(@response.body)
+    response_errors = response_body['errors']
+    assert_not_nil response_errors, 'Expected error in response'
+    assert (response_errors.first.include? 'openid_prefix parameter is missing'),
+        'Expected ArgumentError'
+  end
+
+  test "setup user with user, vm and repo and verify links" do
+    authorize_with :admin
+
+    post :setup, {
+      user: {
+        first_name: "in_create_test_first_name",
+        last_name: "test_last_name",
+        email: "foo@example.com"
+      },
+      vm_uuid: @vm_uuid,
+      repo_name: 'test_repo',
+      openid_prefix: 'https://www.google.com/accounts/o8/id'
+    }
+
+    assert_response :success
+
+    response_items = JSON.parse(@response.body)['items']
+    created = find_obj_in_resp response_items, 'User', nil
+
+    assert_equal 'in_create_test_first_name', created['first_name']
+    assert_not_nil created['uuid'], 'expected uuid for new user'
+    assert_not_nil created['email'], 'expected non-nil email'
+    assert_nil created['identity_url'], 'expected no identity_url' 
+
+    # expect 4 new links: arvados#user, repo, vm and 'All users' group link
+    verify_num_links @all_links_at_start, 4
+
+    verify_link response_items, 'arvados#user', true, 'permission', 'can_login',
+        created['uuid'], created['email'], 'arvados#user', false, 'User'
+
+    verify_link response_items, 'arvados#repository', true, 'permission', 'can_write',
+        'test_repo', created['uuid'], 'arvados#repository', true, 'Repository'
+
+    verify_link response_items, 'arvados#group', true, 'permission', 'can_read',
+        'All users', created['uuid'], 'arvados#group', true, 'Group'
+
+    verify_link response_items, 'arvados#virtualMachine', true, 'permission', 'can_login', 
+        @vm_uuid, created['uuid'], 'arvados#virtualMachine', false, 'VirtualMachine'
+  end
+
+  test "create user as non admin user and expect error" do
+    authorize_with :active
+
+    post :create, {
+      user: {email: 'foo@example.com'}
+    }
+
+    response_body = JSON.parse(@response.body)
+    response_errors = response_body['errors']
+    assert_not_nil response_errors, 'Expected error in response'
+    assert (response_errors.first.include? 'PermissionDenied'), 
+          'Expected PermissionDeniedError'
+  end
+
+  test "setup user as non admin user and expect error" do
+    authorize_with :active
+
+    post :setup, {
+      openid_prefix: 'https://www.google.com/accounts/o8/id',
+      user: {email: 'foo@example.com'}
+    }
+
+    response_body = JSON.parse(@response.body)
+    response_errors = response_body['errors']
+    assert_not_nil response_errors, 'Expected error in response'
+    assert (response_errors.first.include? 'Forbidden'), 
+          'Expected Forbidden error'
+  end
+
+  test "setup user in multiple steps and verify response" do
+    authorize_with :admin
+
+    post :setup, {
+      openid_prefix: 'http://www.example.com/account',
+      user: {
+        email: "foo@example.com"
+      }
+    }
+
+    assert_response :success
+    response_items = JSON.parse(@response.body)['items']
+    created = find_obj_in_resp response_items, 'User', nil
+
+    assert_not_nil created['uuid'], 'expected uuid for new user'
+    assert_not_nil created['email'], 'expected non-nil email'
+    assert_equal created['email'], 'foo@example.com', 'expected input email'
+
+    # verify links; 2 new links: arvados#user, and 'All users' group.
+    verify_num_links @all_links_at_start, 2
+
+    verify_link response_items, 'arvados#user', true, 'permission', 'can_login',
+        created['uuid'], created['email'], 'arvados#user', false, 'User'
+
+    verify_link response_items, 'arvados#group', true, 'permission', 'can_read',
+        'All users', created['uuid'], 'arvados#group', true, 'Group'
+
+    verify_link response_items, 'arvados#repository', false, 'permission', 'can_write',
+        'test_repo', created['uuid'], 'arvados#repository', true, 'Repository'
+
+    verify_link response_items, 'arvados#virtualMachine', false, 'permission', 'can_login',
+        nil, created['uuid'], 'arvados#virtualMachine', false, 'VirtualMachine'
+
+   # invoke setup with a repository
+    post :setup, {
+      openid_prefix: 'http://www.example.com/account',
+      repo_name: 'new_repo',
+      uuid: created['uuid']
+    }
+
+    assert_response :success
+
+    response_items = JSON.parse(@response.body)['items']
+    created = find_obj_in_resp response_items, 'User', nil
+
+    assert_equal 'foo@example.com', created['email'], 'expected input email'
+
+     # verify links
+    verify_link response_items, 'arvados#group', true, 'permission', 'can_read',
+        'All users', created['uuid'], 'arvados#group', true, 'Group'
+
+    verify_link response_items, 'arvados#repository', true, 'permission', 'can_write',
+        'new_repo', created['uuid'], 'arvados#repository', true, 'Repository'
+
+    verify_link response_items, 'arvados#virtualMachine', false, 'permission', 'can_login',
+        nil, created['uuid'], 'arvados#virtualMachine', false, 'VirtualMachine'
+
+    # invoke setup with a vm_uuid
+    post :setup, {
+      vm_uuid: @vm_uuid,
+      openid_prefix: 'http://www.example.com/account',
+      user: {
+        email: 'junk_email'
+      },
+      uuid: created['uuid']
+    }
+
+    assert_response :success
+
+    response_items = JSON.parse(@response.body)['items']
+    created = find_obj_in_resp response_items, 'User', nil
+
+    assert_equal created['email'], 'foo@example.com', 'expected original email'
+
+    # verify links
+    verify_link response_items, 'arvados#group', true, 'permission', 'can_read',
+        'All users', created['uuid'], 'arvados#group', true, 'Group'
+
+    # since no repo name in input, we won't get any; even though user has one
+    verify_link response_items, 'arvados#repository', false, 'permission', 'can_write',
+        'new_repo', created['uuid'], 'arvados#repository', true, 'Repository'
+
+    verify_link response_items, 'arvados#virtualMachine', true, 'permission', 'can_login',
+        @vm_uuid, created['uuid'], 'arvados#virtualMachine', false, 'VirtualMachine'
+  end
+
+  test "setup and unsetup user" do
+    authorize_with :admin
+
+    post :setup, {
+      repo_name: 'test_repo',
+      vm_uuid: @vm_uuid,
+      user: {email: 'foo@example.com'},
+      openid_prefix: 'https://www.google.com/accounts/o8/id'
+    }
+
+    assert_response :success
+    response_items = JSON.parse(@response.body)['items']
+    created = find_obj_in_resp response_items, 'User', nil
+    assert_not_nil created['uuid'], 'expected uuid for the new user'
+    assert_equal created['email'], 'foo@example.com', 'expected given email'
+
+    # 4 extra links: login, group, repo and vm
+    verify_num_links @all_links_at_start, 4
+
+    verify_link response_items, 'arvados#user', true, 'permission', 'can_login',
+        created['uuid'], created['email'], 'arvados#user', false, 'User'
+
+    verify_link response_items, 'arvados#group', true, 'permission', 'can_read',
+        'All users', created['uuid'], 'arvados#group', true, 'Group'
+
+    verify_link response_items, 'arvados#repository', true, 'permission', 'can_write',
+        'test_repo', created['uuid'], 'arvados#repository', true, 'Repository'
+
+    verify_link response_items, 'arvados#virtualMachine', true, 'permission', 'can_login',
+        @vm_uuid, created['uuid'], 'arvados#virtualMachine', false, 'VirtualMachine'
+
+    verify_link_existence created['uuid'], created['email'], true, true, true, false
+
+    # now unsetup this user
+    post :unsetup, uuid: created['uuid']
+    assert_response :success
+
+    created2 = JSON.parse(@response.body)
+    assert_not_nil created2['uuid'], 'expected uuid for the newly created user'
+    assert_equal created['uuid'], created2['uuid'], 'expected uuid not found'
+    
+    verify_link_existence created['uuid'], created['email'], false, false, false, false
+  end
+
+  test "unsetup active user" do
+    authorize_with :active
+    get :current
+    assert_response :success
+    active_user = JSON.parse(@response.body)
+    assert_not_nil active_user['uuid'], 'expected uuid for the active user'
+    assert active_user['is_active'], 'expected is_active for active user'
+
+    verify_link_existence active_user['uuid'], active_user['email'],
+          false, false, false, true
+
+    authorize_with :admin
+
+    # now unsetup this user
+    post :unsetup, uuid: active_user['uuid']
+    assert_response :success
+
+    response_user = JSON.parse(@response.body)
+    assert_not_nil response_user['uuid'], 'expected uuid for the upsetup user'
+    assert_equal active_user['uuid'], response_user['uuid'], 'expected uuid not found'
+    assert !response_user['is_active'], 'expected user to be inactive'
+
+    verify_link_existence response_user['uuid'], response_user['email'],
+          false, false, false, false
+  end
+
+  def verify_num_links (original_links, expected_additional_links)
+    links_now = Link.all
+    assert_equal original_links.size+expected_additional_links, Link.all.size,
+        "Expected #{expected_additional_links.inspect} more links"
+  end
+
+  def find_obj_in_resp (response_items, object_type, head_kind=nil)
+    return_obj = nil
+    response_items.each { |x|
+      if !x
+        next
+      end
+
+      if object_type == 'User'
+        if !x['head_kind']
+          return_obj = x
+          break
+        end
+      else  # looking for a link
+        if x['head_kind'] == head_kind
+          return_obj = x
+          break
+        end
+      end
+    }
+    return return_obj
+  end
+
+  def verify_link(response_items, link_object_name, expect_link, link_class,
+        link_name, head_uuid, tail_uuid, head_kind, fetch_object, class_name)
+
+    link = find_obj_in_resp response_items, 'Link', link_object_name
+
+    if !expect_link 
+      assert_nil link, "Expected no link for #{link_object_name}"
+      return
+    end
+
+    assert_not_nil link, "Expected link for #{link_object_name}"
+
+    if fetch_object
+      object = Object.const_get(class_name).where(name: head_uuid)
+      assert [] != object, "expected #{class_name} with name #{head_uuid}"
+      head_uuid = object.first[:uuid]
+    end
+    assert_equal link['link_class'], link_class,
+        "did not find expected link_class for #{link_object_name}"
+    assert_equal link['name'], link_name,
+        "did not find expected link_name for #{link_object_name}"
+    assert_equal link['tail_uuid'], tail_uuid,
+        "did not find expected tail_uuid for #{link_object_name}"
+    assert_equal link['head_kind'], head_kind,
+        "did not find expected head_kind for #{link_object_name}"
+    assert_equal link['head_uuid'], head_uuid,
+        "did not find expected head_uuid for #{link_object_name}"
+  end
+
+  def verify_link_existence uuid, email, expect_oid_login_perms,
+        expect_repo_perms, expect_vm_perms, expect_signatures
+    # verify that all links are deleted for the user
+    oid_login_perms = Link.where(tail_uuid: email,
+                                 head_kind: 'arvados#user',
+                                 link_class: 'permission',
+                                 name: 'can_login')
+    if expect_oid_login_perms
+      assert oid_login_perms.any?, "expected oid_login_perms"
+    else
+      assert !oid_login_perms.any?, "expected all oid_login_perms deleted"
+    end
+
+    repo_perms = Link.where(tail_uuid: uuid,
+                              head_kind: 'arvados#repository',
+                              link_class: 'permission',
+                              name: 'can_write')
+    if expect_repo_perms
+      assert repo_perms.any?, "expected repo_perms"
+    else
+      assert !repo_perms.any?, "expected all repo_perms deleted"
+    end
+
+    vm_login_perms = Link.where(tail_uuid: uuid,
+                              head_kind: 'arvados#virtualMachine',
+                              link_class: 'permission',
+                              name: 'can_login')
+    if expect_vm_perms
+      assert vm_login_perms.any?, "expected vm_login_perms"
+    else
+      assert !vm_login_perms.any?, "expected all vm_login_perms deleted"
+    end
+
+    signed_uuids = Link.where(link_class: 'signature',
+                                  tail_kind: 'arvados#user',
+                                  tail_uuid: uuid)
+          
+    if expect_signatures
+      assert signed_uuids.any?, "expected singnatures"
+    else
+      assert !signed_uuids.any?, "expected all singnatures deleted"
+    end
+
+  end
 end
diff --git a/services/api/test/test.git.tar b/services/api/test/test.git.tar
new file mode 100644 (file)
index 0000000..fdd7db6
Binary files /dev/null and b/services/api/test/test.git.tar differ
diff --git a/services/keep/keep.go b/services/keep/keep.go
new file mode 100644 (file)
index 0000000..06a81b6
--- /dev/null
@@ -0,0 +1,137 @@
+package main
+
+import (
+       "bufio"
+       "crypto/md5"
+       "errors"
+       "fmt"
+       "github.com/gorilla/mux"
+       "log"
+       "net/http"
+       "os"
+       "strings"
+)
+
+const DEFAULT_PORT = 25107
+const BLOCKSIZE = 64 * 1024 * 1024
+
+var KeepVolumes []string
+
+func main() {
+       // Look for local keep volumes.
+       KeepVolumes = FindKeepVolumes()
+       if len(KeepVolumes) == 0 {
+               log.Fatal("could not find any keep volumes")
+       }
+       for _, v := range KeepVolumes {
+               log.Println("keep volume:", v)
+       }
+
+       // Set up REST handlers.
+       //
+       // Start with a router that will route each URL path to an
+       // appropriate handler.
+       //
+       rest := mux.NewRouter()
+       rest.HandleFunc("/{hash:[0-9a-f]{32}}", GetBlockHandler).Methods("GET")
+
+       // Tell the built-in HTTP server to direct all requests to the REST
+       // router.
+       http.Handle("/", rest)
+
+       // Start listening for requests.
+       port := fmt.Sprintf(":%d", DEFAULT_PORT)
+       http.ListenAndServe(port, nil)
+}
+
+// FindKeepVolumes
+//     Returns a list of Keep volumes mounted on this system.
+//
+//     A Keep volume is a normal or tmpfs volume with a /keep
+//     directory at the top level of the mount point.
+//
+func FindKeepVolumes() []string {
+       vols := make([]string, 0)
+
+       if f, err := os.Open("/proc/mounts"); err != nil {
+               log.Fatal("could not read /proc/mounts: ", err)
+       } else {
+               scanner := bufio.NewScanner(f)
+               for scanner.Scan() {
+                       args := strings.Fields(scanner.Text())
+                       dev, mount := args[0], args[1]
+                       if (dev == "tmpfs" || strings.HasPrefix(dev, "/dev/")) && mount != "/" {
+                               keep := mount + "/keep"
+                               if st, err := os.Stat(keep); err == nil && st.IsDir() {
+                                       vols = append(vols, keep)
+                               }
+                       }
+               }
+               if err := scanner.Err(); err != nil {
+                       log.Fatal(err)
+               }
+       }
+       return vols
+}
+
+func GetBlockHandler(w http.ResponseWriter, req *http.Request) {
+       hash := mux.Vars(req)["hash"]
+
+       block, err := GetBlock(hash)
+       if err != nil {
+               http.Error(w, err.Error(), 404)
+               return
+       }
+
+       _, err = w.Write(block)
+       if err != nil {
+               log.Printf("GetBlockHandler: writing response: %s", err)
+       }
+
+       return
+}
+
+func GetBlock(hash string) ([]byte, error) {
+       var buf = make([]byte, BLOCKSIZE)
+
+       // Attempt to read the requested hash from a keep volume.
+       for _, vol := range KeepVolumes {
+               var f *os.File
+               var err error
+               var nread int
+
+               path := fmt.Sprintf("%s/%s/%s", vol, hash[0:3], hash)
+
+               f, err = os.Open(path)
+               if err != nil {
+                       log.Printf("%s: opening %s: %s\n", vol, path, err)
+                       continue
+               }
+
+               nread, err = f.Read(buf)
+               if err != nil {
+                       log.Printf("%s: reading %s: %s\n", vol, path, err)
+                       continue
+               }
+
+               // Double check the file checksum.
+               //
+               filehash := fmt.Sprintf("%x", md5.Sum(buf[:nread]))
+               if filehash != hash {
+                       // TODO(twp): this condition probably represents a bad disk and
+                       // should raise major alarm bells for an administrator: e.g.
+                       // they should be sent directly to an event manager at high
+                       // priority or logged as urgent problems.
+                       //
+                       log.Printf("%s: checksum mismatch: %s (actual hash %s)\n",
+                               vol, path, filehash)
+                       continue
+               }
+
+               // Success!
+               return buf[:nread], nil
+       }
+
+       log.Printf("%s: not found on any volumes, giving up\n", hash)
+       return buf, errors.New("not found: " + hash)
+}
diff --git a/services/keep/keep_test.go b/services/keep/keep_test.go
new file mode 100644 (file)
index 0000000..5e3b763
--- /dev/null
@@ -0,0 +1,125 @@
+package main
+
+import (
+       "fmt"
+       "io/ioutil"
+       "os"
+       "path"
+       "testing"
+)
+
+var TEST_BLOCK = []byte("The quick brown fox jumps over the lazy dog.")
+var TEST_HASH = "e4d909c290d0fb1ca068ffaddf22cbd0"
+var BAD_BLOCK = []byte("The magic words are squeamish ossifrage.")
+
+// Test simple block reads.
+func TestGetBlockOK(t *testing.T) {
+       defer teardown()
+
+       // Create two test Keep volumes and store a block in each of them.
+       setup(t, 2)
+       for _, vol := range KeepVolumes {
+               store(t, vol, TEST_HASH, TEST_BLOCK)
+       }
+
+       // Check that GetBlock returns success.
+       result, err := GetBlock(TEST_HASH)
+       if err != nil {
+               t.Errorf("GetBlock error: %s", err)
+       }
+       if fmt.Sprint(result) != fmt.Sprint(TEST_BLOCK) {
+               t.Errorf("expected %s, got %s", TEST_BLOCK, result)
+       }
+}
+
+// Test block reads when one Keep volume is missing.
+func TestGetBlockOneKeepOK(t *testing.T) {
+       defer teardown()
+
+       // Two test Keep volumes, only the second has a block.
+       setup(t, 2)
+       store(t, KeepVolumes[1], TEST_HASH, TEST_BLOCK)
+
+       // Check that GetBlock returns success.
+       result, err := GetBlock(TEST_HASH)
+       if err != nil {
+               t.Errorf("GetBlock error: %s", err)
+       }
+       if fmt.Sprint(result) != fmt.Sprint(TEST_BLOCK) {
+               t.Errorf("expected %s, got %s", TEST_BLOCK, result)
+       }
+}
+
+// Test block read failure.
+func TestGetBlockFail(t *testing.T) {
+       defer teardown()
+
+       // Create two empty test Keep volumes.
+       setup(t, 2)
+
+       // Check that GetBlock returns failure.
+       result, err := GetBlock(TEST_HASH)
+       if err == nil {
+               t.Errorf("GetBlock incorrectly returned success: ", result)
+       }
+}
+
+// Test reading a corrupt block.
+func TestGetBlockCorrupt(t *testing.T) {
+       defer teardown()
+
+       // Create two test Keep volumes and store a block in each of them,
+       // but the hash of the block does not match the filename.
+       setup(t, 2)
+       for _, vol := range KeepVolumes {
+               store(t, vol, TEST_HASH, BAD_BLOCK)
+       }
+
+       // Check that GetBlock returns failure.
+       result, err := GetBlock(TEST_HASH)
+       if err == nil {
+               t.Errorf("GetBlock incorrectly returned success: %s", result)
+       }
+}
+
+// setup
+//     Create KeepVolumes for testing.
+//
+func setup(t *testing.T, num_volumes int) {
+       KeepVolumes = make([]string, num_volumes)
+       for i := range KeepVolumes {
+               if dir, err := ioutil.TempDir(os.TempDir(), "keeptest"); err == nil {
+                       KeepVolumes[i] = dir + "/keep"
+               } else {
+                       t.Fatal(err)
+               }
+       }
+}
+
+// teardown
+//     Cleanup to perform after each test.
+//
+func teardown() {
+       for _, vol := range KeepVolumes {
+               os.RemoveAll(path.Dir(vol))
+       }
+}
+
+// store
+//
+func store(t *testing.T, keepdir string, filename string, block []byte) error {
+       blockdir := fmt.Sprintf("%s/%s", keepdir, filename[:3])
+       if err := os.MkdirAll(blockdir, 0755); err != nil {
+               t.Fatal(err)
+       }
+
+       blockpath := fmt.Sprintf("%s/%s", blockdir, filename)
+       if f, err := os.Create(blockpath); err == nil {
+               f.Write(block)
+               f.Close()
+       } else {
+               t.Fatal(err)
+       }
+
+       return nil
+}