Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

api.py 30 KB

You have to be logged in to leave a comment. Sign In
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
  1. from gql import Client, gql
  2. from gql.client import RetryError
  3. from gql.transport.requests import RequestsHTTPTransport
  4. import os
  5. import requests
  6. import ast
  7. from six.moves import configparser
  8. from functools import wraps
  9. import logging
  10. import hashlib
  11. import os
  12. import json
  13. import yaml
  14. from wandb import __version__, __stage_dir__, GitRepo
  15. from wandb import util
  16. from base64 import b64encode
  17. import binascii
  18. import click
  19. import collections
  20. import itertools
  21. import logging
  22. import requests
  23. from six.moves import queue
  24. import threading
  25. import time
  26. logger = logging.getLogger(__name__)
  27. def IDENTITY(monitor):
  28. """A default callback for the Progress helper"""
  29. return monitor
  30. class Progress(object):
  31. """A helper class for displaying progress"""
  32. def __init__(self, file, callback=None):
  33. self.file = file
  34. self.callback = callback or IDENTITY
  35. self.bytes_read = 0
  36. self.len = os.fstat(file.fileno()).st_size
  37. def read(self, size=-1):
  38. """Read bytes and call the callback"""
  39. bites = self.file.read(size)
  40. self.bytes_read += len(bites)
  41. self.callback(len(bites))
  42. return bites
  43. class Error(Exception):
  44. """Base W&B Error"""
  45. # For python 2 support
  46. def encode(self, encoding):
  47. return self.message
  48. class CommError(Error):
  49. """Error communicating with W&B"""
  50. pass
  51. class UsageError(Error):
  52. """API Usage Error"""
  53. pass
  54. def normalize_exceptions(func):
  55. """Function decorator for catching common errors and re-raising as wandb.Error"""
  56. @wraps(func)
  57. def wrapper(*args, **kwargs):
  58. message = "Whoa, you found a bug."
  59. try:
  60. return func(*args, **kwargs)
  61. except requests.HTTPError as err:
  62. raise CommError(err.response)
  63. except RetryError as err:
  64. if "response" in dir(err.last_exception) and err.last_exception.response is not None:
  65. message = err.last_exception.response.json().get(
  66. 'errors', [{'message': message}])[0]['message']
  67. else:
  68. message = err.last_exception
  69. raise CommError(message)
  70. except Exception as err:
  71. # gql raises server errors with dict's as strings...
  72. payload = err.args[0]
  73. if str(payload).startswith("{"):
  74. message = ast.literal_eval(str(payload))["message"]
  75. else:
  76. message = str(err)
  77. if os.getenv("DEBUG") == "true":
  78. raise err
  79. else:
  80. raise CommError(message)
  81. return wrapper
  82. class Api(object):
  83. """W&B Api wrapper
  84. Note:
  85. Settings are automatically overridden by looking for
  86. a `wandb/settings` file in the current working directory or it's parent
  87. directory. If none can be found, we look in the current users home
  88. directory.
  89. Args:
  90. default_settings(:obj:`dict`, optional): If you aren't using a settings
  91. file or you wish to override the section to use in the settings file
  92. Override the settings here.
  93. """
  94. def __init__(self, default_settings=None, load_settings=True):
  95. self.default_settings = {
  96. 'section': "default",
  97. 'entity': "models",
  98. 'run': "latest",
  99. 'git_remote': "origin",
  100. 'git_tag': False,
  101. 'base_url': "https://api.wandb.ai"
  102. }
  103. self.default_settings.update(default_settings or {})
  104. self._settings = None
  105. self.retries = 3
  106. self._settings_parser = configparser.ConfigParser()
  107. self.tagged = False
  108. if load_settings:
  109. potential_settings_paths = [
  110. os.path.expanduser('~/.wandb/settings')
  111. ]
  112. if __stage_dir__ is not None:
  113. potential_settings_paths.append(
  114. os.path.join(os.getcwd(), __stage_dir__, 'settings'))
  115. files=self._settings_parser.read(potential_settings_paths)
  116. self.settings_file=files[0] if len(files) > 0 else "Not found"
  117. else:
  118. self.settings_file="Not found"
  119. self.git=GitRepo(remote = self.settings("git_remote"))
  120. self._commit=self.git.last_commit
  121. if self.git.dirty:
  122. self.git.repo.git.execute(['git', 'diff'], output_stream = open(
  123. __stage_dir__ + 'diff.patch', 'wb'))
  124. self.client=Client(
  125. retries = self.retries,
  126. transport = RequestsHTTPTransport(
  127. headers={'User-Agent': self.user_agent},
  128. use_json=True,
  129. auth=("api", self.api_key),
  130. url='%s/graphql' % self.settings('base_url')
  131. )
  132. )
  133. self._current_run=None
  134. self._file_stream_api=None
  135. def set_current_run(self, run_id):
  136. self._current_run=run_id
  137. @property
  138. def current_run(self):
  139. return self._current_run
  140. @property
  141. def user_agent(self):
  142. return 'W&B Client %s' % __version__
  143. @property
  144. def api_key(self):
  145. auth=requests.utils.get_netrc_auth(self.settings()['base_url'])
  146. if auth:
  147. key=auth[-1]
  148. else:
  149. key=os.environ.get("WANDB_API_KEY")
  150. return key
  151. def settings(self, key = None, section = None):
  152. """The settings overridden from the wandb/settings file.
  153. Args:
  154. key (str, optional): If provided only this setting is returned
  155. section (str, optional): If provided this section of the setting file is
  156. used, defaults to "default"
  157. Returns:
  158. A dict with the current settings
  159. {
  160. "entity": "models",
  161. "base_url": "https://api.wandb.ai",
  162. "project": None
  163. }
  164. """
  165. if not self._settings:
  166. self._settings=self.default_settings.copy()
  167. section=section or self._settings['section']
  168. try:
  169. if section in self._settings_parser.sections():
  170. for option in self._settings_parser.options(section):
  171. self._settings[option]=self._settings_parser.get(
  172. section, option)
  173. except configparser.InterpolationSyntaxError:
  174. print("WARNING: Unable to parse settings file")
  175. self._settings["project"]=self._settings.get(
  176. "project", os.environ.get("WANDB_PROJECT"))
  177. self._settings["entity"] = self._settings.get(
  178. "entity", os.environ.get("WANDB_ENTITY"))
  179. self._settings["base_url"] = self._settings.get(
  180. "base_url", os.environ.get("WANDB_BASE_URL"))
  181. return self._settings if key is None else self._settings[key]
  182. def parse_slug(self, slug, project=None, run=None):
  183. if slug and "/" in slug:
  184. parts = slug.split("/")
  185. project = parts[0]
  186. run = parts[1]
  187. else:
  188. project = project or self.settings().get("project")
  189. if project is None:
  190. raise CommError("No default project configured.")
  191. run = run or slug or os.environ.get("WANDB_RUN")
  192. if run is None:
  193. run = "latest"
  194. return (project, run)
  195. @normalize_exceptions
  196. def viewer(self):
  197. query = gql('''
  198. query Viewer{
  199. viewer {
  200. id
  201. entity
  202. }
  203. }
  204. ''')
  205. return self.client.execute(query).get('viewer') or {}
  206. @normalize_exceptions
  207. def list_projects(self, entity=None):
  208. """Lists projects in W&B scoped by entity.
  209. Args:
  210. entity (str, optional): The entity to scope this project to. Defaults to public models
  211. Returns:
  212. [{"id","name","description"}]
  213. """
  214. query = gql('''
  215. query Models($entity: String!) {
  216. models(first: 10, entityName: $entity) {
  217. edges {
  218. node {
  219. id
  220. name
  221. description
  222. }
  223. }
  224. }
  225. }
  226. ''')
  227. return self._flatten_edges(self.client.execute(query, variable_values={
  228. 'entity': entity or self.settings('entity')})['models'])
  229. @normalize_exceptions
  230. def list_runs(self, project, entity=None):
  231. """Lists runs in W&B scoped by project.
  232. Args:
  233. project (str): The project to scope the runs to
  234. entity (str, optional): The entity to scope this project to. Defaults to public models
  235. Returns:
  236. [{"id",name","description"}]
  237. """
  238. query = gql('''
  239. query Buckets($model: String!, $entity: String!) {
  240. model(name: $model, entityName: $entity) {
  241. buckets(first: 10) {
  242. edges {
  243. node {
  244. id
  245. name
  246. description
  247. }
  248. }
  249. }
  250. }
  251. }
  252. ''')
  253. return self._flatten_edges(self.client.execute(query, variable_values={
  254. 'entity': entity or self.settings('entity'),
  255. 'model': project or self.settings('project')})['model']['buckets'])
  256. @normalize_exceptions
  257. def run_config(self, project, run=None, entity=None):
  258. """Get the config for a run
  259. Args:
  260. project (str): The project to download, (can include bucket)
  261. run (str, optional): The run to download
  262. entity (str, optional): The entity to scope this project to.
  263. """
  264. query = gql('''
  265. query Model($name: String!, $entity: String!, $run: String!) {
  266. model(name: $name, entityName: $entity) {
  267. bucket(name: $run) {
  268. config
  269. commit
  270. patch
  271. }
  272. }
  273. }
  274. ''')
  275. response = self.client.execute(query, variable_values={
  276. 'name': project, 'bucket': run, 'entity': entity
  277. })
  278. run = response['model']['bucket']
  279. commit = run['commit']
  280. patch = run['patch']
  281. config = json.loads(run['config'] or '{}')
  282. return (commit, config, patch)
  283. @normalize_exceptions
  284. def upsert_project(self, project, id=None, description=None, entity=None):
  285. """Create a new project
  286. Args:
  287. project (str): The project to create
  288. description (str, optional): A description of this project
  289. entity (str, optional): The entity to scope this project to.
  290. """
  291. mutation = gql('''
  292. mutation UpsertModel($name: String!, $id: String, $entity: String!, $description: String, $repo: String) {
  293. upsertModel(input: { id: $id, name: $name, entityName: $entity, description: $description, repo: $repo }) {
  294. model {
  295. name
  296. description
  297. }
  298. }
  299. }
  300. ''')
  301. response = self.client.execute(mutation, variable_values={
  302. 'name': project, 'entity': entity or self.settings('entity'),
  303. 'description': description, 'repo': self.git.remote_url, 'id': id})
  304. return response['upsertModel']['model']
  305. #@normalize_exceptions
  306. def upsert_run(self, id=None, name=None, project=None, host=None, config=None, description=None, entity=None, commit=None):
  307. """Update a run
  308. Args:
  309. id (str, optional): The existing run to update
  310. name (str, optional): The name of the run to create
  311. project (str, optional): The name of the project
  312. config (dict, optional): The latest config params
  313. description (str, optional): A description of this project
  314. entity (str, optional): The entity to scope this project to.
  315. commit (str, optional): The Git SHA to associate the run with
  316. """
  317. mutation = gql('''
  318. mutation UpsertBucket(
  319. $id: String, $name: String,
  320. $project: String,
  321. $entity: String!,
  322. $description: String,
  323. $commit: String,
  324. $config: JSONString,
  325. $host: String,
  326. $debug: Boolean
  327. ) {
  328. upsertBucket(input: {
  329. id: $id, name: $name,
  330. modelName: $project,
  331. entityName: $entity,
  332. description: $description,
  333. config: $config,
  334. commit: $commit,
  335. host: $host,
  336. debug: $debug
  337. }) {
  338. bucket {
  339. name
  340. description
  341. config
  342. }
  343. }
  344. }
  345. ''')
  346. if config is not None:
  347. config = json.dumps(config)
  348. if not description:
  349. description = None
  350. response = self.client.execute(mutation, variable_values={
  351. 'id': id, 'entity': entity or self.settings('entity'), 'name': name, 'project': project,
  352. 'description': description, 'config': config, 'commit': commit or self._commit,
  353. 'host': host, 'debug': os.getenv('DEBUG')})
  354. return response['upsertBucket']['bucket']
  355. @normalize_exceptions
  356. def upload_urls(self, project, files, run=None, entity=None, description=None):
  357. """Generate temporary resumeable upload urls
  358. Args:
  359. project (str): The project to download
  360. files (list or dict): The filenames to upload
  361. run (str, optional): The run to upload to
  362. entity (str, optional): The entity to scope this project to. Defaults to wandb models
  363. Returns:
  364. (bucket_id, file_info)
  365. bucket_id: id of bucket we uploaded to
  366. file_info: A dict of filenames and urls, also indicates if this revision already has uploaded files.
  367. {
  368. 'weights.h5': { "url": "https://weights.url" },
  369. 'model.json': { "url": "https://model.json", "updatedAt": '2013-04-26T22:22:23.832Z', 'md5': 'mZFLkyvTelC5g8XnyQrpOw==' },
  370. }
  371. """
  372. query = gql('''
  373. query Model($name: String!, $files: [String]!, $entity: String!, $run: String!, $description: String) {
  374. model(name: $name, entityName: $entity) {
  375. bucket(name: $run, desc: $description) {
  376. id
  377. files(names: $files) {
  378. edges {
  379. node {
  380. name
  381. url(upload: true)
  382. updatedAt
  383. }
  384. }
  385. }
  386. }
  387. }
  388. }
  389. ''')
  390. query_result = self.client.execute(query, variable_values={
  391. 'name': project, 'run': run or self.settings('run'),
  392. 'entity': entity or self.settings('entity'),
  393. 'description': description,
  394. 'files': [file for file in files]
  395. })
  396. run = query_result['model']['bucket']
  397. result = {file['name']
  398. : file for file in self._flatten_edges(run['files'])}
  399. return run['id'], result
  400. @normalize_exceptions
  401. def download_urls(self, project, run=None, entity=None):
  402. """Generate download urls
  403. Args:
  404. project (str): The project to download
  405. run (str, optional): The run to upload to
  406. entity (str, optional): The entity to scope this project to. Defaults to wandb models
  407. Returns:
  408. A dict of extensions and urls
  409. {
  410. 'weights.h5': { "url": "https://weights.url", "updatedAt": '2013-04-26T22:22:23.832Z', 'md5': 'mZFLkyvTelC5g8XnyQrpOw==' },
  411. 'model.json': { "url": "https://model.url", "updatedAt": '2013-04-26T22:22:23.832Z', 'md5': 'mZFLkyvTelC5g8XnyQrpOw==' }
  412. }
  413. """
  414. query = gql('''
  415. query Model($name: String!, $entity: String!, $run: String!) {
  416. model(name: $name, entityName: $entity) {
  417. bucket(name: $run) {
  418. files {
  419. edges {
  420. node {
  421. name
  422. url
  423. md5
  424. updatedAt
  425. }
  426. }
  427. }
  428. }
  429. }
  430. }
  431. ''')
  432. query_result = self.client.execute(query, variable_values={
  433. 'name': project, 'run': run or self.settings('run'),
  434. 'entity': entity or self.settings('entity')})
  435. files = self._flatten_edges(query_result['model']['bucket']['files'])
  436. return {file['name']: file for file in files}
  437. @normalize_exceptions
  438. def download_file(self, url):
  439. """Initiate a streaming download
  440. Args:
  441. url (str): The url to download
  442. Returns:
  443. A tuple of the content length and the streaming response
  444. """
  445. response = requests.get(url, stream=True)
  446. response.raise_for_status()
  447. return (int(response.headers.get('content-length', 0)), response)
  448. @normalize_exceptions
  449. def upload_file(self, url, file, callback=None):
  450. """Uploads a file to W&B with failure resumption
  451. Args:
  452. url (str): The url to download
  453. file (str): The path to the file you want to upload
  454. callback (:obj:`func`, optional): A callback which is passed the number of
  455. bytes uploaded since the last time it was called, used to report progress
  456. Returns:
  457. The requests library response object
  458. """
  459. attempts = 0
  460. extra_headers = {}
  461. if os.stat(file.name).st_size == 0:
  462. raise CommError("%s is an empty file" % file.name)
  463. while attempts < self.retries:
  464. try:
  465. progress = Progress(file, callback=callback)
  466. response = requests.put(
  467. url, data=progress, headers=extra_headers)
  468. response.raise_for_status()
  469. break
  470. except requests.exceptions.RequestException as e:
  471. total = progress.len
  472. status = self._status_request(url, total)
  473. if status.status_code == 308:
  474. attempts += 1
  475. completed = int(status.headers['Range'].split("-")[-1])
  476. extra_headers = {
  477. 'Content-Range': 'bytes {completed}-{total}/{total}'.format(
  478. completed=completed,
  479. total=total
  480. ),
  481. 'Content-Length': str(total - completed)
  482. }
  483. else:
  484. raise e
  485. return response
  486. @property
  487. def latest_config(self):
  488. "The latest config parameters trained on"
  489. if os.path.exists(__stage_dir__ + 'latest.yaml'):
  490. config = yaml.load(open(__stage_dir__ + 'latest.yaml'))
  491. del config['wandb_version']
  492. return config
  493. def _md5(self, fname):
  494. hash_md5 = hashlib.md5()
  495. with open(fname, "rb") as f:
  496. for chunk in iter(lambda: f.read(4096), b""):
  497. hash_md5.update(chunk)
  498. return b64encode(hash_md5.digest()).decode('ascii')
  499. def file_current(self, fname, md5):
  500. """Checksum a file and compare the md5 with the known md5
  501. """
  502. return os.path.isfile(fname) and self._md5(fname) == md5
  503. @normalize_exceptions
  504. def pull(self, project, run=None, entity=None):
  505. """Download files from W&B
  506. Args:
  507. project (str): The project to download
  508. run (str, optional): The run to upload to
  509. entity (str, optional): The entity to scope this project to. Defaults to wandb models
  510. Returns:
  511. The requests library response object
  512. """
  513. project, run = self.parse_slug(project, run=run)
  514. urls = self.download_urls(project, run, entity)
  515. responses = []
  516. for fileName in urls:
  517. if self.file_current(fileName, urls[fileName]['md5']):
  518. continue
  519. with open(fileName, "wb") as file:
  520. size, res = self.download_file(urls[fileName]['url'])
  521. responses.append(res)
  522. for data in res.iter_content():
  523. file.write(data)
  524. return responses
  525. @normalize_exceptions
  526. def push(self, project, files, run=None, entity=None, description=None, force=True, progress=False):
  527. """Uploads multiple files to W&B
  528. Args:
  529. project (str): The project to upload to
  530. files (list or dict): The filenames to upload
  531. run (str, optional): The run to upload to
  532. entity (str, optional): The entity to scope this project to. Defaults to wandb models
  533. description (str, optional): The description of the changes
  534. force (bool, optional): Whether to prevent push if git has uncommitted changes
  535. Returns:
  536. The requests library response object
  537. """
  538. project, run = self.parse_slug(project, run=run)
  539. # Only tag if enabled
  540. if self.settings("git_tag"):
  541. self.tag_and_push(run, description, force)
  542. run_id, result = self.upload_urls(
  543. project, files, run, entity, description)
  544. responses = []
  545. for file_name, file_info in result.items():
  546. try:
  547. open_file = files[file_name] if isinstance(
  548. files, dict) else open(file_name, "rb")
  549. except IOError:
  550. print("%s does not exist" % file_name)
  551. continue
  552. if progress:
  553. length = os.fstat(open_file.fileno()).st_size
  554. with click.progressbar(file=progress, length=length, label='Uploading file: %s' % (file_name),
  555. fill_char=click.style('&', fg='green')) as bar:
  556. self.upload_file(
  557. file_info['url'], open_file, lambda bites: bar.update(bites))
  558. else:
  559. responses.append(self.upload_file(file_info['url'], open_file))
  560. open_file.close()
  561. if self.latest_config:
  562. self.upsert_run(id=run_id, description=description,
  563. entity=entity, config=self.latest_config)
  564. return responses
  565. def get_file_stream_api(self):
  566. if not self._file_stream_api:
  567. settings = self.settings()
  568. if self._current_run is None:
  569. raise UsageError(
  570. 'Must have a current run to use file stream API.')
  571. self._file_stream_api = FileStreamApi(
  572. self.api_key, self.user_agent, settings['base_url'],
  573. settings['entity'], settings['project'], self._current_run)
  574. return self._file_stream_api
  575. def tag_and_push(self, name, description, force=True):
  576. if self.git.enabled and not self.tagged:
  577. self.tagged = True
  578. # TODO: this is getting called twice...
  579. print("Tagging your git repo...")
  580. if not force and self.git.dirty:
  581. raise CommError(
  582. "You have un-committed changes. Use the force flag or commit your changes.")
  583. elif self.git.dirty and os.path.exists(__stage_dir__):
  584. self.git.repo.git.execute(['git', 'diff'], output_stream=open(
  585. os.path.join(__stage_dir__, 'diff.patch'), 'wb'))
  586. self.git.tag(name, description)
  587. result = self.git.push(name)
  588. if(result is None or len(result) is None):
  589. print("Unable to push git tag.")
  590. def _status_request(self, url, length):
  591. """Ask google how much we've uploaded"""
  592. return requests.put(
  593. url=url,
  594. headers={'Content-Length': '0',
  595. 'Content-Range': 'bytes */%i' % length}
  596. )
  597. def _flatten_edges(self, response):
  598. """Return an array from the nested graphql relay structure"""
  599. return [node['node'] for node in response['edges']]
  600. Chunk = collections.namedtuple('Chunk', ('filename', 'data'))
  601. class DefaultFilePolicy(object):
  602. def __init__(self):
  603. self._chunk_id = 0
  604. def process_chunks(self, chunks):
  605. chunk_id = self._chunk_id
  606. self._chunk_id += len(chunks)
  607. return {
  608. 'offset': chunk_id,
  609. 'content': [c.data for c in chunks]
  610. }
  611. class CRDedupeFilePolicy(object):
  612. def __init__(self):
  613. self._chunk_id = 0
  614. def process_chunks(self, chunks):
  615. content = []
  616. for line in [c.data for c in chunks]:
  617. if content and content[-1].endswith('\r'):
  618. content[-1] = line
  619. else:
  620. content.append(line)
  621. chunk_id = self._chunk_id
  622. self._chunk_id += len(content)
  623. if content and content[-1].endswith('\r'):
  624. self._chunk_id -= 1
  625. return {
  626. 'offset': chunk_id,
  627. 'content': content
  628. }
  629. class FileStreamApi(object):
  630. """Pushes chunks of files to our streaming endpoint.
  631. This class is used as a singleton. It has a thread that serializes access to
  632. the streaming endpoint and performs rate-limiting and batching.
  633. TODO: Differentiate between binary/text encoding.
  634. """
  635. Finish = collections.namedtuple('Finish', ('failed'))
  636. HTTP_TIMEOUT = 10
  637. RATE_LIMIT_SECONDS = 1
  638. HEARTBEAT_INTERVAL_SECONDS = 15
  639. MAX_ITEMS_PER_PUSH = 10000
  640. def __init__(self, api_key, user_agent, base_url, entity, project, run_id):
  641. self._endpoint = "{base}/{entity}/{project}/{run}/file_stream".format(
  642. base=base_url,
  643. entity=entity,
  644. project=project,
  645. run=run_id)
  646. self._client = requests.Session()
  647. self._client.auth = ('api', api_key)
  648. self._client.timeout = self.HTTP_TIMEOUT
  649. self._client.headers.update({
  650. 'User-Agent': user_agent,
  651. })
  652. self._file_policies = {}
  653. self._queue = queue.Queue()
  654. self._thread = threading.Thread(target=self._thread_body)
  655. # It seems we need to make this a daemon thread to get sync.py's atexit handler to run, which
  656. # cleans this thread up.
  657. self._thread.daemon = True
  658. self._thread.start()
  659. def add_file_policy(self, filename, file_policy):
  660. self._file_policies[filename] = file_policy
  661. def _read_queue(self):
  662. # called from the push thread (_thread_body), this does an initial read
  663. # that'll block for up to RATE_LIMIT_SECONDS. Then it tries to read
  664. # as much out of the queue as it can. We do this because the http post
  665. # to the server happens within _thread_body, and can take longer than
  666. # our rate limit. So next time we get a chance to read the queue we want
  667. # read all the stuff that queue'd up since last time.
  668. #
  669. # If we have more than MAX_ITEMS_PER_PUSH in the queue then the push thread
  670. # will get behind and data will buffer up in the queue.
  671. try:
  672. item = self._queue.get(True, self.RATE_LIMIT_SECONDS)
  673. except queue.Empty:
  674. return []
  675. items = [item]
  676. for i in range(self.MAX_ITEMS_PER_PUSH):
  677. try:
  678. item = self._queue.get_nowait()
  679. except queue.Empty:
  680. return items
  681. items.append(item)
  682. return items
  683. def _thread_body(self):
  684. posted_data_time = time.time()
  685. posted_anything_time = time.time()
  686. ready_chunks = []
  687. finished = None
  688. while finished is None:
  689. items = self._read_queue()
  690. for item in items:
  691. if isinstance(item, self.Finish):
  692. finished = item
  693. else:
  694. # item is Chunk
  695. ready_chunks.append(item)
  696. cur_time = time.time()
  697. if ready_chunks and cur_time - posted_data_time > self.RATE_LIMIT_SECONDS:
  698. posted_data_time = cur_time
  699. posted_anything_time = cur_time
  700. self._send(ready_chunks)
  701. ready_chunks = []
  702. if cur_time - posted_anything_time > self.HEARTBEAT_INTERVAL_SECONDS:
  703. logger.debug("Sending heartbeat at %s", cur_time)
  704. posted_anything_time = cur_time
  705. util.request_with_retry(self._client.post,
  706. self._endpoint, json={'complete': False, 'failed': False})
  707. # post the final close message. (item is self.Finish instance now)
  708. util.request_with_retry(self._client.post,
  709. self._endpoint, json={'complete': True, 'failed': bool(finished.failed)})
  710. def _send(self, chunks):
  711. # create files dict. dict of <filename: chunks> pairs where chunks is a list of
  712. # [chunk_id, chunk_data] tuples (as lists since this will be json).
  713. files = {}
  714. for filename, file_chunks in itertools.groupby(chunks, lambda c: c.filename):
  715. file_chunks = list(file_chunks) # groupby returns iterator
  716. policy = self._file_policies.get(filename)
  717. if policy is None:
  718. policy = CRDedupeFilePolicy()
  719. self._file_policies[filename] = policy
  720. files[filename] = policy.process_chunks(file_chunks)
  721. util.request_with_retry(
  722. self._client.post, self._endpoint, json={'files': files})
  723. def push(self, filename, data):
  724. """Push a chunk of a file to the streaming endpoint.
  725. Args:
  726. filename: Name of file that this is a chunk of.
  727. chunk_id: TODO: change to 'offset'
  728. chunk: File data.
  729. """
  730. self._queue.put(Chunk(filename, data))
  731. def finish(self, failed):
  732. """Cleans up.
  733. Anything pushed after finish will be dropped.
  734. Args:
  735. failed: Set True to to display run failure in UI.
  736. """
  737. self._queue.put(self.Finish(failed))
  738. self._thread.join()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...