Merge branch 'master' into 9587-trash-page
authorradhika <radhika@curoverse.com>
Tue, 6 Jun 2017 00:29:18 +0000 (20:29 -0400)
committerradhika <radhika@curoverse.com>
Tue, 6 Jun 2017 00:29:18 +0000 (20:29 -0400)
25 files changed:
apps/workbench/app/assets/javascripts/filterable.js
apps/workbench/app/assets/javascripts/select_modal.js
build/run-tests.sh
sdk/cwl/setup.py
sdk/go/arvados/client.go
sdk/go/arvadosclient/arvadosclient.go
sdk/go/arvadosclient/arvadosclient_test.go
sdk/go/keepclient/discover.go
sdk/go/keepclient/discover_test.go
sdk/go/keepclient/keepclient.go
sdk/go/keepclient/keepclient_test.go
sdk/go/keepclient/support.go
services/api/app/controllers/arvados/v1/keep_services_controller.rb
services/api/test/functional/arvados/v1/keep_services_controller_test.rb
services/keep-balance/integration_test.go
services/keep-web/handler.go
services/keepproxy/keepproxy.go
services/keepproxy/keepproxy_test.go
services/keepstore/keepstore.go
services/keepstore/pull_worker_integration_test.go
tools/keep-block-check/keep-block-check.go
tools/keep-block-check/keep-block-check_test.go
tools/keep-exercise/keep-exercise.go
tools/keep-rsync/keep-rsync.go
tools/keep-rsync/keep-rsync_test.go

index 5f6370c2905171bda848622f9d2e6e638d33ad9b..e3639d0f2bdefea6d72da8b0fd6cd34bbe47f4c2 100644 (file)
@@ -57,6 +57,7 @@ function updateFilterableQueryNow($target) {
     } else {
       params.filters = [['any', '@@', newquery.trim().concat(':*')]];
     }
+    $(".modal-dialog-preview-pane").html("");
     $target.data('infinite-content-params-filterable', params);
     $target.data('filterable-query', newquery);
 }
index 17b334eb643438631eb35c3b8ffa31d04d9c2d30..d31cb45dbaf8bcd9cb2ac1ec65a1ab2a8b3c773d 100644 (file)
@@ -120,6 +120,7 @@ $(document).on('click', '.selectable', function() {
                   'project_uuid': project_uuid
                  };
     }
+    $(".modal-dialog-preview-pane").html("");
     // Use current selection as dropdown button label
     $(this).
         closest('.dropdown-menu').
index b6a93d471211a41a3d97c6aa8bbe11e3b033e130..dffbe32e8ab9c89d6cecf02dd445c8314d2560ad 100755 (executable)
@@ -567,7 +567,7 @@ do_test_once() {
         # mode makes Go show the wrong line numbers when reporting
         # compilation errors.
         go get -t "git.curoverse.com/arvados.git/$1" && \
-            cd "$WORKSPACE/$1" && \
+            cd "$GOPATH/src/git.curoverse.com/arvados.git/$1" && \
             [[ -z "$(gofmt -e -d . | tee /dev/stderr)" ]] && \
             if [[ -n "${testargs[$1]}" ]]
         then
index df988f69918e337f8a2a1e91346bbf35dc8a1878..6633314042624d932ca5989e126ff19becf434f3 100644 (file)
@@ -48,7 +48,7 @@ setup(name='arvados-cwl-runner',
       # Note that arvados/build/run-build-packages.sh looks at this
       # file to determine what version of cwltool and schema-salad to build.
       install_requires=[
-          'cwltool==1.0.20170510165748',
+          'cwltool==1.0.20170525215327',
           'schema-salad==2.5.20170428142041',
           'typing==3.5.3.0',
           'ruamel.yaml==0.13.7',
index 9691e7a07e475668cc73a80dffba466addb3b4ef..d7eb811b8a7a26a08931b07b9c66fcfec83d78a3 100644 (file)
@@ -6,6 +6,7 @@ import (
        "fmt"
        "io"
        "io/ioutil"
+       "log"
        "math"
        "net/http"
        "net/url"
@@ -63,13 +64,25 @@ var DefaultSecureClient = &http.Client{
 // ARVADOS_API_* environment variables.
 func NewClientFromEnv() *Client {
        var svcs []string
-       if s := os.Getenv("ARVADOS_KEEP_SERVICES"); s != "" {
-               svcs = strings.Split(s, " ")
+       for _, s := range strings.Split(os.Getenv("ARVADOS_KEEP_SERVICES"), " ") {
+               if s == "" {
+                       continue
+               } else if u, err := url.Parse(s); err != nil {
+                       log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
+               } else if !u.IsAbs() {
+                       log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
+               } else {
+                       svcs = append(svcs, s)
+               }
+       }
+       var insecure bool
+       if s := strings.ToLower(os.Getenv("ARVADOS_API_HOST_INSECURE")); s == "1" || s == "yes" || s == "true" {
+               insecure = true
        }
        return &Client{
                APIHost:         os.Getenv("ARVADOS_API_HOST"),
                AuthToken:       os.Getenv("ARVADOS_API_TOKEN"),
-               Insecure:        os.Getenv("ARVADOS_API_HOST_INSECURE") != "",
+               Insecure:        insecure,
                KeepServiceURIs: svcs,
        }
 }
index 021b9471ff93814b81c933923e819f821efd8f1b..4cfda94581518fd9360ebc4f3268e231893797c7 100644 (file)
@@ -11,11 +11,13 @@ import (
        "fmt"
        "io"
        "io/ioutil"
+       "log"
        "net/http"
        "net/url"
        "os"
        "regexp"
        "strings"
+       "sync"
        "time"
 
        "git.curoverse.com/arvados.git/sdk/go/arvados"
@@ -38,6 +40,12 @@ var MaxIdleConnectionDuration = 30 * time.Second
 
 var RetryDelay = 2 * time.Second
 
+var (
+       defaultInsecureHTTPClient *http.Client
+       defaultSecureHTTPClient   *http.Client
+       defaultHTTPClientMtx      sync.Mutex
+)
+
 // Indicates an error that was returned by the API server.
 type APIServerError struct {
        // Address of server returning error, of the form "host:port".
@@ -66,6 +74,13 @@ func (e APIServerError) Error() string {
        }
 }
 
+// StringBool tests whether s is suggestive of true. It returns true
+// if s is a mixed/uppoer/lower-case variant of "1", "yes", or "true".
+func StringBool(s string) bool {
+       s = strings.ToLower(s)
+       return s == "1" || s == "yes" || s == "true"
+}
+
 // Helper type so we don't have to write out 'map[string]interface{}' every time.
 type Dict map[string]interface{}
 
@@ -111,26 +126,31 @@ var CertFiles = []string{
        "/etc/pki/tls/certs/ca-bundle.crt",   // Fedora/RHEL
 }
 
-// MakeTLSConfig sets up TLS configuration for communicating with Arvados and Keep services.
+// MakeTLSConfig sets up TLS configuration for communicating with
+// Arvados and Keep services.
 func MakeTLSConfig(insecure bool) *tls.Config {
        tlsconfig := tls.Config{InsecureSkipVerify: insecure}
 
        if !insecure {
-               // Look for /etc/arvados/ca-certificates.crt in addition to normal system certs.
+               // Use the first entry in CertFiles that we can read
+               // certificates from. If none of those work out, use
+               // the Go defaults.
                certs := x509.NewCertPool()
                for _, file := range CertFiles {
                        data, err := ioutil.ReadFile(file)
-                       if err == nil {
-                               success := certs.AppendCertsFromPEM(data)
-                               if !success {
-                                       fmt.Printf("Unable to load any certificates from %v", file)
-                               } else {
-                                       tlsconfig.RootCAs = certs
-                                       break
+                       if err != nil {
+                               if !os.IsNotExist(err) {
+                                       log.Printf("error reading %q: %s", file, err)
                                }
+                               continue
+                       }
+                       if !certs.AppendCertsFromPEM(data) {
+                               log.Printf("unable to load any certificates from %v", file)
+                               continue
                        }
+                       tlsconfig.RootCAs = certs
+                       break
                }
-               // Will use system default CA roots instead.
        }
 
        return &tlsconfig
@@ -150,6 +170,7 @@ func New(c *arvados.Client) (*ArvadosClient, error) {
                        TLSClientConfig: MakeTLSConfig(c.Insecure)}},
                External:          false,
                Retries:           2,
+               KeepServiceURIs:   c.KeepServiceURIs,
                lastClosedIdlesAt: time.Now(),
        }
 
@@ -161,42 +182,12 @@ func New(c *arvados.Client) (*ArvadosClient, error) {
 // ARVADOS_API_HOST_INSECURE, ARVADOS_EXTERNAL_CLIENT, and
 // ARVADOS_KEEP_SERVICES.
 func MakeArvadosClient() (ac *ArvadosClient, err error) {
-       var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
-       insecure := matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
-       external := matchTrue.MatchString(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
-
-       ac = &ArvadosClient{
-               Scheme:      "https",
-               ApiServer:   os.Getenv("ARVADOS_API_HOST"),
-               ApiToken:    os.Getenv("ARVADOS_API_TOKEN"),
-               ApiInsecure: insecure,
-               Client: &http.Client{Transport: &http.Transport{
-                       TLSClientConfig: MakeTLSConfig(insecure)}},
-               External: external,
-               Retries:  2}
-
-       for _, s := range strings.Split(os.Getenv("ARVADOS_KEEP_SERVICES"), " ") {
-               if s == "" {
-                       continue
-               }
-               if u, err := url.Parse(s); err != nil {
-                       return ac, fmt.Errorf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
-               } else if !u.IsAbs() {
-                       return ac, fmt.Errorf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
-               }
-               ac.KeepServiceURIs = append(ac.KeepServiceURIs, s)
-       }
-
-       if ac.ApiServer == "" {
-               return ac, MissingArvadosApiHost
-       }
-       if ac.ApiToken == "" {
-               return ac, MissingArvadosApiToken
+       ac, err = New(arvados.NewClientFromEnv())
+       if err != nil {
+               return
        }
-
-       ac.lastClosedIdlesAt = time.Now()
-
-       return ac, err
+       ac.External = StringBool(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
+       return
 }
 
 // CallRaw is the same as Call() but returns a Reader that reads the
@@ -420,3 +411,20 @@ func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err erro
                return value, ErrInvalidArgument
        }
 }
+
+func (ac *ArvadosClient) httpClient() *http.Client {
+       if ac.Client != nil {
+               return ac.Client
+       }
+       c := &defaultSecureHTTPClient
+       if ac.ApiInsecure {
+               c = &defaultInsecureHTTPClient
+       }
+       if *c == nil {
+               defaultHTTPClientMtx.Lock()
+               defer defaultHTTPClientMtx.Unlock()
+               *c = &http.Client{Transport: &http.Transport{
+                       TLSClientConfig: MakeTLSConfig(ac.ApiInsecure)}}
+       }
+       return *c
+}
index 54591d30ba34706cc9f4359c02c612f86b396bf8..794a3ce16f732ede733ab1a710be294da4780ace 100644 (file)
@@ -41,21 +41,21 @@ func (s *ServerRequiredSuite) SetUpTest(c *C) {
 
 func (s *ServerRequiredSuite) TestMakeArvadosClientSecure(c *C) {
        os.Setenv("ARVADOS_API_HOST_INSECURE", "")
-       kc, err := MakeArvadosClient()
+       ac, err := MakeArvadosClient()
        c.Assert(err, Equals, nil)
-       c.Check(kc.ApiServer, Equals, os.Getenv("ARVADOS_API_HOST"))
-       c.Check(kc.ApiToken, Equals, os.Getenv("ARVADOS_API_TOKEN"))
-       c.Check(kc.ApiInsecure, Equals, false)
+       c.Check(ac.ApiServer, Equals, os.Getenv("ARVADOS_API_HOST"))
+       c.Check(ac.ApiToken, Equals, os.Getenv("ARVADOS_API_TOKEN"))
+       c.Check(ac.ApiInsecure, Equals, false)
 }
 
 func (s *ServerRequiredSuite) TestMakeArvadosClientInsecure(c *C) {
        os.Setenv("ARVADOS_API_HOST_INSECURE", "true")
-       kc, err := MakeArvadosClient()
+       ac, err := MakeArvadosClient()
        c.Assert(err, Equals, nil)
-       c.Check(kc.ApiInsecure, Equals, true)
-       c.Check(kc.ApiServer, Equals, os.Getenv("ARVADOS_API_HOST"))
-       c.Check(kc.ApiToken, Equals, os.Getenv("ARVADOS_API_TOKEN"))
-       c.Check(kc.Client.Transport.(*http.Transport).TLSClientConfig.InsecureSkipVerify, Equals, true)
+       c.Check(ac.ApiInsecure, Equals, true)
+       c.Check(ac.ApiServer, Equals, os.Getenv("ARVADOS_API_HOST"))
+       c.Check(ac.ApiToken, Equals, os.Getenv("ARVADOS_API_TOKEN"))
+       c.Check(ac.Client.Transport.(*http.Transport).TLSClientConfig.InsecureSkipVerify, Equals, true)
 }
 
 func (s *ServerRequiredSuite) TestGetInvalidUUID(c *C) {
index f3e39606980b79b71ddb62ec7d61d90f9b6d0056..e2cd329fc4c22ccfdb73ff6099ce8c95f6f28d16 100644 (file)
@@ -4,105 +4,167 @@ import (
        "encoding/json"
        "fmt"
        "log"
-       "net/http"
        "os"
        "os/signal"
-       "reflect"
        "strings"
+       "sync"
        "syscall"
        "time"
+
+       "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
 )
 
-// DiscoverKeepServers gets list of available keep services from the
-// API server.
-//
-// If a list of services is provided in the arvadosclient (e.g., from
-// an environment variable or local config), that list is used
-// instead.
-func (this *KeepClient) DiscoverKeepServers() error {
-       if this.Arvados.KeepServiceURIs != nil {
-               this.foundNonDiskSvc = true
-               this.replicasPerService = 0
-               if c, ok := this.Client.(*http.Client); ok {
-                       this.setClientSettingsNonDisk(c)
-               }
-               roots := make(map[string]string)
-               for i, uri := range this.Arvados.KeepServiceURIs {
-                       roots[fmt.Sprintf("00000-bi6l4-%015d", i)] = uri
-               }
-               this.SetServiceRoots(roots, roots, roots)
-               return nil
+// ClearCache clears the Keep service discovery cache.
+func RefreshServiceDiscovery() {
+       svcListCacheMtx.Lock()
+       defer svcListCacheMtx.Unlock()
+       for _, ent := range svcListCache {
+               ent.clear <- struct{}{}
        }
+}
 
-       // ArvadosClient did not provide a services list. Ask API
-       // server for a list of accessible services.
-       var list svcList
-       err := this.Arvados.Call("GET", "keep_services", "", "accessible", nil, &list)
-       if err != nil {
-               return err
+// ClearCacheOnSIGHUP installs a signal handler that calls
+// ClearCache when SIGHUP is received.
+func RefreshServiceDiscoveryOnSIGHUP() {
+       svcListCacheMtx.Lock()
+       defer svcListCacheMtx.Unlock()
+       if svcListCacheSignal != nil {
+               return
        }
-       return this.loadKeepServers(list)
+       svcListCacheSignal = make(chan os.Signal, 1)
+       signal.Notify(svcListCacheSignal, syscall.SIGHUP)
+       go func() {
+               for range svcListCacheSignal {
+                       RefreshServiceDiscovery()
+               }
+       }()
 }
 
-// LoadKeepServicesFromJSON gets list of available keep services from given JSON
-func (this *KeepClient) LoadKeepServicesFromJSON(services string) error {
-       var list svcList
-
-       // Load keep services from given json
-       dec := json.NewDecoder(strings.NewReader(services))
-       if err := dec.Decode(&list); err != nil {
-               return err
-       }
+var (
+       svcListCache       = map[string]cachedSvcList{}
+       svcListCacheSignal chan os.Signal
+       svcListCacheMtx    sync.Mutex
+)
 
-       return this.loadKeepServers(list)
+type cachedSvcList struct {
+       arv    *arvadosclient.ArvadosClient
+       latest chan svcList
+       clear  chan struct{}
 }
 
-// RefreshServices calls DiscoverKeepServers to refresh the keep
-// service list on SIGHUP; when the given interval has elapsed since
-// the last refresh; and (if the last refresh failed) the given
-// errInterval has elapsed.
-func (kc *KeepClient) RefreshServices(interval, errInterval time.Duration) {
-       var previousRoots = []map[string]string{}
-
-       timer := time.NewTimer(interval)
-       gotHUP := make(chan os.Signal, 1)
-       signal.Notify(gotHUP, syscall.SIGHUP)
+// Check for new services list every few minutes. Send the latest list
+// to the "latest" channel as needed.
+func (ent *cachedSvcList) poll() {
+       wakeup := make(chan struct{})
+
+       replace := make(chan svcList)
+       go func() {
+               wakeup <- struct{}{}
+               current := <-replace
+               for {
+                       select {
+                       case <-ent.clear:
+                               wakeup <- struct{}{}
+                               // Wait here for the next success, in
+                               // order to avoid returning stale
+                               // results on the "latest" channel.
+                               current = <-replace
+                       case current = <-replace:
+                       case ent.latest <- current:
+                       }
+               }
+       }()
 
+       okDelay := 5 * time.Minute
+       errDelay := 3 * time.Second
+       timer := time.NewTimer(okDelay)
        for {
                select {
-               case <-gotHUP:
                case <-timer.C:
+               case <-wakeup:
+                       if !timer.Stop() {
+                               // Lost race stopping timer; skip extra firing
+                               <-timer.C
+                       }
                }
-               timer.Reset(interval)
-
-               if err := kc.DiscoverKeepServers(); err != nil {
-                       log.Printf("WARNING: Error retrieving services list: %v (retrying in %v)", err, errInterval)
-                       timer.Reset(errInterval)
+               var next svcList
+               err := ent.arv.Call("GET", "keep_services", "", "accessible", nil, &next)
+               if err != nil {
+                       log.Printf("WARNING: Error retrieving services list: %v (retrying in %v)", err, errDelay)
+                       timer.Reset(errDelay)
                        continue
                }
-               newRoots := []map[string]string{kc.LocalRoots(), kc.GatewayRoots()}
+               replace <- next
+               timer.Reset(okDelay)
+       }
+}
 
-               if !reflect.DeepEqual(previousRoots, newRoots) {
-                       DebugPrintf("DEBUG: Updated services list: locals %v gateways %v", newRoots[0], newRoots[1])
-                       previousRoots = newRoots
+// discoverServices gets the list of available keep services from
+// the API server.
+//
+// If a list of services is provided in the arvadosclient (e.g., from
+// an environment variable or local config), that list is used
+// instead.
+//
+// If an API call is made, the result is cached for 5 minutes or until
+// ClearCache() is called, and during this interval it is reused by
+// other KeepClients that use the same API server host.
+func (kc *KeepClient) discoverServices() error {
+       if kc.disableDiscovery {
+               return nil
+       }
+
+       if kc.Arvados.KeepServiceURIs != nil {
+               kc.disableDiscovery = true
+               kc.foundNonDiskSvc = true
+               kc.replicasPerService = 0
+               roots := make(map[string]string)
+               for i, uri := range kc.Arvados.KeepServiceURIs {
+                       roots[fmt.Sprintf("00000-bi6l4-%015d", i)] = uri
                }
+               kc.setServiceRoots(roots, roots, roots)
+               return nil
+       }
 
-               if len(newRoots[0]) == 0 {
-                       log.Printf("WARNING: No local services (retrying in %v)", errInterval)
-                       timer.Reset(errInterval)
+       svcListCacheMtx.Lock()
+       cacheEnt, ok := svcListCache[kc.Arvados.ApiServer]
+       if !ok {
+               arv := *kc.Arvados
+               cacheEnt = cachedSvcList{
+                       latest: make(chan svcList),
+                       clear:  make(chan struct{}),
+                       arv:    &arv,
                }
+               go cacheEnt.poll()
+               svcListCache[kc.Arvados.ApiServer] = cacheEnt
        }
+       svcListCacheMtx.Unlock()
+
+       return kc.loadKeepServers(<-cacheEnt.latest)
 }
 
-// loadKeepServers
-func (this *KeepClient) loadKeepServers(list svcList) error {
+// LoadKeepServicesFromJSON gets list of available keep services from
+// given JSON and disables automatic service discovery.
+func (kc *KeepClient) LoadKeepServicesFromJSON(services string) error {
+       kc.disableDiscovery = true
+
+       var list svcList
+       dec := json.NewDecoder(strings.NewReader(services))
+       if err := dec.Decode(&list); err != nil {
+               return err
+       }
+
+       return kc.loadKeepServers(list)
+}
+
+func (kc *KeepClient) loadKeepServers(list svcList) error {
        listed := make(map[string]bool)
        localRoots := make(map[string]string)
        gatewayRoots := make(map[string]string)
        writableLocalRoots := make(map[string]string)
 
        // replicasPerService is 1 for disks; unknown or unlimited otherwise
-       this.replicasPerService = 1
+       kc.replicasPerService = 1
 
        for _, service := range list.Items {
                scheme := "http"
@@ -121,12 +183,12 @@ func (this *KeepClient) loadKeepServers(list svcList) error {
                if service.ReadOnly == false {
                        writableLocalRoots[service.Uuid] = url
                        if service.SvcType != "disk" {
-                               this.replicasPerService = 0
+                               kc.replicasPerService = 0
                        }
                }
 
                if service.SvcType != "disk" {
-                       this.foundNonDiskSvc = true
+                       kc.foundNonDiskSvc = true
                }
 
                // Gateway services are only used when specified by
@@ -137,14 +199,6 @@ func (this *KeepClient) loadKeepServers(list svcList) error {
                gatewayRoots[service.Uuid] = url
        }
 
-       if client, ok := this.Client.(*http.Client); ok {
-               if this.foundNonDiskSvc {
-                       this.setClientSettingsNonDisk(client)
-               } else {
-                       this.setClientSettingsDisk(client)
-               }
-       }
-
-       this.SetServiceRoots(localRoots, writableLocalRoots, gatewayRoots)
+       kc.setServiceRoots(localRoots, writableLocalRoots, gatewayRoots)
        return nil
 }
index 379d44c820aec0e0b88d84b3c52e5fd316480844..4065ce342e43dfaa5172ca48f4a3ec3282045296 100644 (file)
@@ -3,28 +3,15 @@ package keepclient
 import (
        "crypto/md5"
        "fmt"
-       "gopkg.in/check.v1"
        "net/http"
        "os"
-       "time"
+
+       "gopkg.in/check.v1"
 
        "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
        "git.curoverse.com/arvados.git/sdk/go/arvadostest"
 )
 
-func ExampleKeepClient_RefreshServices() {
-       arv, err := arvadosclient.MakeArvadosClient()
-       if err != nil {
-               panic(err)
-       }
-       kc, err := MakeKeepClient(arv)
-       if err != nil {
-               panic(err)
-       }
-       go kc.RefreshServices(5*time.Minute, 3*time.Second)
-       fmt.Printf("LocalRoots: %#v\n", kc.LocalRoots())
-}
-
 func (s *ServerRequiredSuite) TestOverrideDiscovery(c *check.C) {
        defer os.Setenv("ARVADOS_KEEP_SERVICES", "")
 
index b56cc7f724b3ba64ee26033f5ddd4b6f888f2422..029c6ee7f3a5834a8af149b64917aff2d5dc4bcb 100644 (file)
@@ -8,11 +8,13 @@ import (
        "fmt"
        "io"
        "io/ioutil"
+       "net"
        "net/http"
        "regexp"
        "strconv"
        "strings"
        "sync"
+       "time"
 
        "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
        "git.curoverse.com/arvados.git/sdk/go/streamer"
@@ -21,6 +23,18 @@ import (
 // A Keep "block" is 64MB.
 const BLOCKSIZE = 64 * 1024 * 1024
 
+var (
+       DefaultRequestTimeout      = 20 * time.Second
+       DefaultConnectTimeout      = 2 * time.Second
+       DefaultTLSHandshakeTimeout = 4 * time.Second
+       DefaultKeepAlive           = 180 * time.Second
+
+       DefaultProxyRequestTimeout      = 300 * time.Second
+       DefaultProxyConnectTimeout      = 30 * time.Second
+       DefaultProxyTLSHandshakeTimeout = 10 * time.Second
+       DefaultProxyKeepAlive           = 120 * time.Second
+)
+
 // Error interface with an error and boolean indicating whether the error is temporary
 type Error interface {
        error
@@ -74,11 +88,11 @@ type HTTPClient interface {
 type KeepClient struct {
        Arvados            *arvadosclient.ArvadosClient
        Want_replicas      int
-       localRoots         *map[string]string
-       writableLocalRoots *map[string]string
-       gatewayRoots       *map[string]string
+       localRoots         map[string]string
+       writableLocalRoots map[string]string
+       gatewayRoots       map[string]string
        lock               sync.RWMutex
-       Client             HTTPClient
+       HTTPClient         HTTPClient
        Retries            int
        BlockCache         *BlockCache
 
@@ -87,16 +101,21 @@ type KeepClient struct {
 
        // Any non-disk typed services found in the list of keepservers?
        foundNonDiskSvc bool
+
+       // Disable automatic discovery of keep services
+       disableDiscovery bool
 }
 
-// MakeKeepClient creates a new KeepClient by contacting the API server to discover Keep servers.
+// MakeKeepClient creates a new KeepClient, calls
+// DiscoverKeepServices(), and returns when the client is ready to
+// use.
 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
        kc := New(arv)
-       return kc, kc.DiscoverKeepServers()
+       return kc, kc.discoverServices()
 }
 
-// New func creates a new KeepClient struct.
-// This func does not discover keep servers. It is the caller's responsibility.
+// New creates a new KeepClient. Service discovery will occur on the
+// next read/write operation.
 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
        defaultReplicationLevel := 2
        value, err := arv.Discovery("defaultCollectionReplication")
@@ -106,15 +125,11 @@ func New(arv *arvadosclient.ArvadosClient) *KeepClient {
                        defaultReplicationLevel = int(v)
                }
        }
-
-       kc := &KeepClient{
+       return &KeepClient{
                Arvados:       arv,
                Want_replicas: defaultReplicationLevel,
-               Client: &http.Client{Transport: &http.Transport{
-                       TLSClientConfig: arvadosclient.MakeTLSConfig(arv.ApiInsecure)}},
-               Retries: 2,
+               Retries:       2,
        }
-       return kc
 }
 
 // Put a block given the block hash, a reader, and the number of bytes
@@ -204,7 +219,7 @@ func (kc *KeepClient) getOrHead(method string, locator string) (io.ReadCloser, i
                                continue
                        }
                        req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
-                       resp, err := kc.Client.Do(req)
+                       resp, err := kc.httpClient().Do(req)
                        if err != nil {
                                // Probably a network error, may be transient,
                                // can try again.
@@ -305,7 +320,7 @@ func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error
        }
 
        req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
-       resp, err := kc.Client.Do(req)
+       resp, err := kc.httpClient().Do(req)
        if err != nil {
                return nil, err
        }
@@ -336,55 +351,47 @@ func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error
 // LocalRoots() returns the map of local (i.e., disk and proxy) Keep
 // services: uuid -> baseURI.
 func (kc *KeepClient) LocalRoots() map[string]string {
+       kc.discoverServices()
        kc.lock.RLock()
        defer kc.lock.RUnlock()
-       return *kc.localRoots
+       return kc.localRoots
 }
 
 // GatewayRoots() returns the map of Keep remote gateway services:
 // uuid -> baseURI.
 func (kc *KeepClient) GatewayRoots() map[string]string {
+       kc.discoverServices()
        kc.lock.RLock()
        defer kc.lock.RUnlock()
-       return *kc.gatewayRoots
+       return kc.gatewayRoots
 }
 
 // WritableLocalRoots() returns the map of writable local Keep services:
 // uuid -> baseURI.
 func (kc *KeepClient) WritableLocalRoots() map[string]string {
+       kc.discoverServices()
        kc.lock.RLock()
        defer kc.lock.RUnlock()
-       return *kc.writableLocalRoots
+       return kc.writableLocalRoots
 }
 
-// SetServiceRoots updates the localRoots and gatewayRoots maps,
-// without risk of disrupting operations that are already in progress.
+// SetServiceRoots disables service discovery and updates the
+// localRoots and gatewayRoots maps, without disrupting operations
+// that are already in progress.
 //
-// The KeepClient makes its own copy of the supplied maps, so the
-// caller can reuse/modify them after SetServiceRoots returns, but
-// they should not be modified by any other goroutine while
-// SetServiceRoots is running.
-func (kc *KeepClient) SetServiceRoots(newLocals, newWritableLocals, newGateways map[string]string) {
-       locals := make(map[string]string)
-       for uuid, root := range newLocals {
-               locals[uuid] = root
-       }
-
-       writables := make(map[string]string)
-       for uuid, root := range newWritableLocals {
-               writables[uuid] = root
-       }
-
-       gateways := make(map[string]string)
-       for uuid, root := range newGateways {
-               gateways[uuid] = root
-       }
+// The supplied maps must not be modified after calling
+// SetServiceRoots.
+func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
+       kc.disableDiscovery = true
+       kc.setServiceRoots(locals, writables, gateways)
+}
 
+func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
        kc.lock.Lock()
        defer kc.lock.Unlock()
-       kc.localRoots = &locals
-       kc.writableLocalRoots = &writables
-       kc.gatewayRoots = &gateways
+       kc.localRoots = locals
+       kc.writableLocalRoots = writables
+       kc.gatewayRoots = gateways
 }
 
 // getSortedRoots returns a list of base URIs of Keep services, in the
@@ -423,6 +430,80 @@ func (kc *KeepClient) cache() *BlockCache {
        }
 }
 
+var (
+       // There are four global http.Client objects for the four
+       // possible permutations of TLS behavior (verify/skip-verify)
+       // and timeout settings (proxy/non-proxy).
+       defaultClient = map[bool]map[bool]HTTPClient{
+               // defaultClient[false] is used for verified TLS reqs
+               false: {},
+               // defaultClient[true] is used for unverified
+               // (insecure) TLS reqs
+               true: {},
+       }
+       defaultClientMtx sync.Mutex
+)
+
+// httpClient returns the HTTPClient field if it's not nil, otherwise
+// whichever of the four global http.Client objects is suitable for
+// the current environment (i.e., TLS verification on/off, keep
+// services are/aren't proxies).
+func (kc *KeepClient) httpClient() HTTPClient {
+       if kc.HTTPClient != nil {
+               return kc.HTTPClient
+       }
+       defaultClientMtx.Lock()
+       defer defaultClientMtx.Unlock()
+       if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
+               return c
+       }
+
+       var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
+       if kc.foundNonDiskSvc {
+               // Use longer timeouts when connecting to a proxy,
+               // because this usually means the intervening network
+               // is slower.
+               requestTimeout = DefaultProxyRequestTimeout
+               connectTimeout = DefaultProxyConnectTimeout
+               tlsTimeout = DefaultProxyTLSHandshakeTimeout
+               keepAlive = DefaultProxyKeepAlive
+       } else {
+               requestTimeout = DefaultRequestTimeout
+               connectTimeout = DefaultConnectTimeout
+               tlsTimeout = DefaultTLSHandshakeTimeout
+               keepAlive = DefaultKeepAlive
+       }
+
+       transport, ok := http.DefaultTransport.(*http.Transport)
+       if ok {
+               copy := *transport
+               transport = &copy
+       } else {
+               // Evidently the application has replaced
+               // http.DefaultTransport with a different type, so we
+               // need to build our own from scratch using the Go 1.8
+               // defaults.
+               transport = &http.Transport{
+                       MaxIdleConns:          100,
+                       IdleConnTimeout:       90 * time.Second,
+                       ExpectContinueTimeout: time.Second,
+               }
+       }
+       transport.DialContext = (&net.Dialer{
+               Timeout:   connectTimeout,
+               KeepAlive: keepAlive,
+               DualStack: true,
+       }).DialContext
+       transport.TLSHandshakeTimeout = tlsTimeout
+       transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
+       c := &http.Client{
+               Timeout:   requestTimeout,
+               Transport: transport,
+       }
+       defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
+       return c
+}
+
 type Locator struct {
        Hash  string
        Size  int      // -1 if data size is not known
index fcae4131fc028e563f5eac4ed1fa1748c5a7f5da..724d7ff3214db2315053d5e94f09e5e91adb070e 100644 (file)
@@ -35,6 +35,10 @@ type ServerRequiredSuite struct{}
 // Standalone tests
 type StandaloneSuite struct{}
 
+func (s *StandaloneSuite) SetUpTest(c *C) {
+       RefreshServiceDiscovery()
+}
+
 func pythonDir() string {
        cwd, _ := os.Getwd()
        return fmt.Sprintf("%s/../../python/tests", cwd)
@@ -50,6 +54,10 @@ func (s *ServerRequiredSuite) TearDownSuite(c *C) {
        arvadostest.StopAPI()
 }
 
+func (s *ServerRequiredSuite) SetUpTest(c *C) {
+       RefreshServiceDiscovery()
+}
+
 func (s *ServerRequiredSuite) TestMakeKeepClient(c *C) {
        arv, err := arvadosclient.MakeArvadosClient()
        c.Assert(err, Equals, nil)
@@ -1067,12 +1075,14 @@ func (s *StandaloneSuite) TestGetIndexWithNoPrefix(c *C) {
        defer ks.listener.Close()
 
        arv, err := arvadosclient.MakeArvadosClient()
-       kc, _ := MakeKeepClient(arv)
+       c.Assert(err, IsNil)
+       kc, err := MakeKeepClient(arv)
+       c.Assert(err, IsNil)
        arv.ApiToken = "abc123"
        kc.SetServiceRoots(map[string]string{"x": ks.url}, nil, nil)
 
        r, err := kc.GetIndex("x", "")
-       c.Check(err, Equals, nil)
+       c.Check(err, IsNil)
 
        content, err2 := ioutil.ReadAll(r)
        c.Check(err2, Equals, nil)
@@ -1098,7 +1108,7 @@ func (s *StandaloneSuite) TestGetIndexWithPrefix(c *C) {
        kc.SetServiceRoots(map[string]string{"x": ks.url}, nil, nil)
 
        r, err := kc.GetIndex("x", hash[0:3])
-       c.Check(err, Equals, nil)
+       c.Assert(err, Equals, nil)
 
        content, err2 := ioutil.ReadAll(r)
        c.Check(err2, Equals, nil)
@@ -1237,6 +1247,7 @@ func (s *ServerRequiredSuite) TestMakeKeepClientWithNonDiskTypeService(c *C) {
                &blobKeepService)
        c.Assert(err, Equals, nil)
        defer func() { arv.Delete("keep_services", blobKeepService["uuid"].(string), nil, nil) }()
+       RefreshServiceDiscovery()
 
        // Make a keepclient and ensure that the testblobstore is included
        kc, err := MakeKeepClient(arv)
@@ -1265,5 +1276,5 @@ func (s *ServerRequiredSuite) TestMakeKeepClientWithNonDiskTypeService(c *C) {
 
        c.Assert(kc.replicasPerService, Equals, 0)
        c.Assert(kc.foundNonDiskSvc, Equals, true)
-       c.Assert(kc.Client.(*http.Client).Timeout, Equals, 300*time.Second)
+       c.Assert(kc.httpClient().(*http.Client).Timeout, Equals, 300*time.Second)
 }
index 33ba8720bc86363dab027c6481535bb9f74d26b4..8545cb80b855d9e53606042bfc940df7388e51eb 100644 (file)
@@ -8,13 +8,11 @@ import (
        "io/ioutil"
        "log"
        "math/rand"
-       "net"
        "net/http"
        "os"
-       "regexp"
        "strings"
-       "time"
 
+       "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
        "git.curoverse.com/arvados.git/sdk/go/streamer"
 )
 
@@ -24,8 +22,7 @@ import (
 var DebugPrintf = func(string, ...interface{}) {}
 
 func init() {
-       var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
-       if matchTrue.MatchString(os.Getenv("ARVADOS_DEBUG")) {
+       if arvadosclient.StringBool(os.Getenv("ARVADOS_DEBUG")) {
                DebugPrintf = log.Printf
        }
 }
@@ -44,50 +41,6 @@ func Md5String(s string) string {
        return fmt.Sprintf("%x", md5.Sum([]byte(s)))
 }
 
-// Set timeouts applicable when connecting to non-disk services
-// (assumed to be over the Internet).
-func (*KeepClient) setClientSettingsNonDisk(client *http.Client) {
-       // Maximum time to wait for a complete response
-       client.Timeout = 300 * time.Second
-
-       // TCP and TLS connection settings
-       client.Transport = &http.Transport{
-               Dial: (&net.Dialer{
-                       // The maximum time to wait to set up
-                       // the initial TCP connection.
-                       Timeout: 30 * time.Second,
-
-                       // The TCP keep alive heartbeat
-                       // interval.
-                       KeepAlive: 120 * time.Second,
-               }).Dial,
-
-               TLSHandshakeTimeout: 10 * time.Second,
-       }
-}
-
-// Set timeouts applicable when connecting to keepstore services directly
-// (assumed to be on the local network).
-func (*KeepClient) setClientSettingsDisk(client *http.Client) {
-       // Maximum time to wait for a complete response
-       client.Timeout = 20 * time.Second
-
-       // TCP and TLS connection timeouts
-       client.Transport = &http.Transport{
-               Dial: (&net.Dialer{
-                       // The maximum time to wait to set up
-                       // the initial TCP connection.
-                       Timeout: 2 * time.Second,
-
-                       // The TCP keep alive heartbeat
-                       // interval.
-                       KeepAlive: 180 * time.Second,
-               }).Dial,
-
-               TLSHandshakeTimeout: 4 * time.Second,
-       }
-}
-
 type svcList struct {
        Items []keepService `json:"items"`
 }
@@ -115,8 +68,8 @@ func (this *KeepClient) uploadToKeepServer(host string, hash string, body io.Rea
 
        req.ContentLength = expectedLength
        if expectedLength > 0 {
-               // http.Client.Do will close the body ReadCloser when it is
-               // done with it.
+               // Do() will close the body ReadCloser when it is done
+               // with it.
                req.Body = body
        } else {
                // "For client requests, a value of 0 means unknown if Body is
@@ -131,7 +84,7 @@ func (this *KeepClient) uploadToKeepServer(host string, hash string, body io.Rea
        req.Header.Add(X_Keep_Desired_Replicas, fmt.Sprint(this.Want_replicas))
 
        var resp *http.Response
-       if resp, err = this.Client.Do(req); err != nil {
+       if resp, err = this.httpClient().Do(req); err != nil {
                DebugPrintf("DEBUG: [%08x] Upload failed %v error: %v", requestID, url, err.Error())
                upload_status <- uploadStatus{err, url, 0, 0, ""}
                return
index d2a512bde75f68c790360813b47872b748481be1..e59c5f25789e4e83a9be0a215a784df6742d8eb2 100644 (file)
@@ -2,6 +2,7 @@ class Arvados::V1::KeepServicesController < ApplicationController
 
   skip_before_filter :find_object_by_uuid, only: :accessible
   skip_before_filter :render_404_if_no_object, only: :accessible
+  skip_before_filter :require_auth_scope, only: :accessible
 
   def find_objects_for_index
     # all users can list all keep services
index 1375d4c9ce71549bdb43988cf4808eb70a908bf2..706f73ffda6157812e9cb687c9340f344464c663 100644 (file)
@@ -20,9 +20,9 @@ class Arvados::V1::KeepServicesControllerTest < ActionController::TestCase
     assert_equal true, assigns(:objects).any?
   end
 
-  [:admin, :active, :inactive, :anonymous].each do |u|
-    test "accessible to #{u} user" do
-      authorize_with u
+  [:admin, :active, :inactive, :anonymous, nil].each do |u|
+    test "accessible to #{u.inspect} user" do
+      authorize_with(u) if u
       get :accessible
       assert_response :success
       assert_not_empty json_response['items']
index 148b783788e1df83afd75fdb2ed2615d60e76b84..cca1d85c824290eb304531cdee9cc1b27ba5f326 100644 (file)
@@ -3,7 +3,6 @@ package main
 import (
        "bytes"
        "log"
-       "net/http"
        "os"
        "strings"
        "testing"
@@ -35,11 +34,9 @@ func (s *integrationSuite) SetUpSuite(c *check.C) {
        arv, err := arvadosclient.MakeArvadosClient()
        arv.ApiToken = arvadostest.DataManagerToken
        c.Assert(err, check.IsNil)
-       s.keepClient = &keepclient.KeepClient{
-               Arvados: arv,
-               Client:  &http.Client{},
-       }
-       c.Assert(s.keepClient.DiscoverKeepServers(), check.IsNil)
+
+       s.keepClient, err = keepclient.MakeKeepClient(arv)
+       c.Assert(err, check.IsNil)
        s.putReplicas(c, "foo", 4)
        s.putReplicas(c, "bar", 1)
 }
index 008876488b97aa675e30541754ec4e8c814ffe8f..b7e39c6041d256188350d464da86ee39fb29bdeb 100644 (file)
@@ -64,6 +64,7 @@ func parseCollectionIDFromURL(s string) string {
 
 func (h *handler) setup() {
        h.clientPool = arvadosclient.MakeClientPool()
+       keepclient.RefreshServiceDiscoveryOnSIGHUP()
 }
 
 // ServeHTTP implements http.Handler.
@@ -335,12 +336,6 @@ func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
                statusCode, statusText = http.StatusInternalServerError, err.Error()
                return
        }
-       if client, ok := kc.Client.(*http.Client); ok && client.Transport != nil {
-               // Workaround for https://dev.arvados.org/issues/9005
-               if t, ok := client.Transport.(*http.Transport); ok {
-                       t.DisableKeepAlives = true
-               }
-       }
        rdr, err := kc.CollectionFileReader(collection, filename)
        if os.IsNotExist(err) {
                statusCode = http.StatusNotFound
index 65f7a42cd9d737399c278d71b2b47071ad655c6c..7dfd01ad41e7fd96f74b763d6129cc1792448538 100644 (file)
@@ -104,6 +104,7 @@ func main() {
        if err != nil {
                log.Fatalf("Error setting up keep client %s", err.Error())
        }
+       keepclient.RefreshServiceDiscoveryOnSIGHUP()
 
        if cfg.PIDFile != "" {
                f, err := os.Create(cfg.PIDFile)
@@ -133,8 +134,6 @@ func main() {
        if cfg.DefaultReplicas > 0 {
                kc.Want_replicas = cfg.DefaultReplicas
        }
-       kc.Client.(*http.Client).Timeout = time.Duration(cfg.Timeout)
-       go kc.RefreshServices(5*time.Minute, 3*time.Second)
 
        listener, err = net.Listen("tcp", cfg.Listen)
        if err != nil {
@@ -157,7 +156,7 @@ func main() {
        signal.Notify(term, syscall.SIGINT)
 
        // Start serving requests.
-       router = MakeRESTRouter(!cfg.DisableGet, !cfg.DisablePut, kc)
+       router = MakeRESTRouter(!cfg.DisableGet, !cfg.DisablePut, kc, time.Duration(cfg.Timeout))
        http.Serve(listener, router)
 
        log.Println("shutting down")
@@ -241,15 +240,29 @@ type proxyHandler struct {
        http.Handler
        *keepclient.KeepClient
        *ApiTokenCache
+       timeout   time.Duration
+       transport *http.Transport
 }
 
 // MakeRESTRouter returns an http.Handler that passes GET and PUT
 // requests to the appropriate handlers.
-func MakeRESTRouter(enable_get bool, enable_put bool, kc *keepclient.KeepClient) http.Handler {
+func MakeRESTRouter(enable_get bool, enable_put bool, kc *keepclient.KeepClient, timeout time.Duration) http.Handler {
        rest := mux.NewRouter()
+
+       transport := *(http.DefaultTransport.(*http.Transport))
+       transport.DialContext = (&net.Dialer{
+               Timeout:   keepclient.DefaultConnectTimeout,
+               KeepAlive: keepclient.DefaultKeepAlive,
+               DualStack: true,
+       }).DialContext
+       transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
+       transport.TLSHandshakeTimeout = keepclient.DefaultTLSHandshakeTimeout
+
        h := &proxyHandler{
                Handler:    rest,
                KeepClient: kc,
+               timeout:    timeout,
+               transport:  &transport,
                ApiTokenCache: &ApiTokenCache{
                        tokens:     make(map[string]int64),
                        expireTime: 300,
@@ -335,12 +348,11 @@ func (h *proxyHandler) Get(resp http.ResponseWriter, req *http.Request) {
                }
        }()
 
-       kc := *h.KeepClient
-       kc.Client = &proxyClient{client: kc.Client, proto: req.Proto}
+       kc := h.makeKeepClient(req)
 
        var pass bool
        var tok string
-       if pass, tok = CheckAuthorizationHeader(&kc, h.ApiTokenCache, req); !pass {
+       if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
                status, err = http.StatusForbidden, BadAuthorizationHeader
                return
        }
@@ -407,8 +419,7 @@ func (h *proxyHandler) Put(resp http.ResponseWriter, req *http.Request) {
        SetCorsHeaders(resp)
        resp.Header().Set("Via", "HTTP/1.1 "+viaAlias)
 
-       kc := *h.KeepClient
-       kc.Client = &proxyClient{client: kc.Client, proto: req.Proto}
+       kc := h.makeKeepClient(req)
 
        var err error
        var expectLength int64
@@ -446,7 +457,7 @@ func (h *proxyHandler) Put(resp http.ResponseWriter, req *http.Request) {
 
        var pass bool
        var tok string
-       if pass, tok = CheckAuthorizationHeader(&kc, h.ApiTokenCache, req); !pass {
+       if pass, tok = CheckAuthorizationHeader(kc, h.ApiTokenCache, req); !pass {
                err = BadAuthorizationHeader
                status = http.StatusForbidden
                return
@@ -527,9 +538,8 @@ func (h *proxyHandler) Index(resp http.ResponseWriter, req *http.Request) {
                }
        }()
 
-       kc := *h.KeepClient
-
-       ok, token := CheckAuthorizationHeader(&kc, h.ApiTokenCache, req)
+       kc := h.makeKeepClient(req)
+       ok, token := CheckAuthorizationHeader(kc, h.ApiTokenCache, req)
        if !ok {
                status, err = http.StatusForbidden, BadAuthorizationHeader
                return
@@ -566,3 +576,15 @@ func (h *proxyHandler) Index(resp http.ResponseWriter, req *http.Request) {
        status = http.StatusOK
        resp.Write([]byte("\n"))
 }
+
+func (h *proxyHandler) makeKeepClient(req *http.Request) *keepclient.KeepClient {
+       kc := *h.KeepClient
+       kc.HTTPClient = &proxyClient{
+               client: &http.Client{
+                       Timeout:   h.timeout,
+                       Transport: h.transport,
+               },
+               proto: req.Proto,
+       }
+       return &kc
+}
index 4e856262dd1827395df6c54c99a5c68cfb18432a..2c672f06339faf3cf01c186532894c9ee04096ea 100644 (file)
@@ -185,7 +185,7 @@ func (s *ServerRequiredSuite) TestPutWrongContentLength(c *C) {
        // fixes the invalid Content-Length header. In order to test
        // our server behavior, we have to call the handler directly
        // using an httptest.ResponseRecorder.
-       rtr := MakeRESTRouter(true, true, kc)
+       rtr := MakeRESTRouter(true, true, kc, 10*time.Second)
 
        type testcase struct {
                sendLength   string
index 9033de811775f776499b61f5347545dd42775cc0..d53d35da6002932e820979d03300e406d81b676f 100644 (file)
@@ -159,7 +159,6 @@ func main() {
        keepClient := &keepclient.KeepClient{
                Arvados:       &arvadosclient.ArvadosClient{},
                Want_replicas: 1,
-               Client:        &http.Client{},
        }
 
        // Initialize the pullq and worker
index 8c7a1e222ddc8905041161cee67d605334285a65..34c2f61a37a01097ec1ce257f49f5ccb9c33e246 100644 (file)
@@ -5,7 +5,6 @@ import (
        "errors"
        "io"
        "io/ioutil"
-       "net/http"
        "os"
        "strings"
        "testing"
@@ -30,25 +29,23 @@ func SetupPullWorkerIntegrationTest(t *testing.T, testData PullWorkIntegrationTe
        // start api and keep servers
        arvadostest.StartAPI()
        arvadostest.StartKeep(2, false)
+       keepclient.RefreshServiceDiscovery()
 
        // make arvadosclient
        arv, err := arvadosclient.MakeArvadosClient()
        if err != nil {
-               t.Error("Error creating arv")
+               t.Fatalf("Error creating arv: %s", err)
        }
 
        // keep client
-       keepClient = &keepclient.KeepClient{
-               Arvados:       arv,
-               Want_replicas: 1,
-               Client:        &http.Client{},
+       keepClient, err = keepclient.MakeKeepClient(arv)
+       if err != nil {
+               t.Fatalf("error creating KeepClient: %s", err)
        }
+       keepClient.Want_replicas = 1
 
        // discover keep services
        var servers []string
-       if err := keepClient.DiscoverKeepServers(); err != nil {
-               t.Error("Error discovering keep services")
-       }
        for _, host := range keepClient.LocalRoots() {
                servers = append(servers, host)
        }
index 6cf11a728075c60990c1b049c0fb916cea5cd5d5..e22e4b5cfe56e2d127d334ef593d6b5067cc3978 100644 (file)
@@ -5,15 +5,15 @@ import (
        "errors"
        "flag"
        "fmt"
-       "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
-       "git.curoverse.com/arvados.git/sdk/go/keepclient"
        "io/ioutil"
        "log"
        "net/http"
        "os"
-       "regexp"
        "strings"
        "time"
+
+       "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
+       "git.curoverse.com/arvados.git/sdk/go/keepclient"
 )
 
 func main() {
@@ -99,8 +99,6 @@ func loadConfig(configFile string) (config apiConfig, blobSigningKey string, err
        return
 }
 
-var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
-
 // Read config from file
 func readConfigFromFile(filename string) (config apiConfig, blobSigningKey string, err error) {
        if !strings.Contains(filename, "/") {
@@ -130,9 +128,9 @@ func readConfigFromFile(filename string) (config apiConfig, blobSigningKey strin
                        case "ARVADOS_API_HOST":
                                config.APIHost = value
                        case "ARVADOS_API_HOST_INSECURE":
-                               config.APIHostInsecure = matchTrue.MatchString(value)
+                               config.APIHostInsecure = arvadosclient.StringBool(value)
                        case "ARVADOS_EXTERNAL_CLIENT":
-                               config.ExternalClient = matchTrue.MatchString(value)
+                               config.ExternalClient = arvadosclient.StringBool(value)
                        case "ARVADOS_BLOB_SIGNING_KEY":
                                blobSigningKey = value
                        }
@@ -153,7 +151,7 @@ func setupKeepClient(config apiConfig, keepServicesJSON string, blobSignatureTTL
                External: config.ExternalClient,
        }
 
-       // if keepServicesJSON is provided, use it to load services; else, use DiscoverKeepServers
+       // If keepServicesJSON is provided, use it instead of service discovery
        if keepServicesJSON == "" {
                kc, err = keepclient.MakeKeepClient(&arv)
                if err != nil {
index e49fe68616626275f00ba5bce21877dd969207dd..34d4f022bf8d7d4570e2465fd7d811dd3e1a2aa3 100644 (file)
@@ -12,6 +12,7 @@ import (
        "testing"
        "time"
 
+       "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
        "git.curoverse.com/arvados.git/sdk/go/arvadostest"
        "git.curoverse.com/arvados.git/sdk/go/keepclient"
 
@@ -64,6 +65,7 @@ func (s *DoMainTestSuite) SetUpSuite(c *C) {
 func (s *DoMainTestSuite) SetUpTest(c *C) {
        logOutput := io.MultiWriter(&logBuffer)
        log.SetOutput(logOutput)
+       keepclient.RefreshServiceDiscovery()
 }
 
 func (s *DoMainTestSuite) TearDownTest(c *C) {
@@ -79,7 +81,7 @@ func setupKeepBlockCheckWithTTL(c *C, enforcePermissions bool, keepServicesJSON
        var config apiConfig
        config.APIHost = os.Getenv("ARVADOS_API_HOST")
        config.APIToken = arvadostest.DataManagerToken
-       config.APIHostInsecure = matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
+       config.APIHostInsecure = arvadosclient.StringBool(os.Getenv("ARVADOS_API_HOST_INSECURE"))
 
        // Start Keep servers
        arvadostest.StartKeep(2, enforcePermissions)
@@ -89,6 +91,8 @@ func setupKeepBlockCheckWithTTL(c *C, enforcePermissions bool, keepServicesJSON
        kc, ttl, err = setupKeepClient(config, keepServicesJSON, ttl)
        c.Assert(ttl, Equals, blobSignatureTTL)
        c.Check(err, IsNil)
+
+       keepclient.RefreshServiceDiscovery()
 }
 
 // Setup test data
@@ -144,9 +148,8 @@ func setupBlockHashFile(c *C, name string, blocks []string) string {
 
 func checkErrorLog(c *C, blocks []string, prefix, suffix string) {
        for _, hash := range blocks {
-               expected := prefix + `.*` + hash + `.*` + suffix
-               match, _ := regexp.MatchString(expected, logBuffer.String())
-               c.Assert(match, Equals, true)
+               expected := `(?ms).*` + prefix + `.*` + hash + `.*` + suffix + `.*`
+               c.Check(logBuffer.String(), Matches, expected)
        }
 }
 
@@ -288,7 +291,7 @@ func (s *ServerRequiredSuite) TestLoadConfig(c *C) {
 
        c.Assert(config.APIHost, Equals, os.Getenv("ARVADOS_API_HOST"))
        c.Assert(config.APIToken, Equals, arvadostest.DataManagerToken)
-       c.Assert(config.APIHostInsecure, Equals, matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE")))
+       c.Assert(config.APIHostInsecure, Equals, arvadosclient.StringBool(os.Getenv("ARVADOS_API_HOST_INSECURE")))
        c.Assert(config.ExternalClient, Equals, false)
        c.Assert(blobSigningKey, Equals, "abcdefg")
 }
index 706664ce28a3756047afcc2f87264b01857d5244..a4684739e72ad36e33920490671b4d2c222cd799 100644 (file)
@@ -53,7 +53,13 @@ func main() {
                log.Fatal(err)
        }
        kc.Want_replicas = *Replicas
-       kc.Client.(*http.Client).Timeout = 10 * time.Minute
+
+       transport := *(http.DefaultTransport.(*http.Transport))
+       transport.TLSClientConfig = arvadosclient.MakeTLSConfig(arv.ApiInsecure)
+       kc.HTTPClient = &http.Client{
+               Timeout:   10 * time.Minute,
+               Transport: &transport,
+       }
 
        overrideServices(kc)
 
index c6e7665caa2a312c327b8a603159a7da07941450..b1513a02a7e30f3211b39bbf0a4335c8dd9cf8d9 100644 (file)
@@ -6,15 +6,15 @@ import (
        "errors"
        "flag"
        "fmt"
-       "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
-       "git.curoverse.com/arvados.git/sdk/go/keepclient"
        "io/ioutil"
        "log"
        "net/http"
        "os"
-       "regexp"
        "strings"
        "time"
+
+       "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
+       "git.curoverse.com/arvados.git/sdk/go/keepclient"
 )
 
 func main() {
@@ -119,8 +119,6 @@ func loadConfig(configFile string) (config apiConfig, blobSigningKey string, err
        return
 }
 
-var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
-
 // Read config from file
 func readConfigFromFile(filename string) (config apiConfig, blobSigningKey string, err error) {
        if !strings.Contains(filename, "/") {
@@ -149,9 +147,9 @@ func readConfigFromFile(filename string) (config apiConfig, blobSigningKey strin
                case "ARVADOS_API_HOST":
                        config.APIHost = value
                case "ARVADOS_API_HOST_INSECURE":
-                       config.APIHostInsecure = matchTrue.MatchString(value)
+                       config.APIHostInsecure = arvadosclient.StringBool(value)
                case "ARVADOS_EXTERNAL_CLIENT":
-                       config.ExternalClient = matchTrue.MatchString(value)
+                       config.ExternalClient = arvadosclient.StringBool(value)
                case "ARVADOS_BLOB_SIGNING_KEY":
                        blobSigningKey = value
                }
@@ -170,7 +168,7 @@ func setupKeepClient(config apiConfig, keepServicesJSON string, isDst bool, repl
                External: config.ExternalClient,
        }
 
-       // if keepServicesJSON is provided, use it to load services; else, use DiscoverKeepServers
+       // If keepServicesJSON is provided, use it instead of service discovery
        if keepServicesJSON == "" {
                kc, err = keepclient.MakeKeepClient(&arv)
                if err != nil {
index 09609eb7498bb8dc28d95bc41892f4cca9ec8563..fec1f354c957e1ca5f106f666c632af3728d3b82 100644 (file)
@@ -4,35 +4,42 @@ import (
        "crypto/md5"
        "fmt"
        "io/ioutil"
-       "log"
        "os"
        "strings"
        "testing"
        "time"
 
+       "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
        "git.curoverse.com/arvados.git/sdk/go/arvadostest"
        "git.curoverse.com/arvados.git/sdk/go/keepclient"
 
        . "gopkg.in/check.v1"
 )
 
+var kcSrc, kcDst *keepclient.KeepClient
+var srcKeepServicesJSON, dstKeepServicesJSON, blobSigningKey string
+var blobSignatureTTL = time.Duration(2*7*24) * time.Hour
+
+func resetGlobals() {
+       blobSigningKey = ""
+       srcKeepServicesJSON = ""
+       dstKeepServicesJSON = ""
+       kcSrc = nil
+       kcDst = nil
+}
+
 // Gocheck boilerplate
 func Test(t *testing.T) {
        TestingT(t)
 }
 
-// Gocheck boilerplate
 var _ = Suite(&ServerRequiredSuite{})
 var _ = Suite(&ServerNotRequiredSuite{})
 var _ = Suite(&DoMainTestSuite{})
 
-// Tests that require the Keep server running
 type ServerRequiredSuite struct{}
-type ServerNotRequiredSuite struct{}
-type DoMainTestSuite struct{}
 
 func (s *ServerRequiredSuite) SetUpSuite(c *C) {
-       // Start API server
        arvadostest.StartAPI()
 }
 
@@ -41,36 +48,32 @@ func (s *ServerRequiredSuite) TearDownSuite(c *C) {
        arvadostest.ResetEnv()
 }
 
-var initialArgs []string
-
-func (s *DoMainTestSuite) SetUpSuite(c *C) {
-       initialArgs = os.Args
-}
-
-var kcSrc, kcDst *keepclient.KeepClient
-var srcKeepServicesJSON, dstKeepServicesJSON, blobSigningKey string
-var blobSignatureTTL = time.Duration(2*7*24) * time.Hour
-
 func (s *ServerRequiredSuite) SetUpTest(c *C) {
-       // reset all variables between tests
-       blobSigningKey = ""
-       srcKeepServicesJSON = ""
-       dstKeepServicesJSON = ""
-       kcSrc = &keepclient.KeepClient{}
-       kcDst = &keepclient.KeepClient{}
+       resetGlobals()
 }
 
 func (s *ServerRequiredSuite) TearDownTest(c *C) {
        arvadostest.StopKeep(3)
 }
 
+func (s *ServerNotRequiredSuite) SetUpTest(c *C) {
+       resetGlobals()
+}
+
+type ServerNotRequiredSuite struct{}
+
+type DoMainTestSuite struct {
+       initialArgs []string
+}
+
 func (s *DoMainTestSuite) SetUpTest(c *C) {
-       args := []string{"keep-rsync"}
-       os.Args = args
+       s.initialArgs = os.Args
+       os.Args = []string{"keep-rsync"}
+       resetGlobals()
 }
 
 func (s *DoMainTestSuite) TearDownTest(c *C) {
-       os.Args = initialArgs
+       os.Args = s.initialArgs
 }
 
 var testKeepServicesJSON = "{ \"kind\":\"arvados#keepServiceList\", \"etag\":\"\", \"self_link\":\"\", \"offset\":null, \"limit\":null, \"items\":[ { \"href\":\"/keep_services/zzzzz-bi6l4-123456789012340\", \"kind\":\"arvados#keepService\", \"etag\":\"641234567890enhj7hzx432e5\", \"uuid\":\"zzzzz-bi6l4-123456789012340\", \"owner_uuid\":\"zzzzz-tpzed-123456789012345\", \"service_host\":\"keep0.zzzzz.arvadosapi.com\", \"service_port\":25107, \"service_ssl_flag\":false, \"service_type\":\"disk\", \"read_only\":false }, { \"href\":\"/keep_services/zzzzz-bi6l4-123456789012341\", \"kind\":\"arvados#keepService\", \"etag\":\"641234567890enhj7hzx432e5\", \"uuid\":\"zzzzz-bi6l4-123456789012341\", \"owner_uuid\":\"zzzzz-tpzed-123456789012345\", \"service_host\":\"keep0.zzzzz.arvadosapi.com\", \"service_port\":25108, \"service_ssl_flag\":false, \"service_type\":\"disk\", \"read_only\":false } ], \"items_available\":2 }"
@@ -83,13 +86,13 @@ func setupRsync(c *C, enforcePermissions bool, replications int) {
        var srcConfig apiConfig
        srcConfig.APIHost = os.Getenv("ARVADOS_API_HOST")
        srcConfig.APIToken = arvadostest.DataManagerToken
-       srcConfig.APIHostInsecure = matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
+       srcConfig.APIHostInsecure = arvadosclient.StringBool(os.Getenv("ARVADOS_API_HOST_INSECURE"))
 
        // dstConfig
        var dstConfig apiConfig
        dstConfig.APIHost = os.Getenv("ARVADOS_API_HOST")
        dstConfig.APIToken = arvadostest.DataManagerToken
-       dstConfig.APIHostInsecure = matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
+       dstConfig.APIHostInsecure = arvadosclient.StringBool(os.Getenv("ARVADOS_API_HOST_INSECURE"))
 
        if enforcePermissions {
                blobSigningKey = arvadostest.BlobSigningKey
@@ -97,45 +100,30 @@ func setupRsync(c *C, enforcePermissions bool, replications int) {
 
        // Start Keep servers
        arvadostest.StartKeep(3, enforcePermissions)
+       keepclient.RefreshServiceDiscovery()
 
        // setup keepclients
        var err error
        kcSrc, _, err = setupKeepClient(srcConfig, srcKeepServicesJSON, false, 0, blobSignatureTTL)
-       c.Check(err, IsNil)
+       c.Assert(err, IsNil)
 
        kcDst, _, err = setupKeepClient(dstConfig, dstKeepServicesJSON, true, replications, 0)
-       c.Check(err, IsNil)
+       c.Assert(err, IsNil)
 
-       for uuid := range kcSrc.LocalRoots() {
+       srcRoots := map[string]string{}
+       dstRoots := map[string]string{}
+       for uuid, root := range kcSrc.LocalRoots() {
                if strings.HasSuffix(uuid, "02") {
-                       delete(kcSrc.LocalRoots(), uuid)
+                       dstRoots[uuid] = root
+               } else {
+                       srcRoots[uuid] = root
                }
        }
-       for uuid := range kcSrc.GatewayRoots() {
-               if strings.HasSuffix(uuid, "02") {
-                       delete(kcSrc.GatewayRoots(), uuid)
-               }
+       if srcKeepServicesJSON == "" {
+               kcSrc.SetServiceRoots(srcRoots, srcRoots, srcRoots)
        }
-       for uuid := range kcSrc.WritableLocalRoots() {
-               if strings.HasSuffix(uuid, "02") {
-                       delete(kcSrc.WritableLocalRoots(), uuid)
-               }
-       }
-
-       for uuid := range kcDst.LocalRoots() {
-               if strings.HasSuffix(uuid, "00") || strings.HasSuffix(uuid, "01") {
-                       delete(kcDst.LocalRoots(), uuid)
-               }
-       }
-       for uuid := range kcDst.GatewayRoots() {
-               if strings.HasSuffix(uuid, "00") || strings.HasSuffix(uuid, "01") {
-                       delete(kcDst.GatewayRoots(), uuid)
-               }
-       }
-       for uuid := range kcDst.WritableLocalRoots() {
-               if strings.HasSuffix(uuid, "00") || strings.HasSuffix(uuid, "01") {
-                       delete(kcDst.WritableLocalRoots(), uuid)
-               }
+       if dstKeepServicesJSON == "" {
+               kcDst.SetServiceRoots(dstRoots, dstRoots, dstRoots)
        }
 
        if replications == 0 {
@@ -188,22 +176,8 @@ func (s *ServerRequiredSuite) TestRsyncInitializeWithKeepServicesJSON(c *C) {
 
        localRoots := kcSrc.LocalRoots()
        c.Check(localRoots, NotNil)
-
-       foundIt := false
-       for k := range localRoots {
-               if k == "zzzzz-bi6l4-123456789012340" {
-                       foundIt = true
-               }
-       }
-       c.Check(foundIt, Equals, true)
-
-       foundIt = false
-       for k := range localRoots {
-               if k == "zzzzz-bi6l4-123456789012341" {
-                       foundIt = true
-               }
-       }
-       c.Check(foundIt, Equals, true)
+       c.Check(localRoots["zzzzz-bi6l4-123456789012340"], Not(Equals), "")
+       c.Check(localRoots["zzzzz-bi6l4-123456789012341"], Not(Equals), "")
 }
 
 // Test keep-rsync initialization with default replications count
@@ -329,8 +303,8 @@ func (s *ServerRequiredSuite) TestErrorDuringRsync_FakeSrcKeepservers(c *C) {
        setupRsync(c, false, 1)
 
        err := performKeepRsync(kcSrc, kcDst, blobSignatureTTL, "", "")
-       log.Printf("Err = %v", err)
-       c.Check(strings.Contains(err.Error(), "no such host"), Equals, true)
+       c.Assert(err, NotNil)
+       c.Check(err.Error(), Matches, ".*no such host.*")
 }
 
 // Setup rsync using dstKeepServicesJSON with fake keepservers.
@@ -341,8 +315,8 @@ func (s *ServerRequiredSuite) TestErrorDuringRsync_FakeDstKeepservers(c *C) {
        setupRsync(c, false, 1)
 
        err := performKeepRsync(kcSrc, kcDst, blobSignatureTTL, "", "")
-       log.Printf("Err = %v", err)
-       c.Check(strings.Contains(err.Error(), "no such host"), Equals, true)
+       c.Assert(err, NotNil)
+       c.Check(err.Error(), Matches, ".*no such host.*")
 }
 
 // Test rsync with signature error during Get from src.
@@ -356,7 +330,8 @@ func (s *ServerRequiredSuite) TestErrorDuringRsync_ErrorGettingBlockFromSrc(c *C
        blobSigningKey = "thisisfakeblobsigningkey"
 
        err := performKeepRsync(kcSrc, kcDst, blobSignatureTTL, blobSigningKey, "")
-       c.Check(strings.Contains(err.Error(), "HTTP 403 \"Forbidden\""), Equals, true)
+       c.Assert(err, NotNil)
+       c.Check(err.Error(), Matches, ".*HTTP 403 \"Forbidden\".*")
 }
 
 // Test rsync with error during Put to src.
@@ -370,7 +345,8 @@ func (s *ServerRequiredSuite) TestErrorDuringRsync_ErrorPuttingBlockInDst(c *C)
        kcDst.Want_replicas = 2
 
        err := performKeepRsync(kcSrc, kcDst, blobSignatureTTL, blobSigningKey, "")
-       c.Check(strings.Contains(err.Error(), "Could not write sufficient replicas"), Equals, true)
+       c.Assert(err, NotNil)
+       c.Check(err.Error(), Matches, ".*Could not write sufficient replicas.*")
 }
 
 // Test loadConfig func
@@ -391,7 +367,7 @@ func (s *ServerNotRequiredSuite) TestLoadConfig(c *C) {
 
        c.Assert(srcConfig.APIHost, Equals, os.Getenv("ARVADOS_API_HOST"))
        c.Assert(srcConfig.APIToken, Equals, arvadostest.DataManagerToken)
-       c.Assert(srcConfig.APIHostInsecure, Equals, matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE")))
+       c.Assert(srcConfig.APIHostInsecure, Equals, arvadosclient.StringBool(os.Getenv("ARVADOS_API_HOST_INSECURE")))
        c.Assert(srcConfig.ExternalClient, Equals, false)
 
        dstConfig, _, err := loadConfig(dstConfigFile)
@@ -399,7 +375,7 @@ func (s *ServerNotRequiredSuite) TestLoadConfig(c *C) {
 
        c.Assert(dstConfig.APIHost, Equals, os.Getenv("ARVADOS_API_HOST"))
        c.Assert(dstConfig.APIToken, Equals, arvadostest.DataManagerToken)
-       c.Assert(dstConfig.APIHostInsecure, Equals, matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE")))
+       c.Assert(dstConfig.APIHostInsecure, Equals, arvadosclient.StringBool(os.Getenv("ARVADOS_API_HOST_INSECURE")))
        c.Assert(dstConfig.ExternalClient, Equals, false)
 
        c.Assert(srcBlobSigningKey, Equals, "abcdefg")
@@ -414,15 +390,15 @@ func (s *ServerNotRequiredSuite) TestLoadConfig_MissingSrcConfig(c *C) {
 // Test loadConfig func - error reading config
 func (s *ServerNotRequiredSuite) TestLoadConfig_ErrorLoadingSrcConfig(c *C) {
        _, _, err := loadConfig("no-such-config-file")
-       c.Assert(strings.Contains(err.Error(), "no such file or directory"), Equals, true)
+       c.Assert(err, NotNil)
+       c.Check(err.Error(), Matches, ".*no such file or directory.*")
 }
 
 func (s *ServerNotRequiredSuite) TestSetupKeepClient_NoBlobSignatureTTL(c *C) {
        var srcConfig apiConfig
        srcConfig.APIHost = os.Getenv("ARVADOS_API_HOST")
        srcConfig.APIToken = arvadostest.DataManagerToken
-       srcConfig.APIHostInsecure = matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
-       arvadostest.StartKeep(2, false)
+       srcConfig.APIHostInsecure = arvadosclient.StringBool(os.Getenv("ARVADOS_API_HOST_INSECURE"))
 
        _, ttl, err := setupKeepClient(srcConfig, srcKeepServicesJSON, false, 0, 0)
        c.Check(err, IsNil)
@@ -448,7 +424,7 @@ func setupConfigFile(c *C, name string) *os.File {
 
 func (s *DoMainTestSuite) Test_doMain_NoSrcConfig(c *C) {
        err := doMain()
-       c.Check(err, NotNil)
+       c.Assert(err, NotNil)
        c.Assert(err.Error(), Equals, "Error loading src configuration from file: config file not specified")
 }
 
@@ -457,7 +433,7 @@ func (s *DoMainTestSuite) Test_doMain_SrcButNoDstConfig(c *C) {
        args := []string{"-replications", "3", "-src", srcConfig.Name()}
        os.Args = append(os.Args, args...)
        err := doMain()
-       c.Check(err, NotNil)
+       c.Assert(err, NotNil)
        c.Assert(err.Error(), Equals, "Error loading dst configuration from file: config file not specified")
 }
 
@@ -465,8 +441,8 @@ func (s *DoMainTestSuite) Test_doMain_BadSrcConfig(c *C) {
        args := []string{"-src", "abcd"}
        os.Args = append(os.Args, args...)
        err := doMain()
-       c.Check(err, NotNil)
-       c.Assert(strings.HasPrefix(err.Error(), "Error loading src configuration from file: Error reading config file"), Equals, true)
+       c.Assert(err, NotNil)
+       c.Assert(err.Error(), Matches, "Error loading src configuration from file: Error reading config file.*")
 }
 
 func (s *DoMainTestSuite) Test_doMain_WithReplicationsButNoSrcConfig(c *C) {
@@ -488,6 +464,7 @@ func (s *DoMainTestSuite) Test_doMainWithSrcAndDstConfig(c *C) {
        // actual copying to dst will happen, but that's ok.
        arvadostest.StartKeep(2, false)
        defer arvadostest.StopKeep(2)
+       keepclient.RefreshServiceDiscovery()
 
        err := doMain()
        c.Check(err, IsNil)