-
Notifications
You must be signed in to change notification settings - Fork 3
/
fabfile.py
1352 lines (1075 loc) · 36.4 KB
/
fabfile.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
from __future__ import print_function, unicode_literals, absolute_import
from fabric.api import (
local,
lcd,
run,
sudo,
cd,
prompt,
get,
put,
hosts,
settings,
task,
)
from fabric.utils import abort
from fabric.state import env
from fabric.contrib import files
import datetime
import sys
import os
import codecs
import yaml
import time
import requests
import webbrowser
import datetime
import pkg_resources
from io import StringIO, BytesIO, TextIOWrapper
def env_from_yaml(path):
import yaml
with codecs.open(path, errors="replace") as f:
data = yaml.safe_load(f)
if not isinstance(data, dict):
abort(
"YAML file at {} doesn't contain a dictionary, can't use that for setting env"
)
for key, value in data.items():
setattr(env, key, value)
env_from_yaml("./fabfile.yaml")
env.disable_known_hosts = True
env.no_keys = True
env.target = os.environ.get("TARGET", None)
env.tag = os.environ.get("TAG", None)
env.rpi_user = os.environ.get("RPI_USER", env.rpi_user)
def dict_merge(a, b, leaf_merger=None):
"""
Recursively deep-merges two dictionaries.
Taken from https://www.xormedia.com/recursively-merge-dictionaries-in-python/
Arguments:
a (dict): The dictionary to merge ``b`` into
b (dict): The dictionary to merge into ``a``
leaf_merger (callable): An optional callable to use to merge leaves (non-dict values)
Returns:
dict: ``b`` deep-merged into ``a``
"""
from copy import deepcopy
if a is None:
a = dict()
if b is None:
b = dict()
if not isinstance(b, dict):
return b
result = deepcopy(a)
for k, v in b.items():
if k in result and isinstance(result[k], dict):
result[k] = dict_merge(result[k], v, leaf_merger=leaf_merger)
else:
merged = None
if k in result and callable(leaf_merger):
try:
merged = leaf_merger(result[k], v)
except ValueError:
# can't be merged by leaf merger
pass
if merged is None:
merged = deepcopy(v)
result[k] = merged
return result
def normalize_version(version):
if "-" in version:
version = version[: version.find("-")]
# Debian has the python version set to 2.7.15+ which is not PEP440 compliant (bug 914072)
if version.endswith("+"):
version = version[:-1]
if version[0].lower() == "v":
version = version[1:]
return version.strip()
def get_comparable_version(version_string, cut=None, **kwargs):
"""
Args:
version_string: The version string for which to create a comparable version instance
cut: optional, how many version digits to remove (e.g., cut=1 will turn 1.2.3 into 1.2).
Defaults to ``None``, meaning no further action. Settings this to 0 will remove
anything up to the last digit, e.g. dev or rc information.
Returns:
A comparable version
"""
if "base" in kwargs and kwargs.get("base", False) and cut is None:
cut = 0
if cut is not None and (cut < 0 or not isinstance(cut, int)):
raise ValueError("level must be a positive integer")
version_string = normalize_version(version_string)
version = pkg_resources.parse_version(version_string)
if cut is not None:
# new setuptools
version = pkg_resources.parse_version(version.base_version)
if cut is not None:
parts = version.base_version.split(".")
if 0 < cut < len(parts):
reduced = parts[:-cut]
version = pkg_resources.parse_version(".".join(str(x) for x in reduced))
return version
##~~ Release testing ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@task
def sync_test_repo(force=False):
"""sync local checkout with testrepo"""
with lcd(env.octoprint):
for branch in (
"master",
"maintenance",
"staging/maintenance",
"rc/maintenance",
"devel",
"rc/devel",
):
local("git checkout {}".format(branch))
if force:
local("git push --force releasetest {}".format(branch))
else:
local("git push releasetest {}".format(branch))
@task
def merge_and_push(branch="master", force=False):
with lcd(env.octoprint):
for pushbranch in (
"rc/maintenance",
"rc/devel",
"staging/maintenance",
"staging/devel",
):
local("git checkout {}".format(pushbranch))
local("git merge {}".format(branch))
if force:
local("git push --force")
else:
local("git push")
def test_branch(release_branch, prep_branch, dev_branch, tag=None, force=False):
if tag is None:
tag = env.tag
if tag is None:
abort("Tag needs to be set")
if tag.endswith("rc1"):
merge_tag_push_test_repo(release_branch, dev_branch, tag, force=force)
else:
merge_tag_push_test_repo(release_branch, prep_branch, tag, force=force)
@task
def test_rc_devel(tag=None, force=False):
"""prep devel rc on testrepo (from staging/devel)"""
test_branch("rc/devel", "staging/devel", "devel", tag=tag, force=force)
@task
def test_rc_maintenance(tag=None, force=False):
"""prep maintenance rc on testrepo (from staging/maintenance)"""
test_branch(
"rc/maintenance", "staging/maintenance", "maintenance", tag=tag, force=force
)
@task
def test_stable(tag=None, force=False):
"""prep stable release on testrepo (from staging/maintenance)"""
if tag is None:
tag = env.tag
if tag is None:
abort("Tag needs to be set")
merge_tag_push_test_repo("master", "staging/maintenance", tag, force=force)
@task
def test_bugfix(tag=None, force=False):
"""prep bugfix release on testrepo (from staging/bugfix)"""
if tag is None:
tag = env.tag
if tag is None:
abort("Tag needs to be set")
merge_tag_push_test_repo("master", "staging/bugfix", tag, force=force)
def merge_tag_push_test_repo(push_branch, merge_branch, tag=None, force=False):
# merge, tag and push to testrepo
if tag is None:
tag = env.tag
if tag is None:
abort("Tag needs to be set")
with lcd(env.octoprint):
local("git fetch --tags -f releasetest")
local("git checkout {}".format(push_branch))
local("git merge {}".format(merge_branch))
if force:
local("git tag -d {}".format(tag))
local("git tag {}".format(tag))
local("git push releasetest {}".format(push_branch))
local("git push --tags releasetest {}".format(tag))
def merge_push_test_repo(push_branch, merge_branch):
# merge and push to testrepo
with lcd(env.octoprint):
local("git checkout {}".format(push_branch))
local("git merge {}".format(merge_branch))
local("git push releasetest {}".format(push_branch))
##~~ Local install testing ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def venv_executable(venv, executable):
if sys.platform == "win32":
return "{}\\Scripts\\{}.exe".format(venv, executable)
else:
return "{}/bin/{}".format(venv, executable)
def test_install(installable, python, target="wheel"):
basedir = "testconf-dist"
venv = "venv-dist"
with lcd(env.octoprint):
local("rm -rf {} || true".format(venv))
local("rm -rf {} || true".format(basedir))
local("{} -m venv {}".format(getattr(env, python), venv))
local(
"{} -m pip install {}".format(venv_executable(venv, "python"), installable)
)
local(
"{} serve --debug --basedir {} --port 5001".format(
venv_executable(venv, "octoprint"), basedir
)
)
def test_local(tag, python, target="wheel"):
# test local install of tag against python version and wheel/sdist
if tag is None:
tag = env.tag
if tag is None:
abort("Tag needs to be set")
with lcd(env.octoprint):
if not os.path.exists(os.path.join("dist", "OctoPrint-{}.tar.gz".format(tag))):
local("{} setup.py sdist bdist_wheel".format(sys.executable))
if target == "wheel":
installable = "dist/OctoPrint-{}-py2.py3-none-any.whl".format(tag)
elif target == "sdist":
installable = "dist/OctoPrint-{}.tar.gz".format(tag)
else:
abort("Unknown target {}".format(target))
return
test_install(installable, python)
@task
def test_sdist(python, tag=None):
"""test sdist install of tag against python version"""
test_local(tag, python, target="sdist")
@task
def test_wheel(python, tag=None):
"""test wheel install of tag against python version"""
test_local(tag, python, target="wheel")
@task
def test_version(version, python="python37"):
"""test install of version against python version"""
test_install("OctoPrint=={}".format(version), python)
##~~ FlashHost ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def format_serial(serial):
return "0" * (12 - len(serial)) + serial
def disk_device(serial):
return "/dev/disk/by-id/usb-LinuxAut_sdmux_HS-SD_MMC_{}-0:0".format(
format_serial(serial)
)
def boot_part_device(serial):
return "/dev/disk/by-id/usb-LinuxAut_sdmux_HS-SD_MMC_{}-0:0-part1".format(
format_serial(serial)
)
def mqtt_annotate(target, text):
if env.flashhost.get("mqtt_annotation"):
run('{} {} "{}"'.format(env.flashhost["mqtt_annotation"], target, text))
def read_file(path):
fd = BytesIO()
try:
get(path, fd)
fd.seek(0)
return fd.read()
finally:
fd.close()
def write_file(path, data, use_sudo=False):
fd = BytesIO()
try:
fd.write(data)
fd.seek(0)
put(fd, path, use_sudo=use_sudo)
finally:
fd.close()
def print_file(path):
print("-" * len(path))
print(path)
print("-" * len(path))
print(read_file(path).decode("utf-8"))
@task
@hosts("[email protected]")
def flashhost_release_lock():
"""release flash lock if left set for some reason"""
lock = env.flashhost["flashlock"]
sudo("rm -rf {}".format(lock))
@task
@hosts("[email protected]")
def flashhost_flash(image, target=None):
"""flashes target with OctoPi image of provided image using dd"""
lockfile = env.flashhost["flashlock"]
imagefile = "{}/{}.img".format(env.flashhost["images"], image)
if not files.exists(imagefile):
imagefile = "{}/octopi-{}.img".format(env.flashhost["images"], image)
if target is None:
target = env.target
if target not in env.targets:
abort("Unknown target: {}".format(target))
if not files.exists(imagefile):
abort("Image not available: {}".format(imagefile))
serial = env.targets[target]["serial"]
targetdev = disk_device(serial)
sudo(
"flock -w600 {} dd bs=4M if={} of={} status=progress conv=fsync".format(
lockfile, imagefile, targetdev
)
)
def encrypt_psk(ssid, psk):
from hashlib import pbkdf2_hmac
from binascii import hexlify
return hexlify(pbkdf2_hmac("sha1", str.encode(psk), str.encode(ssid), 4096, 32)).decode("utf-8")
def flashhost_provision_octopi(target, boot):
hostname = env.targets[target]["hostname"]
password = env.rpi_password
if env.rpi_user != "pi":
abort("Legacy provisioning only supports pi user")
files.upload_template(
"octopi-wpa-supplicant.txt",
boot + "/octopi-wpa-supplicant.txt",
context=dict(ssid=env.wifi_ssid, psk=env.wifi_psk, country=env.wifi_country),
use_jinja=True,
template_dir="templates",
backup=False,
keep_trailing_newline=True,
use_sudo=True,
)
files.upload_template(
"octopi-network.txt",
boot + "/octopi-network.txt",
context=dict(ssid=env.wifi_ssid, psk=env.wifi_psk),
use_jinja=True,
template_dir="templates",
backup=False,
keep_trailing_newline=True,
use_sudo=True,
)
files.upload_template(
"octopi-hostname.txt",
boot + "/octopi-hostname.txt",
context=dict(hostname=hostname),
use_jinja=True,
template_dir="templates",
backup=False,
keep_trailing_newline=True,
use_sudo=True,
)
files.upload_template(
"octopi-password.txt",
boot + "/octopi-password.txt",
context=dict(password=password),
use_jinja=True,
template_dir="templates",
backup=False,
keep_trailing_newline=True,
use_sudo=True,
)
def flashhost_provision_firstrun(target, boot):
from passlib.hash import sha512_crypt
hostname = env.targets[target]["hostname"]
user = env.rpi_user
password = env.rpi_password
passwordhash = sha512_crypt.using(rounds=5000).hash(password)
files.upload_template(
"firstrun.sh",
boot + "/firstrun.sh",
context=dict(
hostname=hostname,
user=user,
passwordhash=passwordhash,
ssid=env.wifi_ssid,
psk=encrypt_psk(env.wifi_ssid, env.wifi_psk),
country=env.wifi_country,
),
use_jinja=True,
template_dir="templates",
backup=False,
keep_trailing_newline=True,
use_sudo=True,
)
print_file(boot + "/firstrun.sh")
cmdline = read_file(boot + "/cmdline.txt").strip()
if b"firstrun.sh" not in cmdline:
cmdline += b" systemd.run=/boot/firstrun.sh systemd.run_success_action=reboot systemd.unit=kernel-command-line.target"
write_file(boot + "/cmdline.txt", cmdline, use_sudo=True)
print_file(boot + "/cmdline.txt")
@task
@hosts("[email protected]")
def flashhost_provision(target=None, firstrun=True):
"""provisions target with wifi, hostname, password and boot_delay"""
if target is None:
target = env.target
if target not in env.targets:
abort("Unknown target: {}".format(target))
serial = env.targets[target]["serial"]
boot = boot_part_device(serial)
mount = "{}/{}".format(env.flashhost["mounts"], target)
if not files.exists(mount):
run("mkdir -p {}".format(mount))
if not files.exists(mount + "/cmdline.txt"):
sudo("mount {} {}".format(boot, mount))
if firstrun:
flashhost_provision_firstrun(target, mount)
else:
flashhost_provision_octopi(target, mount)
files.append(mount + "/config.txt", "boot_delay=3", use_sudo=True)
sudo("umount {}".format(mount))
@task
@hosts("[email protected]")
def flashhost_host(target=None):
"""switches target to Host mode (powered off & USB-SD-MUX Host)"""
if target is None:
target = env.target
if target not in env.targets:
abort("Unknown target: {}".format(target))
usbport = env.targets[target]["usbport"]
serial = env.targets[target]["serial"]
sudo("{} -d {}".format(env.flashhost["ykush"], usbport))
sudo(
"{} /dev/usb-sd-mux/id-{} host".format(
env.flashhost["usbsdmux"], format_serial(serial)
)
)
time.sleep(5.0)
mqtt_annotate(target, "Switched {} to Host mode".format(target))
@task
@hosts("[email protected]")
def flashhost_dut(target=None):
"""switches target to DUT mode (USB-SD-MUX DUT & powered on)"""
if target is None:
target = env.target
if target not in env.targets:
abort("Unknown target: {}".format(target))
usbport = env.targets[target]["usbport"]
serial = env.targets[target]["serial"]
sudo(
"{} /dev/usb-sd-mux/id-{} dut".format(
env.flashhost["usbsdmux"], format_serial(serial)
)
)
sudo("{} -u {}".format(env.flashhost["ykush"], usbport))
if env.targets[target].get("um25c"):
sudo("systemctl restart {}".format(env.targets[target]["um25c"]))
mqtt_annotate(target, "Switched {} to DUT mode".format(target))
@task
@hosts("[email protected]")
def flashhost_dutstate(target=None):
"""switches target to DUT mode (USB-SD-MUX DUT & powered on)"""
if target is None:
target = env.target
if target not in env.targets:
abort("Unknown target: {}".format(target))
usbport = env.targets[target]["usbport"]
sudo("{} -g {}".format(env.flashhost["ykush"], usbport))
@task
@hosts("[email protected]")
def flashhost_reboot(target=None):
"""powers target off and on again"""
if target is None:
target = env.target
if target not in env.targets:
abort("Unknown target: {}".format(target))
usbport = env.targets[target]["usbport"]
sudo("{} -d {}".format(env.flashhost["ykush"], usbport))
time.sleep(1.0)
sudo("{} -u {}".format(env.flashhost["ykush"], usbport))
mqtt_annotate(target, "Rebooted {}".format(target))
@task
@hosts("[email protected]")
def flashhost_flash_and_provision(version, target=None, firstrun=True):
"""runs flash & provision cycle on target for specified OctoPi version"""
if target is None:
target = env.target
flashhost_host(target=target)
flashhost_flash(version, target=target)
print("Flashing done, giving the system a bit to recover...")
time.sleep(5.0)
print("... done")
flashhost_provision(target=target, firstrun=firstrun)
flashhost_dut(target=target)
@task
@hosts("[email protected]")
def flashhost_list_images():
path = env.flashhost["images"]
print("Available images:")
for f in run("ls -1 {}".format(path), quiet=True).split("\n"):
f = f.strip()
if not f.endswith(".img"):
continue
if f.startswith("octopi-"):
print(" {}".format(f[len("octopi-") : -len(".img")]))
else:
print(" {}".format(f[: -len(".img")]))
@task
@hosts("[email protected]")
def flashhost_fetch_image(url, image):
"""downloads image from url to flashhost images directory"""
path = env.flashhost["images"]
tmp_path = path + "/tmp"
if files.exists("{}/{}.img".format(path, image)):
abort("Image {} already exists".format(image))
run("wget {} -O {}/{}.zip".format(url, tmp_path, image))
run("unzip {}/{}.zip -d {}".format(tmp_path, image, tmp_path))
run("rm {}/{}.zip".format(tmp_path, image))
unpacked = run("ls {}/*.img | head -n 1".format(tmp_path), quiet=True).split("\n")[
0
]
run("mv {} {}/{}.img".format(unpacked, path, image))
@task
@hosts("[email protected]")
def flashhost_remove_image(image, ignore_missing=False):
"""removes image from flashhost images directory"""
path = env.flashhost["images"]
imagepath = "{}/{}.img".format(path, image)
if files.exists(imagepath):
run("rm {}".format(imagepath))
return
imagepath = "{}/octopi-{}.img".format(path, image)
if files.exists(imagepath):
run("rm {}".format(imagepath))
return
if ignore_missing:
return
abort("Image {} does not exist".format(image))
##~~ OctoPi ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def release_patch(
key, tag, repo, additional_repos=None, branch="master", prerelease=False, pip=None
):
# generate release patch
now = datetime.datetime.utcnow().replace(microsecond=0).isoformat(" ")
tag_name = "{} (release candidate)" if prerelease else "{} (stable)"
tag_name = tag_name.format(tag)
if additional_repos is None:
additional_repos = []
checks = dict()
if pip is not None:
checks[key] = dict(pip=pip)
release = dict(
draft=False,
html_url="https://github.com/{}/releases/tag/{}".format(repo, tag),
name=tag_name,
prerelease=prerelease,
published_at=now,
tag_name=tag,
target_commitish=branch,
)
releases = dict()
releases[repo] = [
release,
]
for repo in additional_repos:
releases[repo] = [
release,
]
config = dict(
plugins=dict(
github_release_patcher=dict(releases=releases),
softwareupdate=dict(checks=checks),
)
)
return config
def release_patch_octoprint(tag, branch, prerelease):
return release_patch(
"octoprint",
tag,
"OctoPrint/OctoPrint",
additional_repos=[
"foosel/OctoPrint",
],
branch=branch,
prerelease=prerelease,
pip="{}/archive/{{target_version}}.zip".format(env.releasetest_repo),
)
def release_patch_filecheck(tag, branch="master"):
return release_patch(
"file_check",
tag,
"OctoPrint/OctoPrint-FileCheck",
branch=branch,
pip="https://github.com/OctoPrint/OctoPrint-FileCheck/archive/{}.zip".format(
branch
),
)
def release_patch_firmwarecheck(tag, branch="master"):
return release_patch(
"firmware_check",
tag,
"OctoPrint/OctoPrint-FirmwareCheck",
branch=branch,
pip="https://github.com/OctoPrint/OctoPrint-FirmwareCheck/archive/{}.zip".format(
branch
),
)
@task
def octopi_reboot():
"""reboots the system"""
sudo("shutdown -r now")
@task
def octopi_octoservice(command):
"""run service command"""
sudo("service octoprint {}".format(command))
def octopi_standardrepo():
"""set standard repo"""
if files.exists("~/OctoPrint/.git"):
run(
"cd ~/OctoPrint && git remote set-url origin https://github.com/OctoPrint/OctoPrint"
)
def octopi_releasetestrepo():
"""set releasetest repo"""
if files.exists("~/OctoPrint/.git"):
run(
"cd ~/OctoPrint && git remote set-url origin {}".format(
env.releasetest_repo
)
)
@task
def octopi_releasetestplugin_github_release_patcher():
"""install release patcher"""
if not files.exists("~/.octoprint/plugins/github_release_patcher.py"):
put(
"files/github_release_patcher.py",
"~/.octoprint/plugins/github_release_patcher.py",
)
@task
def octopi_install(url):
"""install something inside OctoPrint venv"""
run('~/oprint/bin/pip install "{}"'.format(url))
@task
def octopi_curl_plugin(url):
"""install a single file plugin from url"""
if url in env.fixes["plugins"]:
url = env.fixes["plugins"][url]
if not files.exists("~/.octoprint/plugins"):
run("mkdir -p ~/.octoprint/plugins")
run("cd ~/.octoprint/plugins && curl -L -O '{}'".format(url))
@task
def octopi_tailoctolog():
"""tail octoprint.log"""
run("tail -f ~/.octoprint/logs/octoprint.log")
@task
def octopi_get_version(target=None):
if target is None:
target = env.target
octopi_version_string = run("cat /etc/octopi_version")
print("OctoPi version: {}".format(octopi_version_string))
return octopi_version_string
def octopi_patch_python_env(target=None):
if target is None:
target = env.target
octopi_version_string = octopi_get_version(target=target)
octopi_version = get_comparable_version(octopi_version_string)
if octopi_version < get_comparable_version("0.16.0"):
octopi_install("wrapt==1.12.1")
def octopi_test_releasepatch_octoprint(tag, branch, prerelease):
# creates & applies release patch
config = release_patch_octoprint(tag, branch, bool(prerelease))
octopi_update_config(config)
def octopi_test_releasepatch_filecheck(tag):
config = release_patch_filecheck(tag)
octopi_update_config(config)
def octopi_test_releasepatch_firmwarecheck(tag):
config = release_patch_firmwarecheck(tag)
octopi_update_config(config)
def octopi_update_config(config):
# merge config with existing one and write to disk
fd = BytesIO()
get(".octoprint/config.yaml", fd)
fd.seek(0)
current_config = yaml.safe_load(fd)
fd.close()
merged_config = dict_merge(current_config, config)
fd = StringIO()
yaml.safe_dump(merged_config, fd)
fd.seek(0)
put(fd, ".octoprint/config.yaml")
fd.close()
run("cat .octoprint/config.yaml")
@task
def octopi_await_ntp(timeout=300):
"""waits for the server to have ntp synchronized"""
start = time.monotonic()
print("Waiting for OctoPi to have its time and date synced from NTP")
while True:
if timeout is not None and time.monotonic() > start + timeout:
abort("Time was not synced after {}s".format(timeout))
try:
remote = run('date +"%Y%m%d"').strip()
except Exception:
pass
else:
local = datetime.date.today().strftime("%Y%m%d")
if remote == local:
print("Time has been synced")
break
time.sleep(10.0)
@task
def octopi_await_server(timeout=300):
"""waits for the server to come up, with optional timeout"""
start = time.monotonic()
print("Waiting for OctoPrint to become responsive at http://{}".format(env.host))
while True:
if timeout is not None and time.monotonic() > start + timeout:
abort("Server wasn't up after {}s".format(timeout))
try:
r = requests.get("http://{}/online.txt".format(env.host))
if r.status_code == 200:
print("OctoPrint is up at http://{}".format(env.host))
break
except Exception:
pass
print(".", end="")
time.sleep(10.0)
@task
def octopi_provision(
config="configs/with_acl",
version=None,
release_channel=None,
pip=None,
packages=None,
fixes=None,
restart=True,
releasetest=False,
headless=False,
):
"""provisions instance: start version, config, release channel, release patcher"""
octopi_octoservice("stop")
run("rm .octoprint/.incomplete_startup || true")
if version is not None:
octopi_patch_python_env()
octopi_install("OctoPrint=={}".format(version))
if pip is not None:
octopi_install("pip=={}".format(pip))
if packages:
for package in packages.split("|"):
if "/" in package:
package, version = package.split("/")
package = "{}=={}".format(package, version)
octopi_install(package)
if fixes:
for fix in fixes.split("|"):
octopi_curl_plugin(fix)
with codecs.open(
os.path.join(config, "config.yaml"),
mode="r",
encoding="utf-8",
errors="replace",
) as f:
new_config = yaml.safe_load(f)
if release_channel is not None:
if release_channel in ("maintenance", "devel"):
release_config = dict(
plugins=dict(
softwareupdate=dict(
checks=dict(
octoprint=dict(
prerelease=True,
prerelease_channel="rc/{}".format(release_channel),
)
)
)
)
)
else:
release_config = dict(
plugins=dict(