1 # Copyright 2013 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
9 from environment
import IsAppEngine
, IsComputeEngine
, IsTest
12 _METADATA_SERVER
= 'http://metadata/computeMetadata/v1/instance/service-accounts'
13 _SERVICE_ACCOUNT
= 'default'
15 # The environment variable to use as a fallback token source.
16 _ACCESS_TOKEN_ENV
= 'DOCSERVER_ACCESS_TOKEN'
19 def CreateUrlFetcher(base_path
=None):
21 from url_fetcher_appengine
import UrlFetcherAppengine
22 fetcher
= UrlFetcherAppengine()
24 from url_fetcher_urllib2
import UrlFetcherUrllib2
25 fetcher
= UrlFetcherUrllib2()
27 from url_fetcher_fake
import UrlFetcherFake
28 fetcher
= UrlFetcherFake()
29 fetcher
.SetBasePath(base_path
)
33 def CreatePersistentObjectStore(namespace
):
35 from persistent_object_store_appengine
import PersistentObjectStoreAppengine
36 object_store
= PersistentObjectStoreAppengine(namespace
)
38 from persistent_object_store_fake
import PersistentObjectStoreFake
39 object_store
= PersistentObjectStoreFake(namespace
)
44 '''Acquires an access token either from the metadata service (if running on
45 a real CE VM) or the DOCSERVER_ACCESS_TOKEN environment variable.
47 This may return None if no token is available. That should never happen while
50 # Attempt to grab an access token from the VM instance's metadata.
52 fetcher
= CreateUrlFetcher()
53 token_uri
= '%s/%s/token' % (_METADATA_SERVER
, _SERVICE_ACCOUNT
)
56 token_response
= fetcher
.Fetch(token_uri
,
57 headers
={'Metadata-Flavor': 'Google'})
58 if token_response
.status_code
== 200:
59 return json
.loads(token_response
.content
)['access_token']
60 except Exception as e
:
61 logging
.warn('Failed to fetch access token from VM metadata.')
64 logging
.warn('Using access token from local environment.')
65 access_token
= os
.getenv(_ACCESS_TOKEN_ENV
)
66 if access_token
is None:
67 logging
.error('No access token available. '
68 'Please set %s if you want things to work.' %