googlecloud 0.0.2 → 0.0.4

Sign up to get free protection for your applications and to get access to all the features.
Files changed (118) hide show
  1. data.tar.gz.sig +0 -0
  2. data/CHANGELOG +4 -0
  3. data/LICENSE +674 -0
  4. data/Manifest +111 -0
  5. data/README.md +4 -3
  6. data/bin/gcutil +53 -0
  7. data/googlecloud.gemspec +4 -3
  8. data/packages/gcutil-1.7.1/CHANGELOG +197 -0
  9. data/packages/gcutil-1.7.1/LICENSE +202 -0
  10. data/packages/gcutil-1.7.1/VERSION +1 -0
  11. data/packages/gcutil-1.7.1/gcutil +53 -0
  12. data/packages/gcutil-1.7.1/lib/google_api_python_client/LICENSE +23 -0
  13. data/packages/gcutil-1.7.1/lib/google_api_python_client/apiclient/__init__.py +1 -0
  14. data/packages/gcutil-1.7.1/lib/google_api_python_client/apiclient/discovery.py +743 -0
  15. data/packages/gcutil-1.7.1/lib/google_api_python_client/apiclient/errors.py +123 -0
  16. data/packages/gcutil-1.7.1/lib/google_api_python_client/apiclient/ext/__init__.py +0 -0
  17. data/packages/gcutil-1.7.1/lib/google_api_python_client/apiclient/http.py +1443 -0
  18. data/packages/gcutil-1.7.1/lib/google_api_python_client/apiclient/mimeparse.py +172 -0
  19. data/packages/gcutil-1.7.1/lib/google_api_python_client/apiclient/model.py +385 -0
  20. data/packages/gcutil-1.7.1/lib/google_api_python_client/apiclient/schema.py +303 -0
  21. data/packages/gcutil-1.7.1/lib/google_api_python_client/oauth2client/__init__.py +1 -0
  22. data/packages/gcutil-1.7.1/lib/google_api_python_client/oauth2client/anyjson.py +32 -0
  23. data/packages/gcutil-1.7.1/lib/google_api_python_client/oauth2client/appengine.py +528 -0
  24. data/packages/gcutil-1.7.1/lib/google_api_python_client/oauth2client/client.py +1139 -0
  25. data/packages/gcutil-1.7.1/lib/google_api_python_client/oauth2client/clientsecrets.py +105 -0
  26. data/packages/gcutil-1.7.1/lib/google_api_python_client/oauth2client/crypt.py +244 -0
  27. data/packages/gcutil-1.7.1/lib/google_api_python_client/oauth2client/django_orm.py +124 -0
  28. data/packages/gcutil-1.7.1/lib/google_api_python_client/oauth2client/file.py +107 -0
  29. data/packages/gcutil-1.7.1/lib/google_api_python_client/oauth2client/locked_file.py +343 -0
  30. data/packages/gcutil-1.7.1/lib/google_api_python_client/oauth2client/multistore_file.py +379 -0
  31. data/packages/gcutil-1.7.1/lib/google_api_python_client/oauth2client/tools.py +174 -0
  32. data/packages/gcutil-1.7.1/lib/google_api_python_client/uritemplate/__init__.py +147 -0
  33. data/packages/gcutil-1.7.1/lib/google_apputils/LICENSE +202 -0
  34. data/packages/gcutil-1.7.1/lib/google_apputils/google/__init__.py +3 -0
  35. data/packages/gcutil-1.7.1/lib/google_apputils/google/apputils/__init__.py +3 -0
  36. data/packages/gcutil-1.7.1/lib/google_apputils/google/apputils/app.py +356 -0
  37. data/packages/gcutil-1.7.1/lib/google_apputils/google/apputils/appcommands.py +783 -0
  38. data/packages/gcutil-1.7.1/lib/google_apputils/google/apputils/basetest.py +1260 -0
  39. data/packages/gcutil-1.7.1/lib/google_apputils/google/apputils/datelib.py +421 -0
  40. data/packages/gcutil-1.7.1/lib/google_apputils/google/apputils/debug.py +60 -0
  41. data/packages/gcutil-1.7.1/lib/google_apputils/google/apputils/file_util.py +181 -0
  42. data/packages/gcutil-1.7.1/lib/google_apputils/google/apputils/resources.py +67 -0
  43. data/packages/gcutil-1.7.1/lib/google_apputils/google/apputils/run_script_module.py +217 -0
  44. data/packages/gcutil-1.7.1/lib/google_apputils/google/apputils/setup_command.py +159 -0
  45. data/packages/gcutil-1.7.1/lib/google_apputils/google/apputils/shellutil.py +49 -0
  46. data/packages/gcutil-1.7.1/lib/google_apputils/google/apputils/stopwatch.py +204 -0
  47. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/__init__.py +0 -0
  48. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/auth_helper.py +140 -0
  49. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/auth_helper_test.py +149 -0
  50. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/auto_auth.py +130 -0
  51. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/auto_auth_test.py +75 -0
  52. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/basic_cmds.py +128 -0
  53. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/basic_cmds_test.py +111 -0
  54. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/command_base.py +1808 -0
  55. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/command_base_test.py +1651 -0
  56. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/compute/v1beta13.json +2851 -0
  57. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/compute/v1beta14.json +3361 -0
  58. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/disk_cmds.py +342 -0
  59. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/disk_cmds_test.py +474 -0
  60. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/firewall_cmds.py +344 -0
  61. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/firewall_cmds_test.py +231 -0
  62. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/flags_cache.py +274 -0
  63. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/gcutil +89 -0
  64. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/gcutil_logging.py +69 -0
  65. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/image_cmds.py +262 -0
  66. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/image_cmds_test.py +172 -0
  67. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/instance_cmds.py +1506 -0
  68. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/instance_cmds_test.py +1904 -0
  69. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/kernel_cmds.py +91 -0
  70. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/kernel_cmds_test.py +56 -0
  71. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/machine_type_cmds.py +106 -0
  72. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/machine_type_cmds_test.py +59 -0
  73. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/metadata.py +96 -0
  74. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/metadata_lib.py +357 -0
  75. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/metadata_test.py +84 -0
  76. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/mock_api.py +420 -0
  77. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/mock_metadata.py +58 -0
  78. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/move_cmds.py +824 -0
  79. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/move_cmds_test.py +307 -0
  80. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/network_cmds.py +178 -0
  81. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/network_cmds_test.py +133 -0
  82. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/operation_cmds.py +181 -0
  83. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/operation_cmds_test.py +196 -0
  84. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/path_initializer.py +38 -0
  85. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/project_cmds.py +173 -0
  86. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/project_cmds_test.py +111 -0
  87. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/scopes.py +61 -0
  88. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/scopes_test.py +50 -0
  89. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/snapshot_cmds.py +276 -0
  90. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/snapshot_cmds_test.py +260 -0
  91. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/ssh_keys.py +266 -0
  92. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/ssh_keys_test.py +128 -0
  93. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/table_formatter.py +563 -0
  94. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/thread_pool.py +188 -0
  95. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/thread_pool_test.py +88 -0
  96. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/utils.py +208 -0
  97. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/utils_test.py +193 -0
  98. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/version.py +17 -0
  99. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/version_checker.py +246 -0
  100. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/version_checker_test.py +271 -0
  101. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/zone_cmds.py +151 -0
  102. data/packages/gcutil-1.7.1/lib/google_compute_engine/gcutil/zone_cmds_test.py +60 -0
  103. data/packages/gcutil-1.7.1/lib/httplib2/LICENSE +21 -0
  104. data/packages/gcutil-1.7.1/lib/httplib2/httplib2/__init__.py +1630 -0
  105. data/packages/gcutil-1.7.1/lib/httplib2/httplib2/cacerts.txt +714 -0
  106. data/packages/gcutil-1.7.1/lib/httplib2/httplib2/iri2uri.py +110 -0
  107. data/packages/gcutil-1.7.1/lib/httplib2/httplib2/socks.py +438 -0
  108. data/packages/gcutil-1.7.1/lib/iso8601/LICENSE +20 -0
  109. data/packages/gcutil-1.7.1/lib/iso8601/iso8601/__init__.py +1 -0
  110. data/packages/gcutil-1.7.1/lib/iso8601/iso8601/iso8601.py +102 -0
  111. data/packages/gcutil-1.7.1/lib/iso8601/iso8601/test_iso8601.py +111 -0
  112. data/packages/gcutil-1.7.1/lib/python_gflags/AUTHORS +2 -0
  113. data/packages/gcutil-1.7.1/lib/python_gflags/LICENSE +28 -0
  114. data/packages/gcutil-1.7.1/lib/python_gflags/gflags.py +2862 -0
  115. data/packages/gcutil-1.7.1/lib/python_gflags/gflags2man.py +544 -0
  116. data/packages/gcutil-1.7.1/lib/python_gflags/gflags_validators.py +187 -0
  117. metadata +118 -5
  118. metadata.gz.sig +0 -0
@@ -0,0 +1,107 @@
1
+ # Copyright (C) 2010 Google Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Utilities for OAuth.
16
+
17
+ Utilities for making it easier to work with OAuth 2.0
18
+ credentials.
19
+ """
20
+
21
+
22
+
23
+ import os
24
+ import stat
25
+ import threading
26
+
27
+ from anyjson import simplejson
28
+ from client import Storage as BaseStorage
29
+ from client import Credentials
30
+
31
+
32
+ class Storage(BaseStorage):
33
+ """Store and retrieve a single credential to and from a file."""
34
+
35
+ def __init__(self, filename):
36
+ self._filename = filename
37
+ self._lock = threading.Lock()
38
+
39
+ def acquire_lock(self):
40
+ """Acquires any lock necessary to access this Storage.
41
+
42
+ This lock is not reentrant."""
43
+ self._lock.acquire()
44
+
45
+ def release_lock(self):
46
+ """Release the Storage lock.
47
+
48
+ Trying to release a lock that isn't held will result in a
49
+ RuntimeError.
50
+ """
51
+ self._lock.release()
52
+
53
+ def locked_get(self):
54
+ """Retrieve Credential from file.
55
+
56
+ Returns:
57
+ oauth2client.client.Credentials
58
+ """
59
+ credentials = None
60
+ try:
61
+ f = open(self._filename, 'rb')
62
+ content = f.read()
63
+ f.close()
64
+ except IOError:
65
+ return credentials
66
+
67
+ try:
68
+ credentials = Credentials.new_from_json(content)
69
+ credentials.set_store(self)
70
+ except ValueError:
71
+ pass
72
+
73
+ return credentials
74
+
75
+ def _create_file_if_needed(self):
76
+ """Create an empty file if necessary.
77
+
78
+ This method will not initialize the file. Instead it implements a
79
+ simple version of "touch" to ensure the file has been created.
80
+ """
81
+ if not os.path.exists(self._filename):
82
+ old_umask = os.umask(0177)
83
+ try:
84
+ open(self._filename, 'a+b').close()
85
+ finally:
86
+ os.umask(old_umask)
87
+
88
+ def locked_put(self, credentials):
89
+ """Write Credentials to file.
90
+
91
+ Args:
92
+ credentials: Credentials, the credentials to store.
93
+ """
94
+
95
+ self._create_file_if_needed()
96
+ f = open(self._filename, 'wb')
97
+ f.write(credentials.to_json())
98
+ f.close()
99
+
100
+ def locked_delete(self):
101
+ """Delete Credentials file.
102
+
103
+ Args:
104
+ credentials: Credentials, the credentials to store.
105
+ """
106
+
107
+ os.unlink(self._filename)
@@ -0,0 +1,343 @@
1
+ # Copyright 2011 Google Inc. All Rights Reserved.
2
+
3
+ """Locked file interface that should work on Unix and Windows pythons.
4
+
5
+ This module first tries to use fcntl locking to ensure serialized access
6
+ to a file, then falls back on a lock file if that is unavialable.
7
+
8
+ Usage:
9
+ f = LockedFile('filename', 'r+b', 'rb')
10
+ f.open_and_lock()
11
+ if f.is_locked():
12
+ print 'Acquired filename with r+b mode'
13
+ f.file_handle().write('locked data')
14
+ else:
15
+ print 'Aquired filename with rb mode'
16
+ f.unlock_and_close()
17
+ """
18
+
19
+
20
+
21
+ import errno
22
+ import logging
23
+ import os
24
+ import time
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ class AlreadyLockedException(Exception):
30
+ """Trying to lock a file that has already been locked by the LockedFile."""
31
+ pass
32
+
33
+
34
+ class _Opener(object):
35
+ """Base class for different locking primitives."""
36
+
37
+ def __init__(self, filename, mode, fallback_mode):
38
+ """Create an Opener.
39
+
40
+ Args:
41
+ filename: string, The pathname of the file.
42
+ mode: string, The preferred mode to access the file with.
43
+ fallback_mode: string, The mode to use if locking fails.
44
+ """
45
+ self._locked = False
46
+ self._filename = filename
47
+ self._mode = mode
48
+ self._fallback_mode = fallback_mode
49
+ self._fh = None
50
+
51
+ def is_locked(self):
52
+ """Was the file locked."""
53
+ return self._locked
54
+
55
+ def file_handle(self):
56
+ """The file handle to the file. Valid only after opened."""
57
+ return self._fh
58
+
59
+ def filename(self):
60
+ """The filename that is being locked."""
61
+ return self._filename
62
+
63
+ def open_and_lock(self, timeout, delay):
64
+ """Open the file and lock it.
65
+
66
+ Args:
67
+ timeout: float, How long to try to lock for.
68
+ delay: float, How long to wait between retries.
69
+ """
70
+ pass
71
+
72
+ def unlock_and_close(self):
73
+ """Unlock and close the file."""
74
+ pass
75
+
76
+
77
+ class _PosixOpener(_Opener):
78
+ """Lock files using Posix advisory lock files."""
79
+
80
+ def open_and_lock(self, timeout, delay):
81
+ """Open the file and lock it.
82
+
83
+ Tries to create a .lock file next to the file we're trying to open.
84
+
85
+ Args:
86
+ timeout: float, How long to try to lock for.
87
+ delay: float, How long to wait between retries.
88
+
89
+ Raises:
90
+ AlreadyLockedException: if the lock is already acquired.
91
+ IOError: if the open fails.
92
+ """
93
+ if self._locked:
94
+ raise AlreadyLockedException('File %s is already locked' %
95
+ self._filename)
96
+ self._locked = False
97
+
98
+ try:
99
+ self._fh = open(self._filename, self._mode)
100
+ except IOError, e:
101
+ # If we can't access with _mode, try _fallback_mode and don't lock.
102
+ if e.errno == errno.EACCES:
103
+ self._fh = open(self._filename, self._fallback_mode)
104
+ return
105
+
106
+ lock_filename = self._posix_lockfile(self._filename)
107
+ start_time = time.time()
108
+ while True:
109
+ try:
110
+ self._lock_fd = os.open(lock_filename,
111
+ os.O_CREAT|os.O_EXCL|os.O_RDWR)
112
+ self._locked = True
113
+ break
114
+
115
+ except OSError, e:
116
+ if e.errno != errno.EEXIST:
117
+ raise
118
+ if (time.time() - start_time) >= timeout:
119
+ logger.warn('Could not acquire lock %s in %s seconds' % (
120
+ lock_filename, timeout))
121
+ # Close the file and open in fallback_mode.
122
+ if self._fh:
123
+ self._fh.close()
124
+ self._fh = open(self._filename, self._fallback_mode)
125
+ return
126
+ time.sleep(delay)
127
+
128
+ def unlock_and_close(self):
129
+ """Unlock a file by removing the .lock file, and close the handle."""
130
+ if self._locked:
131
+ lock_filename = self._posix_lockfile(self._filename)
132
+ os.unlink(lock_filename)
133
+ os.close(self._lock_fd)
134
+ self._locked = False
135
+ self._lock_fd = None
136
+ if self._fh:
137
+ self._fh.close()
138
+
139
+ def _posix_lockfile(self, filename):
140
+ """The name of the lock file to use for posix locking."""
141
+ return '%s.lock' % filename
142
+
143
+
144
+ try:
145
+ import fcntl
146
+
147
+ class _FcntlOpener(_Opener):
148
+ """Open, lock, and unlock a file using fcntl.lockf."""
149
+
150
+ def open_and_lock(self, timeout, delay):
151
+ """Open the file and lock it.
152
+
153
+ Args:
154
+ timeout: float, How long to try to lock for.
155
+ delay: float, How long to wait between retries
156
+
157
+ Raises:
158
+ AlreadyLockedException: if the lock is already acquired.
159
+ IOError: if the open fails.
160
+ """
161
+ if self._locked:
162
+ raise AlreadyLockedException('File %s is already locked' %
163
+ self._filename)
164
+ start_time = time.time()
165
+
166
+ try:
167
+ self._fh = open(self._filename, self._mode)
168
+ except IOError, e:
169
+ # If we can't access with _mode, try _fallback_mode and don't lock.
170
+ if e.errno == errno.EACCES:
171
+ self._fh = open(self._filename, self._fallback_mode)
172
+ return
173
+
174
+ # We opened in _mode, try to lock the file.
175
+ while True:
176
+ try:
177
+ fcntl.lockf(self._fh.fileno(), fcntl.LOCK_EX)
178
+ self._locked = True
179
+ return
180
+ except IOError, e:
181
+ # If not retrying, then just pass on the error.
182
+ if timeout == 0:
183
+ raise e
184
+ if e.errno != errno.EACCES:
185
+ raise e
186
+ # We could not acquire the lock. Try again.
187
+ if (time.time() - start_time) >= timeout:
188
+ logger.warn('Could not lock %s in %s seconds' % (
189
+ self._filename, timeout))
190
+ if self._fh:
191
+ self._fh.close()
192
+ self._fh = open(self._filename, self._fallback_mode)
193
+ return
194
+ time.sleep(delay)
195
+
196
+ def unlock_and_close(self):
197
+ """Close and unlock the file using the fcntl.lockf primitive."""
198
+ if self._locked:
199
+ fcntl.lockf(self._fh.fileno(), fcntl.LOCK_UN)
200
+ self._locked = False
201
+ if self._fh:
202
+ self._fh.close()
203
+ except ImportError:
204
+ _FcntlOpener = None
205
+
206
+
207
+ try:
208
+ import pywintypes
209
+ import win32con
210
+ import win32file
211
+
212
+ class _Win32Opener(_Opener):
213
+ """Open, lock, and unlock a file using windows primitives."""
214
+
215
+ # Error #33:
216
+ # 'The process cannot access the file because another process'
217
+ FILE_IN_USE_ERROR = 33
218
+
219
+ # Error #158:
220
+ # 'The segment is already unlocked.'
221
+ FILE_ALREADY_UNLOCKED_ERROR = 158
222
+
223
+ def open_and_lock(self, timeout, delay):
224
+ """Open the file and lock it.
225
+
226
+ Args:
227
+ timeout: float, How long to try to lock for.
228
+ delay: float, How long to wait between retries
229
+
230
+ Raises:
231
+ AlreadyLockedException: if the lock is already acquired.
232
+ IOError: if the open fails.
233
+ """
234
+ if self._locked:
235
+ raise AlreadyLockedException('File %s is already locked' %
236
+ self._filename)
237
+ start_time = time.time()
238
+
239
+ try:
240
+ self._fh = open(self._filename, self._mode)
241
+ except IOError, e:
242
+ # If we can't access with _mode, try _fallback_mode and don't lock.
243
+ if e.errno == errno.EACCES:
244
+ self._fh = open(self._filename, self._fallback_mode)
245
+ return
246
+
247
+ # We opened in _mode, try to lock the file.
248
+ while True:
249
+ try:
250
+ hfile = win32file._get_osfhandle(self._fh.fileno())
251
+ win32file.LockFileEx(
252
+ hfile,
253
+ (win32con.LOCKFILE_FAIL_IMMEDIATELY|
254
+ win32con.LOCKFILE_EXCLUSIVE_LOCK), 0, -0x10000,
255
+ pywintypes.OVERLAPPED())
256
+ self._locked = True
257
+ return
258
+ except pywintypes.error, e:
259
+ if timeout == 0:
260
+ raise e
261
+
262
+ # If the error is not that the file is already in use, raise.
263
+ if e[0] != _Win32Opener.FILE_IN_USE_ERROR:
264
+ raise
265
+
266
+ # We could not acquire the lock. Try again.
267
+ if (time.time() - start_time) >= timeout:
268
+ logger.warn('Could not lock %s in %s seconds' % (
269
+ self._filename, timeout))
270
+ if self._fh:
271
+ self._fh.close()
272
+ self._fh = open(self._filename, self._fallback_mode)
273
+ return
274
+ time.sleep(delay)
275
+
276
+ def unlock_and_close(self):
277
+ """Close and unlock the file using the win32 primitive."""
278
+ if self._locked:
279
+ try:
280
+ hfile = win32file._get_osfhandle(self._fh.fileno())
281
+ win32file.UnlockFileEx(hfile, 0, -0x10000, pywintypes.OVERLAPPED())
282
+ except pywintypes.error, e:
283
+ if e[0] != _Win32Opener.FILE_ALREADY_UNLOCKED_ERROR:
284
+ raise
285
+ self._locked = False
286
+ if self._fh:
287
+ self._fh.close()
288
+ except ImportError:
289
+ _Win32Opener = None
290
+
291
+
292
+ class LockedFile(object):
293
+ """Represent a file that has exclusive access."""
294
+
295
+ def __init__(self, filename, mode, fallback_mode, use_native_locking=True):
296
+ """Construct a LockedFile.
297
+
298
+ Args:
299
+ filename: string, The path of the file to open.
300
+ mode: string, The mode to try to open the file with.
301
+ fallback_mode: string, The mode to use if locking fails.
302
+ use_native_locking: bool, Whether or not fcntl/win32 locking is used.
303
+ """
304
+ opener = None
305
+ if not opener and use_native_locking:
306
+ if _Win32Opener:
307
+ opener = _Win32Opener(filename, mode, fallback_mode)
308
+ if _FcntlOpener:
309
+ opener = _FcntlOpener(filename, mode, fallback_mode)
310
+
311
+ if not opener:
312
+ opener = _PosixOpener(filename, mode, fallback_mode)
313
+
314
+ self._opener = opener
315
+
316
+ def filename(self):
317
+ """Return the filename we were constructed with."""
318
+ return self._opener._filename
319
+
320
+ def file_handle(self):
321
+ """Return the file_handle to the opened file."""
322
+ return self._opener.file_handle()
323
+
324
+ def is_locked(self):
325
+ """Return whether we successfully locked the file."""
326
+ return self._opener.is_locked()
327
+
328
+ def open_and_lock(self, timeout=0, delay=0.05):
329
+ """Open the file, trying to lock it.
330
+
331
+ Args:
332
+ timeout: float, The number of seconds to try to acquire the lock.
333
+ delay: float, The number of seconds to wait between retry attempts.
334
+
335
+ Raises:
336
+ AlreadyLockedException: if the lock is already acquired.
337
+ IOError: if the open fails.
338
+ """
339
+ self._opener.open_and_lock(timeout, delay)
340
+
341
+ def unlock_and_close(self):
342
+ """Unlock and close a file."""
343
+ self._opener.unlock_and_close()
@@ -0,0 +1,379 @@
1
+ # Copyright 2011 Google Inc. All Rights Reserved.
2
+
3
+ """Multi-credential file store with lock support.
4
+
5
+ This module implements a JSON credential store where multiple
6
+ credentials can be stored in one file. That file supports locking
7
+ both in a single process and across processes.
8
+
9
+ The credential themselves are keyed off of:
10
+ * client_id
11
+ * user_agent
12
+ * scope
13
+
14
+ The format of the stored data is like so:
15
+ {
16
+ 'file_version': 1,
17
+ 'data': [
18
+ {
19
+ 'key': {
20
+ 'clientId': '<client id>',
21
+ 'userAgent': '<user agent>',
22
+ 'scope': '<scope>'
23
+ },
24
+ 'credential': {
25
+ # JSON serialized Credentials.
26
+ }
27
+ }
28
+ ]
29
+ }
30
+ """
31
+
32
+
33
+
34
+ import base64
35
+ import errno
36
+ import logging
37
+ import os
38
+ import threading
39
+
40
+ from anyjson import simplejson
41
+ from client import Storage as BaseStorage
42
+ from client import Credentials
43
+ from locked_file import LockedFile
44
+
45
+ logger = logging.getLogger(__name__)
46
+
47
+ # A dict from 'filename'->_MultiStore instances
48
+ _multistores = {}
49
+ _multistores_lock = threading.Lock()
50
+
51
+
52
+ class Error(Exception):
53
+ """Base error for this module."""
54
+ pass
55
+
56
+
57
+ class NewerCredentialStoreError(Error):
58
+ """The credential store is a newer version that supported."""
59
+ pass
60
+
61
+
62
+ def get_credential_storage(filename, client_id, user_agent, scope,
63
+ warn_on_readonly=True):
64
+ """Get a Storage instance for a credential.
65
+
66
+ Args:
67
+ filename: The JSON file storing a set of credentials
68
+ client_id: The client_id for the credential
69
+ user_agent: The user agent for the credential
70
+ scope: string or list of strings, Scope(s) being requested
71
+ warn_on_readonly: if True, log a warning if the store is readonly
72
+
73
+ Returns:
74
+ An object derived from client.Storage for getting/setting the
75
+ credential.
76
+ """
77
+ filename = os.path.realpath(os.path.expanduser(filename))
78
+ _multistores_lock.acquire()
79
+ try:
80
+ multistore = _multistores.setdefault(
81
+ filename, _MultiStore(filename, warn_on_readonly))
82
+ finally:
83
+ _multistores_lock.release()
84
+ if type(scope) is list:
85
+ scope = ' '.join(scope)
86
+ return multistore._get_storage(client_id, user_agent, scope)
87
+
88
+
89
+ class _MultiStore(object):
90
+ """A file backed store for multiple credentials."""
91
+
92
+ def __init__(self, filename, warn_on_readonly=True):
93
+ """Initialize the class.
94
+
95
+ This will create the file if necessary.
96
+ """
97
+ self._file = LockedFile(filename, 'r+b', 'rb')
98
+ self._thread_lock = threading.Lock()
99
+ self._read_only = False
100
+ self._warn_on_readonly = warn_on_readonly
101
+
102
+ self._create_file_if_needed()
103
+
104
+ # Cache of deserialized store. This is only valid after the
105
+ # _MultiStore is locked or _refresh_data_cache is called. This is
106
+ # of the form of:
107
+ #
108
+ # (client_id, user_agent, scope) -> OAuth2Credential
109
+ #
110
+ # If this is None, then the store hasn't been read yet.
111
+ self._data = None
112
+
113
+ class _Storage(BaseStorage):
114
+ """A Storage object that knows how to read/write a single credential."""
115
+
116
+ def __init__(self, multistore, client_id, user_agent, scope):
117
+ self._multistore = multistore
118
+ self._client_id = client_id
119
+ self._user_agent = user_agent
120
+ self._scope = scope
121
+
122
+ def acquire_lock(self):
123
+ """Acquires any lock necessary to access this Storage.
124
+
125
+ This lock is not reentrant.
126
+ """
127
+ self._multistore._lock()
128
+
129
+ def release_lock(self):
130
+ """Release the Storage lock.
131
+
132
+ Trying to release a lock that isn't held will result in a
133
+ RuntimeError.
134
+ """
135
+ self._multistore._unlock()
136
+
137
+ def locked_get(self):
138
+ """Retrieve credential.
139
+
140
+ The Storage lock must be held when this is called.
141
+
142
+ Returns:
143
+ oauth2client.client.Credentials
144
+ """
145
+ credential = self._multistore._get_credential(
146
+ self._client_id, self._user_agent, self._scope)
147
+ if credential:
148
+ credential.set_store(self)
149
+ return credential
150
+
151
+ def locked_put(self, credentials):
152
+ """Write a credential.
153
+
154
+ The Storage lock must be held when this is called.
155
+
156
+ Args:
157
+ credentials: Credentials, the credentials to store.
158
+ """
159
+ self._multistore._update_credential(credentials, self._scope)
160
+
161
+ def locked_delete(self):
162
+ """Delete a credential.
163
+
164
+ The Storage lock must be held when this is called.
165
+
166
+ Args:
167
+ credentials: Credentials, the credentials to store.
168
+ """
169
+ self._multistore._delete_credential(self._client_id, self._user_agent,
170
+ self._scope)
171
+
172
+ def _create_file_if_needed(self):
173
+ """Create an empty file if necessary.
174
+
175
+ This method will not initialize the file. Instead it implements a
176
+ simple version of "touch" to ensure the file has been created.
177
+ """
178
+ if not os.path.exists(self._file.filename()):
179
+ old_umask = os.umask(0177)
180
+ try:
181
+ open(self._file.filename(), 'a+b').close()
182
+ finally:
183
+ os.umask(old_umask)
184
+
185
+ def _lock(self):
186
+ """Lock the entire multistore."""
187
+ self._thread_lock.acquire()
188
+ self._file.open_and_lock()
189
+ if not self._file.is_locked():
190
+ self._read_only = True
191
+ if self._warn_on_readonly:
192
+ logger.warn('The credentials file (%s) is not writable. Opening in '
193
+ 'read-only mode. Any refreshed credentials will only be '
194
+ 'valid for this run.' % self._file.filename())
195
+ if os.path.getsize(self._file.filename()) == 0:
196
+ logger.debug('Initializing empty multistore file')
197
+ # The multistore is empty so write out an empty file.
198
+ self._data = {}
199
+ self._write()
200
+ elif not self._read_only or self._data is None:
201
+ # Only refresh the data if we are read/write or we haven't
202
+ # cached the data yet. If we are readonly, we assume is isn't
203
+ # changing out from under us and that we only have to read it
204
+ # once. This prevents us from whacking any new access keys that
205
+ # we have cached in memory but were unable to write out.
206
+ self._refresh_data_cache()
207
+
208
+ def _unlock(self):
209
+ """Release the lock on the multistore."""
210
+ self._file.unlock_and_close()
211
+ self._thread_lock.release()
212
+
213
+ def _locked_json_read(self):
214
+ """Get the raw content of the multistore file.
215
+
216
+ The multistore must be locked when this is called.
217
+
218
+ Returns:
219
+ The contents of the multistore decoded as JSON.
220
+ """
221
+ assert self._thread_lock.locked()
222
+ self._file.file_handle().seek(0)
223
+ return simplejson.load(self._file.file_handle())
224
+
225
+ def _locked_json_write(self, data):
226
+ """Write a JSON serializable data structure to the multistore.
227
+
228
+ The multistore must be locked when this is called.
229
+
230
+ Args:
231
+ data: The data to be serialized and written.
232
+ """
233
+ assert self._thread_lock.locked()
234
+ if self._read_only:
235
+ return
236
+ self._file.file_handle().seek(0)
237
+ simplejson.dump(data, self._file.file_handle(), sort_keys=True, indent=2)
238
+ self._file.file_handle().truncate()
239
+
240
+ def _refresh_data_cache(self):
241
+ """Refresh the contents of the multistore.
242
+
243
+ The multistore must be locked when this is called.
244
+
245
+ Raises:
246
+ NewerCredentialStoreError: Raised when a newer client has written the
247
+ store.
248
+ """
249
+ self._data = {}
250
+ try:
251
+ raw_data = self._locked_json_read()
252
+ except Exception:
253
+ logger.warn('Credential data store could not be loaded. '
254
+ 'Will ignore and overwrite.')
255
+ return
256
+
257
+ version = 0
258
+ try:
259
+ version = raw_data['file_version']
260
+ except Exception:
261
+ logger.warn('Missing version for credential data store. It may be '
262
+ 'corrupt or an old version. Overwriting.')
263
+ if version > 1:
264
+ raise NewerCredentialStoreError(
265
+ 'Credential file has file_version of %d. '
266
+ 'Only file_version of 1 is supported.' % version)
267
+
268
+ credentials = []
269
+ try:
270
+ credentials = raw_data['data']
271
+ except (TypeError, KeyError):
272
+ pass
273
+
274
+ for cred_entry in credentials:
275
+ try:
276
+ (key, credential) = self._decode_credential_from_json(cred_entry)
277
+ self._data[key] = credential
278
+ except:
279
+ # If something goes wrong loading a credential, just ignore it
280
+ logger.info('Error decoding credential, skipping', exc_info=True)
281
+
282
+ def _decode_credential_from_json(self, cred_entry):
283
+ """Load a credential from our JSON serialization.
284
+
285
+ Args:
286
+ cred_entry: A dict entry from the data member of our format
287
+
288
+ Returns:
289
+ (key, cred) where the key is the key tuple and the cred is the
290
+ OAuth2Credential object.
291
+ """
292
+ raw_key = cred_entry['key']
293
+ client_id = raw_key['clientId']
294
+ user_agent = raw_key['userAgent']
295
+ scope = raw_key['scope']
296
+ key = (client_id, user_agent, scope)
297
+ credential = None
298
+ credential = Credentials.new_from_json(simplejson.dumps(cred_entry['credential']))
299
+ return (key, credential)
300
+
301
+ def _write(self):
302
+ """Write the cached data back out.
303
+
304
+ The multistore must be locked.
305
+ """
306
+ raw_data = {'file_version': 1}
307
+ raw_creds = []
308
+ raw_data['data'] = raw_creds
309
+ for (cred_key, cred) in self._data.items():
310
+ raw_key = {
311
+ 'clientId': cred_key[0],
312
+ 'userAgent': cred_key[1],
313
+ 'scope': cred_key[2]
314
+ }
315
+ raw_cred = simplejson.loads(cred.to_json())
316
+ raw_creds.append({'key': raw_key, 'credential': raw_cred})
317
+ self._locked_json_write(raw_data)
318
+
319
+ def _get_credential(self, client_id, user_agent, scope):
320
+ """Get a credential from the multistore.
321
+
322
+ The multistore must be locked.
323
+
324
+ Args:
325
+ client_id: The client_id for the credential
326
+ user_agent: The user agent for the credential
327
+ scope: A string for the scope(s) being requested
328
+
329
+ Returns:
330
+ The credential specified or None if not present
331
+ """
332
+ key = (client_id, user_agent, scope)
333
+
334
+ return self._data.get(key, None)
335
+
336
+ def _update_credential(self, cred, scope):
337
+ """Update a credential and write the multistore.
338
+
339
+ This must be called when the multistore is locked.
340
+
341
+ Args:
342
+ cred: The OAuth2Credential to update/set
343
+ scope: The scope(s) that this credential covers
344
+ """
345
+ key = (cred.client_id, cred.user_agent, scope)
346
+ self._data[key] = cred
347
+ self._write()
348
+
349
+ def _delete_credential(self, client_id, user_agent, scope):
350
+ """Delete a credential and write the multistore.
351
+
352
+ This must be called when the multistore is locked.
353
+
354
+ Args:
355
+ client_id: The client_id for the credential
356
+ user_agent: The user agent for the credential
357
+ scope: The scope(s) that this credential covers
358
+ """
359
+ key = (client_id, user_agent, scope)
360
+ try:
361
+ del self._data[key]
362
+ except KeyError:
363
+ pass
364
+ self._write()
365
+
366
+ def _get_storage(self, client_id, user_agent, scope):
367
+ """Get a Storage object to get/set a credential.
368
+
369
+ This Storage is a 'view' into the multistore.
370
+
371
+ Args:
372
+ client_id: The client_id for the credential
373
+ user_agent: The user agent for the credential
374
+ scope: A string for the scope(s) being requested
375
+
376
+ Returns:
377
+ A Storage object that can be used to get/set this cred
378
+ """
379
+ return self._Storage(self, client_id, user_agent, scope)