1 # Copyright (c) 2012 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.
8 from StringIO import StringIO
10 import appengine_blobstore as blobstore
11 from appengine_url_fetcher import AppEngineUrlFetcher
12 from appengine_wrappers import GetAppVersion, urlfetch
13 from docs_server_utils import StringIdentity
14 from file_system import FileSystem, StatInfo
15 from future import Future
16 from object_store_creator import ObjectStoreCreator
18 from zipfile import ZipFile, BadZipfile
24 def _MakeBlobstoreKey(version):
25 return ZIP_KEY + '.' + str(version)
27 class _AsyncFetchFutureZip(object):
35 self._fetcher = fetcher
36 self._fetch = fetcher.FetchAsync(ZIP_KEY,
39 self._blobstore = blobstore
40 self._key_to_set = key_to_set
41 self._key_to_delete = key_to_delete
45 result = self._fetch.Get()
46 # Check if Github authentication failed.
47 if result.status_code == 401:
48 logging.error('Github authentication failed for %s, falling back to '
49 'unauthenticated.' % USERNAME)
50 blob = self._fetcher.Fetch(ZIP_KEY).content
53 except urlfetch.DownloadError as e:
54 logging.error('Bad github zip file: %s' % e)
56 if self._key_to_delete is not None:
57 self._blobstore.Delete(_MakeBlobstoreKey(self._key_to_delete),
58 blobstore.BLOBSTORE_GITHUB)
60 return_zip = ZipFile(StringIO(blob))
61 except BadZipfile as e:
62 logging.error('Bad github zip file: %s' % e)
65 self._blobstore.Set(_MakeBlobstoreKey(self._key_to_set),
67 blobstore.BLOBSTORE_GITHUB)
70 class GithubFileSystem(FileSystem):
72 def CreateChromeAppsSamples(object_store_creator):
73 return GithubFileSystem(
74 '%s/GoogleChrome/chrome-app-samples' % url_constants.GITHUB_REPOS,
75 blobstore.AppEngineBlobstore(),
78 def __init__(self, url, blobstore, object_store_creator):
79 # If we key the password store on the app version then the whole advantage
80 # of having it in the first place is greatly lessened (likewise it should
81 # always start populated).
82 password_store = object_store_creator.Create(
88 password_data = password_store.GetMulti(('username', 'password')).Get()
89 self._username, self._password = (password_data.get('username'),
90 password_data.get('password'))
92 password_store.SetMulti({'username': USERNAME, 'password': PASSWORD})
93 self._username, self._password = (USERNAME, PASSWORD)
96 self._fetcher = AppEngineUrlFetcher(url)
97 self._blobstore = blobstore
98 self._stat_object_store = object_store_creator.Create(GithubFileSystem)
100 self._GetZip(self.Stat(ZIP_KEY).version)
102 def _GetZip(self, version):
103 blob = self._blobstore.Get(_MakeBlobstoreKey(version),
104 blobstore.BLOBSTORE_GITHUB)
107 self._zip_file = Future(value=ZipFile(StringIO(blob)))
108 except BadZipfile as e:
109 self._blobstore.Delete(_MakeBlobstoreKey(version),
110 blobstore.BLOBSTORE_GITHUB)
111 logging.error('Bad github zip file: %s' % e)
112 self._zip_file = Future(value=None)
114 self._zip_file = Future(
115 delegate=_AsyncFetchFutureZip(self._fetcher,
120 key_to_delete=self._version))
121 self._version = version
123 def _ReadFile(self, path):
125 zip_file = self._zip_file.Get()
126 except Exception as e:
127 logging.error('Github ReadFile error: %s' % e)
130 logging.error('Bad github zip file.')
132 prefix = zip_file.namelist()[0][:-1]
133 return zip_file.read(prefix + path)
135 def _ListDir(self, path):
137 zip_file = self._zip_file.Get()
138 except Exception as e:
139 logging.error('Github ListDir error: %s' % e)
142 logging.error('Bad github zip file.')
144 filenames = zip_file.namelist()
145 # Take out parent directory name (GoogleChrome-chrome-app-samples-c78a30f)
146 filenames = [f[len(filenames[0]) - 1:] for f in filenames]
147 # Remove the path of the directory we're listing from the filenames.
148 filenames = [f[len(path):] for f in filenames
149 if f != path and f.startswith(path)]
150 # Remove all files not directly in this directory.
151 return [f for f in filenames if f[:-1].count('/') == 0]
153 def Read(self, paths, binary=False):
154 version = self.Stat(ZIP_KEY).version
155 if version != self._version:
156 self._GetZip(version)
159 if path.endswith('/'):
160 result[path] = self._ListDir(path)
162 result[path] = self._ReadFile(path)
163 return Future(value=result)
165 def _DefaultStat(self, path):
167 # TODO(kalman): we should replace all of this by wrapping the
168 # GithubFileSystem in a CachingFileSystem. A lot of work has been put into
169 # CFS to be robust, and GFS is missing out.
170 # For example: the following line is wrong, but it could be moot.
171 self._stat_object_store.Set(path, version)
172 return StatInfo(version)
174 def Stat(self, path):
175 version = self._stat_object_store.Get(path).Get()
176 if version is not None:
177 return StatInfo(version)
179 result = self._fetcher.Fetch('commits/HEAD',
182 except urlfetch.DownloadError as e:
183 logging.warning('GithubFileSystem Stat: %s' % e)
184 return self._DefaultStat(path)
186 # Check if Github authentication failed.
187 if result.status_code == 401:
188 logging.warning('Github authentication failed for %s, falling back to '
189 'unauthenticated.' % USERNAME)
191 result = self._fetcher.Fetch('commits/HEAD')
192 except urlfetch.DownloadError as e:
193 logging.warning('GithubFileSystem Stat: %s' % e)
194 return self._DefaultStat(path)
196 # Parse response JSON - but sometimes github gives us invalid JSON.
198 version = json.loads(result.content)['commit']['tree']['sha']
199 self._stat_object_store.Set(path, version)
200 return StatInfo(version)
201 except StandardError as e:
203 ('%s: got invalid or unexpected JSON from github. Response status ' +
204 'was %s, content %s') % (e, result.status_code, result.content))
205 return self._DefaultStat(path)
207 def GetIdentity(self):
208 return '%s@%s' % (self.__class__.__name__, StringIdentity(self._url))