-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathzync.py
1654 lines (1404 loc) · 53.4 KB
/
zync.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Zync Python API
A Python wrapper around the Zync HTTP API.
"""
__version__ = '1.6.4'
import argparse
import errno
import hashlib
import json
import os
import platform
import random
import re
import select
import SocketServer
import sys
import time
import traceback
from urllib import urlencode
from distutils.version import StrictVersion
# Workaround for certain versions of embedded python that don't have argv in sys
# module. The lack of argv in sys manifests in an error in Oauth library:
# Traceback (most recent call last):
# File "/usr/local/lib/python2.7/dist-packages/oauth2client/tools.py", line 83,
# in _CreateArgumentParser
# parser = argparse.ArgumentParser(add_help=False)
# File "/usr/lib/python2.7/argparse.py", line 1575, in __init_zync_
# prog = _os.path.basename(_sys.argv[0])
# AttributeError: 'module' object has no attribute 'argv'
#
if not hasattr(sys, 'argv'):
sys.argv = ['']
import zync_lib.httplib2 as httplib2
import zync_lib.oauth2client as oauth2client
import zync_lib.requests as requests
import zync_lib.yaml as yaml
from zync_lib.requests.adapters import HTTPAdapter
from zync_lib.requests.packages.urllib3.util.retry import Retry
from zync_lib.yaml.constructor import SafeConstructor
# This is a workaround for a problem that appears on CentOS.
# The stacktrace the user gets when trying to login with Google to a plugin is this:
# Traceback (most recent call last):
# File "/usr/local/Nuke9.0v7/plugins/nuke/callbacks.py", line 127, in knobChanged
# _doCallbacks(knobChangeds)
# File "/usr/local/Nuke9.0v7/plugins/nuke/callbacks.py", line 46, in _doCallbacks
# f[0](*f[1],**f[2])
# File "/usr/local/Nuke9.0v7/plugins/nukescripts/panels.py", line 23, in PythonPanelKnobChanged
# widget.knobChangedCallback(nuke.thisKnob())
# File "/usr/local/Nuke9.0v7/plugins/nukescripts/panels.py", line 71, in knobChangedCallback
# self.knobChanged(knob)
# File "/home/shortcut/zync/zync-nuke/zync_nuke.py", line 644, in knobChanged
# self.userLabel.setValue(' %s' % ZYNC.login_with_google())
# File "/home/shortcut/zync/zync-python/zync.py", line 210, in login_with_google
# credentials = oauth2client.tools.run_flow(flow, storage, flags)
# File "/home/shortcut/zync/zync-python/zync_lib/oauth2client/util.py", line 129, in positional_wrapper
# return wrapped(*args, **kwargs)
# File "/home/shortcut/zync/zync-python/zync_lib/oauth2client/tools.py", line 199, in run_flow
# httpd.handle_request()
# File "/usr/local/Nuke9.0v7/lib/python2.7/SocketServer.py", line 265, in handle_request
# fd_sets = select.select([self], [], [], timeout)
# select.error: (4, 'Interrupted system call')
# The cause of that is that both Maya and Nuke have an old version of SocketServer.py that does
# not correctly retry "select" call interrupted by EINTR. So we inject an implementation
# of handle_request() to ClientRedirectServer which does retries.
def _eintr_retry(redirect_server):
"""Call handle_request() from base class, retrying if interrupted by EINTR.
Args:
redirect_server: oauth2client.tools.ClientRedirectServer
"""
while True:
try:
# We cannot call super() here, because ClientRedirectServer inherits
# from an old-style class.
# The full inheritance hierarchy is:
# BaseServer <- TCPServer <- HTTPServer <- ClientRedirectServer
# but the handle_request() method is defined in BaseServer and not
# redefined in subclasses.
return SocketServer.BaseServer.handle_request(redirect_server)
except (OSError, select.error) as e:
if e.args[0] != errno.EINTR:
raise
oauth2client.tools.ClientRedirectServer.handle_request = _eintr_retry
class ZyncAuthenticationError(Exception):
pass
class ZyncError(Exception):
pass
class ZyncConnectionError(Exception):
pass
class ZyncPreflightError(Exception):
pass
current_dir = os.path.dirname(os.path.abspath(__file__))
if os.environ.get('ZYNC_URL'):
ZYNC_URL = os.environ.get('ZYNC_URL')
else:
# FIXME: maintained for backwards compatibility
config_path = os.path.join(current_dir, 'zync_config.py')
if not os.path.exists(config_path):
raise ZyncError('''
Could not locate zync_config.py.
If you use client application for installing plugins select 'Update plugins' in 'Plugins' tab.
If you install Zync plugins manually rename existing config.py file to zync_config.py.
''')
from zync_config import *
required_config = ['ZYNC_URL']
for key in required_config:
if not key in globals():
raise ZyncError('zync_config.py must define a value for %s.' % (key,))
def __get_config_dir():
"""Return the directory in which Zync configuration should be stored.
Varies depending on current system Operating System conventioned.
Returns:
str, absolute path to the Zync config directory
"""
config_dir = os.path.expanduser('~')
if sys.platform == 'win32':
config_dir = os.path.join(config_dir, 'AppData', 'Roaming', 'Zync')
elif sys.platform == 'darwin':
config_dir = os.path.join(config_dir, 'Library', 'Application Support', 'Zync')
else:
config_dir = os.path.join(config_dir, '.zync')
if not os.path.exists(config_dir):
os.makedirs(config_dir)
return config_dir
CLIENT_SECRET = os.path.join(current_dir, 'client_secret.json')
OAUTH2_STORAGE = os.path.join(__get_config_dir(), 'oauth2.dat')
OAUTH2_SCOPES = ['https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/userinfo.email',
'openid email profile']
OCIO_MAP_TAG_NAMES = ["ColorSpace", "ExponentTransform", "FileTransform",
"GroupTransform", "LogTransform", "Look", "LookTransform",
"TruelightTransform", "View", "ColorSpaceTransform",
"CDLTransform", "MatrixTransform", ]
def get_ocio_files(config_file):
"""Return list of dependencies for the given OCIO config file. Note the file
itself is also returned.
:param config_file: str, absolute path to the OCIO config file to parse.
:rtype: list(str), absolute paths of the dependencies.
"""
config_file_path = os.path.abspath(config_file)
result = [config_file_path]
try:
with open(config_file_path) as yaml_file:
yaml_lines = yaml_file.readlines()
yaml_text = ''.join(yaml_lines)
for ocio_map_tag_name in OCIO_MAP_TAG_NAMES:
SafeConstructor.add_constructor(ocio_map_tag_name, SafeConstructor.construct_yaml_map)
parsed_config = yaml.safe_load(yaml_text)
separator = ';' if platform.system() == 'Windows' else ':'
search_paths = parsed_config['search_path'].split(separator)
for search_path in search_paths:
if not os.path.exists(search_path):
# It might be relative path - try prepending the config file path.
search_path = os.path.join(os.path.dirname(config_file_path), search_path)
if os.path.isdir(search_path) and os.path.exists(search_path):
for root, directories, files in os.walk(search_path):
for file in files:
result.append(os.path.join(root, file))
return result
except:
# Do not fail on exception here. OCIO is a complex format and parsing errors are
# possible. User can work around the problem by manually adding OCIO dependencies
# to the job and failing here would make such a workaround impossible.
print("Error parsing %s:\n" % config_file)
traceback.print_exc()
return result
def _encode_obj_utf8(in_obj):
def encode_list(in_list):
out_list = []
for el in in_list:
out_list.append(_encode_obj_utf8(el))
return out_list
def encode_dict(in_dict):
out_dict = {}
for k, v in in_dict.iteritems():
out_dict[k] = _encode_obj_utf8(v)
return out_dict
if isinstance(in_obj, unicode):
return in_obj.encode('utf-8')
elif isinstance(in_obj, list):
return encode_list(in_obj)
elif isinstance(in_obj, tuple):
return tuple(encode_list(in_obj))
elif isinstance(in_obj, dict):
return encode_dict(in_obj)
return in_obj
class HTTPBackend(object):
"""
Methods for talking to services over HTTP.
"""
def __init__(self, timeout=60.0,
disable_ssl_certificate_validation=False,
url=None, access_token=None, email=None):
"""
Args:
timeout: float, timeout limit for HTTP connection in seconds
disable_ssl_certificate_validation: bool, if True, will disable SSL
certificate validation (for Zync integration tests).
url: str, URL to the site, defaults to ZYNC_URL in zync_config.py.
access_token: str, OAuth access token to use for this connection. if not
provided Zync will perform the proper OAuth flow.
email: str, email address to use to authentication this connection. used
in combination with access_token.
"""
if not url:
url = ZYNC_URL
self.url = url
self.timeout = timeout
self.disable_ssl_certificate_validation = disable_ssl_certificate_validation
self.access_token = None
self.email = None
self.externally_provided_access_token = access_token
self.externally_provided_email = email
self.login_with_google(self.externally_provided_access_token,
self.externally_provided_email,
attempts=1)
@staticmethod
def get_http(timeout=60.0,
disable_ssl_certificate_validation=False):
proxy_info = None
if 'HTTP_PROXY_ADDRESS' in globals():
proxy_info = httplib2.ProxyInfo(httplib2.socks.PROXY_TYPE_HTTP,
HTTP_PROXY_ADDRESS,
int(HTTP_PROXY_PORT),
proxy_user=globals().get('HTTP_PROXY_USER'),
proxy_pass=globals().get('HTTP_PROXY_PASSWORD'))
return httplib2.Http(timeout=timeout,
disable_ssl_certificate_validation=disable_ssl_certificate_validation,
proxy_info=proxy_info)
def __get_http(self):
return HTTPBackend.get_http(self.timeout,
disable_ssl_certificate_validation=self.disable_ssl_certificate_validation)
def up(self):
"""
Checks for the site to be available.
"""
http = self.__get_http()
try:
response, _ = http.request(self.url, 'GET')
except httplib2.ServerNotFoundError:
return False
except AttributeError:
return False
else:
status = str(response['status'])
return status.startswith('2') or status.startswith('3')
def set_cookie(self, headers=None):
"""
Adds the auth cookie to the given headers, raises
ZyncAuthenticationError if cookie doesn't exist.
"""
if not headers:
headers = {}
if self.cookie:
headers['Cookie'] = self.cookie
return headers
else:
raise ZyncAuthenticationError('Zync authentication failed.')
def _auth_with_zync(self, access_token, email):
"""Authenticates a valid Google account with the Zync service.
Args:
access_token: String OAuth access token as returned by Google OAuth flow.
email: String email address of the user authenticating.
Returns:
Response cookie from Zync. This cookie should be used for subsequent
requests to the Zync API.
"""
http = self.__get_http()
url = '%s/api/validate' % self.url
args = {
'access_token': access_token,
'email': email,
}
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
response, content = http.request(url, 'POST', urlencode(args), headers=headers)
if response['status'] == '200':
return response['set-cookie']
else:
# Don't save local credentials if it's not a valid Zync account. This also
# frees the user to log in with a different account if they wish.
self._clear_oauth_credentials()
# We use spaces and newlines in the error message because in some contexts
# (e.g. the Maya status bar) newlines are ignored and the message gets
# hard to read.
raise ZyncAuthenticationError(
'Error for user %s logging into site %s. \n\n'
'Your saved Zync credentials will be cleared to allow you to do a fresh login. \n\n'
'Full error message: \n%s\n\n' % (email, self.url, content))
def __google_api(self, api_path, params=None):
"""Make a call to a Google API.
Args:
api_path: str, the API path to call, i.e. the tail of the
URL with no hostname
params: dict, key-value pairs of any parameters to be passed with
the GET request as part of the URL
Returns:
str, the response body
Raises:
ZyncError, if the response contains anything other than a
200 status code.
"""
http = self.__get_http()
headers = {'Authorization': 'OAuth %s' % self.access_token}
url = 'https://www.googleapis.com/%s' % api_path
if params:
url += '?%s' % urlencode(params)
resp, content = http.request(url, 'GET', headers=headers)
if resp.status == 200:
return content
else:
raise ZyncError(content)
def login_with_google(self, access_token=None, email=None, attempts=5,
max_delay=15):
"""Wraps _login_with_google() in additional retrial loop.
If request fails, retry after waiting random time between 1 and
`max_delay` seconds.
"""
for attempt in range(attempts):
try:
if attempt > 0:
time.sleep(1 + random.random() * (max_delay - 1))
return self._login_with_google(access_token, email)
except ZyncAuthenticationError:
exc_info = sys.exc_info()
# no attempt successful, re-raise last exception
raise exc_info[0], exc_info[1], exc_info[2]
def _login_with_google(self, access_token=None, email=None):
"""Performs the Google OAuth flow, which will open the user's browser
for authorization if necessary, then retrieves the user's account info
and authorizes with Zync.
Args:
access_token: str, access token to use for authentication flow. only
necessary if you must perform OAuth manually for some reason; in
most cases this should be left blank so Zync performs the OAuth
flow
email: str, email address to use to authenticate with. used in
combination with access_token. usually blank.
Returns:
str, the user's email address
Raises:
ZyncAuthenticationError if user info is invalid or the login fails
ZyncConnectionError if the Zync site is down
"""
if not self.up():
raise ZyncConnectionError('ZYNC is down at URL: %s' % self.url)
# if auth details were provided, no need to do anything else, just save
# them out. this will make the appropriate call to pass auth details to
# Zync to check that they are valid for that Zync account.
if access_token and email:
cookie = self._auth_with_zync(access_token, email)
self._save_oauth_credentials(access_token, email, cookie)
return email
# otherwise, run the standard OAuth flow
else:
storage = oauth2client.file.Storage(OAUTH2_STORAGE)
credentials = storage.get()
if credentials is None or credentials.invalid:
flow = oauth2client.client.flow_from_clientsecrets(CLIENT_SECRET,
scope=' '.join(OAUTH2_SCOPES))
parser = argparse.ArgumentParser(parents=[oauth2client.tools.argparser])
flags = parser.parse_args([])
# if --noauth_local_webserver was given on the original commandline
# pass it through, this will cause OAuth to display a link with which
# to perform auth, rather than try to open a browser.
if '--noauth_local_webserver' in sys.argv:
flags.noauth_local_webserver = True
credentials = oauth2client.tools.run_flow(flow, storage, flags, http=self.__get_http())
credentials.refresh(self.__get_http())
self.access_token = credentials.access_token
primary_email = self._get_user_email()
if not primary_email:
self.access_token = None
raise ZyncAuthenticationError('Could not locate user email address')
cookie = self._auth_with_zync(credentials.access_token, primary_email)
self._save_oauth_credentials(credentials.access_token, primary_email, cookie)
return primary_email
def _get_user_email(self):
http = self.__get_http()
headers = {'Authorization': 'OAuth %s' % self.access_token}
discovery_url = 'https://accounts.google.com/.well-known/openid-configuration'
resp, content = http.request(discovery_url, 'GET', headers=headers)
if resp.status != 200:
raise ZyncError(content)
openid_info = json.loads(content)
userinfo_url = openid_info.get('userinfo_endpoint')
if not userinfo_url:
raise ZyncError("userinfo endpoint was not found in Google's discovery document")
resp, content = http.request(userinfo_url, 'GET', headers=headers)
if resp.status != 200:
raise ZyncError(content)
return json.loads(content).get('email')
def _save_oauth_credentials(self, access_token, email, cookie):
"""Saves credentials for oauth authentication.
Used by Zync integration tests.
Args:
access_token: str, the OAuth access token.
email: str, email address of the user authenticating with oauth
cookie: Cookie object authenticated against the Zync service, as returned
by _auth_with_zync().
"""
self.access_token = access_token
self.email = email
self.cookie = cookie
def logout(self):
"""Reduce current session back to script-level login."""
self._clear_oauth_credentials()
self.cookie = None
def _clear_oauth_credentials(self):
"""Clear OAuth credentials."""
self.access_token = None
self.email = None
# Remove the saved session from disk, ignore errors if it does not exist
try:
os.remove(OAUTH2_STORAGE)
except OSError as e:
if e.errno != errno.ENOENT:
raise
def has_user_login(self):
"""Check if current session has run the login-with-google flow.
Returns:
bool, True if logged in, False otherwise.
"""
return (self.access_token is not None)
def request(self, url, operation, data=None, headers=None, attempts=5):
"""Wraps _request() in additional authentication and retrial logic.
If request fails with ZyncAuthenticationError, try to log in
and retry up to `attempts` times.
"""
for attempt in range(attempts):
if self.cookie is None:
self.login_with_google(self.externally_provided_access_token,
self.externally_provided_email)
try:
return self._request(url, operation, data, headers)
except ZyncAuthenticationError:
exc_info = sys.exc_info()
# forget credentials
self.access_token = None
self.email = None
self.cookie = None
# no attempt successful, re-raise last exception
raise exc_info[0], exc_info[1], exc_info[2]
def _request(self, url, operation, data=None, headers=None):
"""Former request(); performs requests to Zync site."""
if not data:
data = {}
if not headers:
headers = {}
http = self.__get_http()
headers = self.set_cookie(headers=headers)
headers['X-Zync-Header'] = '1'
if operation == 'GET':
if data:
url += '?%s' % (urlencode(_encode_obj_utf8(data)),)
resp, content = http.request(url, operation, headers=headers)
else:
if 'Content-Type' not in headers:
headers['Content-Type'] = 'application/x-www-form-urlencoded'
if headers['Content-Type'] == 'application/json':
serialized_data = json.dumps(data)
else:
serialized_data = urlencode(_encode_obj_utf8(data))
resp, content = http.request(url, operation, serialized_data, headers=headers)
if resp['status'] == '200':
try:
return json.loads(content)
except ValueError:
return content
# Unfortunately, for historical reasons the login error and some fatal errors
# all return 400 HTTP code. We have to resort to filtering by the message here.
elif resp['status'] == '403' or (resp['status'] == '400' and
('invalid_token' in content or 'Please login' in content)):
raise ZyncAuthenticationError(content)
else:
raise ZyncError('%s: %s: %s' % (url.split('?')[0], resp['status'], content))
class Zync(HTTPBackend):
"""
The entry point to the Zync service. Initialize this with your script name
and token to use most API methods.
"""
def __init__(self, timeout=60.0, application=None,
disable_ssl_certificate_validation=False, url=None,
access_token=None, email=None):
"""
Create a Zync object, for interacting with the Zync service.
Args:
timeout: float, timeout limit for HTTP connection in seconds
application: str, name of the application in use, if any
disable_ssl_certificate_validation: bool, if True, will disable SSL
certificate validation (for Zync integration tests).
url: str, URL to the site, defaults to ZYNC_URL in zync_config.py.
access_token: str, OAuth access token to use for this connection. if not
provided Zync will perform the proper OAuth flow.
email: str, email address to use to authentication this connection. used
in combination with access_token.
"""
super(Zync, self).__init__(
timeout=timeout,
disable_ssl_certificate_validation=disable_ssl_certificate_validation,
url=url, access_token=access_token, email=email)
self.application = application
#
# Initialize class variables by pulling various info from ZYNC.
#
self.CONFIG = self.get_config()
self.INSTANCE_TYPES = self.get_instance_types()
self.FEATURES = self.get_enabled_features()
self.JOB_SUBTYPES = self.get_job_subtypes()
self.PRICING = self.get_pricing()
def get_config(self, var=None):
"""
Get your site's configuration settings. Use the "var" argument to
get a specific value, or leave it out to get all values.
"""
url = '%s/api/config' % self.url
if var is not None:
url += '/%s' % var
result = self.request(url, 'GET')
if var is None:
return result
elif var in result:
return result[var]
else:
return None
def is_experiment_enabled(self, experiment):
"""Checks if experiment is enabled for the side using Zync web API.
Args:
experiment: str, name of the experiment
Returns:
True if experiment is enabled, False otherwise
"""
url = '%s/api/experiment/%s' % (self.url, experiment)
result = self.request(url, 'GET')
return result
def compare_instance_types(self, type_a, type_b):
obj_a = self.INSTANCE_TYPES[type_a]
obj_b = self.INSTANCE_TYPES[type_b]
if 'order' in obj_a and 'order' in obj_b:
return obj_a['order'] - obj_b['order']
elif 'order' in obj_a and 'order' not in obj_b:
return 1
elif 'order' not in obj_a and 'order' in obj_b:
return -1
else:
return 0
def refresh_instance_types_cache(self, renderer=None, usage_tag=None):
"""Refreshes the cached instance types with new usage tag."""
self.INSTANCE_TYPES = self.get_instance_types(renderer=renderer, usage_tag=usage_tag)
def get_instance_types(self, renderer=None, usage_tag=None):
"""Get a list of instance types available to your site.
Args:
renderer: str, name of the renderer, arnold etc.
usage_tag: str, a tag used for filtering instance types.
"""
data = {}
if self.application:
data['job_type'] = self.application
if renderer:
data['renderer'] = renderer
if usage_tag:
data['usage_tag'] = usage_tag
return self.request('%s/api/instance_types' % self.url, 'GET', data=data)
def get_enabled_features(self):
"""
Get a list of enabled features available to your site.
"""
url = '%s/api/features' % (self.url,)
return self.request(url, 'GET')
def get_job_subtypes(self):
"""
Get a list of job subtypes available to your site. This will
typically only be "render" - in the future ZYNC will likely support
other subtypes like Texture Baking, etc.
"""
url = '%s/api/job_subtypes' % (self.url,)
return self.request(url, 'GET')
def get_project_list(self):
"""
Get a list of existing ZYNC projects on your site.
"""
url = '%s/api/projects' % (self.url,)
return self.request(url, 'GET')
def get_project_name(self, file_path):
"""
Takes the name of a file - either a Maya or Nuke script - and returns
the default Zync project name for it.
"""
url = '%s/api/project_name' % (self.url,)
data = {'file': file_path}
return self.request(url, 'GET', data)
def get_jobs(self, max=100):
"""
Returns a list of existing ZYNC jobs.
"""
url = '%s/api/jobs' % (self.url,)
data = {}
if max != None:
data['max'] = max
return self.request(url, 'GET', data)
def get_job_details(self, job_id):
"""
Get a list of a specific job's details.
"""
url = '%s/api/jobs/%d' % (self.url, job_id)
return self.request(url, 'GET')
def submit_job(self, job_type, *args, **kwargs):
"""
Submit a new job to Zync.
"""
#
# Select a Job subclass based on the job_type argument.
#
job_type = job_type.lower()
if job_type == 'nuke':
JobSelect = NukeJob
elif job_type == 'maya':
JobSelect = MayaJob
elif job_type == 'arnold':
JobSelect = ArnoldJob
elif job_type == 'vray':
JobSelect = VrayJob
elif job_type == 'ae':
JobSelect = AEJob
elif job_type == 'houdini':
JobSelect = HoudiniJob
elif job_type == 'c4d':
JobSelect = C4dJob
elif job_type == 'c4d_vray':
JobSelect = C4dVrayJob
elif job_type == '3dsmax':
JobSelect = ThreeDSMaxJob
elif job_type == '3dsmax_vray':
JobSelect = ThreeDSMaxVrayJob
elif job_type == '3dsmax_arnold':
JobSelect = ThreeDSMaxArnoldJob
else:
raise ZyncError('Unrecognized job_type "%s".' % (job_type,))
#
# Initialize the Job subclass.
#
new_job = JobSelect(self)
#
# Run job.preflight(). If preflight does not succeed, an error will be
# thrown, so no need to check output here.
#
new_job.preflight()
#
# Submit the job and return the output of that method.
#
new_job.submit(*args, **kwargs)
return new_job
def list_files(self, prefix_path, recursive=False, max_depth=4):
"""Returns data about files stored in your Zync account.
Params:
prefix: str, path to the directory which content will be listed.
e.g. projects/foo/home/user/scenes/
recursive: bool, whether to go recursively inside subfolders
Returns:
list, A list of structures describing the files tree.
e.g.
[
{
"url": "#",
"rel": "projects/balls3/usr/local",
"is_folder": true,
"name": "local"
"children": {
"url": "#",
"rel": "projects/balls3/usr/local/foo.txt",
"name": "foo.txt"
}
}
]
"""
url = '%s/api/files' % self.url
args = dict(dir=prefix_path, recursive=recursive, max_depth=max_depth)
return self.request(url, 'POST', args)
def generate_file_path(self, file_path):
"""
Returns a hash-embedded scene path for separation from user scenes.
"""
scene_dir, scene_name = os.path.split(file_path)
zync_dir = os.path.join(scene_dir, '__zync')
if not os.path.exists(zync_dir):
os.makedirs(zync_dir)
local_time = time.localtime()
times = [local_time.tm_mon, local_time.tm_mday, local_time.tm_year,
local_time.tm_hour, local_time.tm_min, local_time.tm_sec]
timecode = ''.join(['%02d' % x for x in times])
old_filename, ext = os.path.splitext(scene_name)
to_hash = '_'.join([old_filename, timecode])
hash = hashlib.md5(to_hash).hexdigest()[-6:]
# filename will be something like: shotName_comp_v094_37aa20.nk
new_filename = '_'.join([old_filename, hash]) + ext
return os.path.join(zync_dir, new_filename)
def get_pricing(self):
url = ('https://zync-dot-cloudpricingcalculator.appspot.com' +
'/static/data/pricelist.json')
with get_requests_session() as session:
response = session.get(url)
if response.status_code < 400:
return response.json()
else:
raise requests.HTTPError('Failed to get pricing from, {}. {} - {}'.format(
url, response.status_code, response.reason))
def get_eulas(self):
return self.request('%s/api/eulas' % self.url, 'GET', {})
def get_machine_type_labels(self, renderer):
"""Gets user-visible machine labels sorted in natural order
Params:
renderer: str, renderer
Returns:
str[], list of machine labels
"""
instance_types = sorted(self.INSTANCE_TYPES.keys(), self.compare_instance_types)
machine_type_labels = []
for instance_type in instance_types:
machine_type_labels.append(self.machine_type_to_label(instance_type, renderer))
return machine_type_labels
def machine_type_to_label(self, machine_type, renderer):
"""Gets the user-visible label for a given machine type.
Args:
machine_type: str, machine type name
renderer: str, renderer
Returns:
str, user-visible label
"""
type_properties = self.INSTANCE_TYPES.get(machine_type)
if not type_properties:
return machine_type
label = '%s (%s)' % (machine_type, type_properties.get('description', '').replace(', preemptible',''))
if renderer:
machine_type_price = self.get_machine_type_price(machine_type, renderer)
if machine_type_price:
label += ' $%.02f' % machine_type_price
return label
def machine_type_from_label(self, instance_label, renderer):
"""Given user-visible label returns machine type.
Example:
'zync-64vcpu-128gb (64 core, 128GB RAM) $4.21' returns
'zync-64vcpu-128gb'
'(PREEMPTIBLE) zync-64vcpu-128gb (64 core, 128GB RAM) $4.21' returns
'(PREEMPTIBLE) zync-64vcpu-128gb'
Args:
instance_label: str, user-visible label
Returns;
str, the machine type name, or None if label was empty
"""
for machine_type in self.INSTANCE_TYPES:
current_label = self.machine_type_to_label(machine_type, renderer)
if current_label == instance_label:
return machine_type
return None
def get_machine_type_price(self, machine_type, renderer):
"""Gets pricing for the given machine type.
Args:
machine_type: str, machine type name
renderer: str, renderer
Returns:
float, pricing for machine type + renderer combination, or
None if pricing is unknown
"""
types = [
{
# standard CPU based machine
'pattern': re.compile(r'^zync-\d+vcpu-\d+gb$'),
'field_name': lambda match: 'CP-ZYNC-%s-%s' % (match.group(0).upper(), renderer.upper())
},
{
# preemptible CPU based machine
'pattern': re.compile(r'^\(PREEMPTIBLE\) (zync-\d+vcpu-\d+gb)$'),
'field_name': lambda match: 'CP-ZYNC-%s-%s-PREEMPTIBLE' % (match.group(1).upper(), renderer.upper())
},
{
# P100 GPU based machine
'pattern': re.compile(r'^zync-(\d+vcpu-\d+gb) \((\d+) Tesla (.*)\)$'),
'field_name': lambda match: 'CP-ZYNC-ZYNC-%(cpu)s-%(gpu)sGPU-%(gpu_type)s-%(renderer)s' %
dict(cpu=match.group(1).upper(), gpu=match.group(2),
gpu_type=match.group(3), renderer=renderer.upper())
},
{
# preemptible P100 GPU based machine
'pattern': re.compile(r'^\(PREEMPTIBLE\) zync-(\d+vcpu-\d+gb) \((\d+) Tesla (.*)\)$'),
'field_name': lambda match: 'CP-ZYNC-ZYNC-%(cpu)s-%(gpu)sGPU-%(gpu_type)s-%(renderer)s-PREEMPTIBLE' %
dict(cpu=match.group(1).upper(), gpu=match.group(2),
gpu_type=match.group(3), renderer=renderer.upper())
}
]
for type in types:
match = type['pattern'].match(machine_type)
if match:
field_name = type['field_name'](match)
break
else:
return None
if (field_name in self.PRICING['gcp_price_list'] and
'us' in self.PRICING['gcp_price_list'][field_name]):
return float(self.PRICING['gcp_price_list'][field_name]['us'])
return None
def check_software(self, software_spec):
"""Returns software version that will be used by zync to render the provided versions.
Example of software_spec:
{'host': {'name': 'maya', 'version': '2018'}, 'plugins': [{'name':
'vray','version': '3.6'}]}
Args:
software_spec: dict, has to contain host and optionally a list of plugins.
Returns: (bool, str), whether th software is supported and a pretty name of
package that will be used.
"""
url = '%s/api/software_versions:check' % self.url
data = software_spec
headers = {'Content-Type': 'application/json'}
result = self.request(url, 'POST', data, headers=headers)
return result['supported'], result['pretty_name']
class Job(object):
"""
Zync Job main class.
"""
def __init__(self, zync):
"""
The base Zync Job object, not useful on its own, but should be
the parent for application-specific Job implementations.
"""
self.zync = zync
self.id = None
self.job_type = None
def _check_id(self):
if self.id == None:
raise ZyncError('This Job hasn\'t been initialized with an ID, ' +
'yet, so this method is unavailable.')
def details(self):
"""
Returns a dictionary of the job details.
"""
self._check_id()
url = '%s/api/jobs/%d' % (self.zync.url, self.id)
return self.zync.request(url, 'GET')
def set_status(self, status):
"""
Sets the job status for the given job. This is the method by which most
job controls are initiated.
"""
self._check_id()
url = '%s/api/jobs/%d' % (self.zync.url, int(self.id))
data = {'status': status}
return self.zync.request(url, 'POST', data)
def cancel(self):
"""
Cancels the given job.
"""
return self.set_status('canceled')
def resume(self):
"""
Resumes the given job.
"""
return self.set_status('resume')
def pause(self):
"""
Pauses the given job.
"""
return self.set_status('paused')
def unpause(self):
"""