This repository has been archived by the owner on Apr 4, 2024. It is now read-only.
/
ioc_json.py
1763 lines (1510 loc) · 65.4 KB
/
ioc_json.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
# Copyright (c) 2014-2017, iocage
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted providing that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Convert, load or write JSON."""
import collections
import datetime
import fileinput
import json
import logging
import os
import re
import shutil
import subprocess as su
import sys
import iocage.lib.ioc_common
import iocage.lib.ioc_create
import iocage.lib.ioc_exec
import iocage.lib.ioc_list
import iocage.lib.ioc_stop
import libzfs
import netifaces
def _get_pool_and_iocroot():
"""For internal setting of pool and iocroot."""
pool = IOCJson().json_get_value("pool")
iocroot = IOCJson(pool).json_get_value("iocroot")
return pool, iocroot
class IOCJson(object):
"""
Migrates old iocage configurations(UCL and ZFS Props) to the new JSON
format, will set and get properties.
"""
def __init__(self,
location="",
silent=False,
cli=False,
stop=False,
exit_on_error=False,
callback=None):
self.location = location
self.lgr = logging.getLogger('ioc_json')
self.cli = cli
self.stop = stop
self.exit_on_error = exit_on_error
self.silent = silent
self.callback = callback
try:
force_env = os.environ["IOCAGE_FORCE"]
except KeyError:
# FreeNAS or an API user, due to the sheer web of calls to this
# module we are assuming they are OK with any renaming opertaions
force_env = "TRUE"
self.force = True if force_env == "TRUE" else False
self.zfs = libzfs.ZFS(history=True, history_prefix="<iocage>")
def json_convert_from_ucl(self):
"""Convert to JSON. Accepts a location to the ucl configuration."""
if os.geteuid() != 0:
raise RuntimeError("You need to be root to convert the"
" configurations to the new format!")
with open(self.location + "/config", "r") as conf:
lines = conf.readlines()
key_and_value = {}
for line in lines:
line = line.partition("=")
key = line[0].rstrip()
value = line[2].replace(";", "").replace('"', '').strip()
key_and_value[key] = value
self.json_write(key_and_value)
def json_convert_from_zfs(self, uuid, skip=False):
"""Convert to JSON. Accepts a jail UUID"""
pool, _ = _get_pool_and_iocroot()
dataset = f"{pool}/iocage/jails/{uuid}"
jail_zfs_prop = "org.freebsd.iocage:jail_zfs_dataset"
if os.geteuid() != 0:
raise RuntimeError("You need to be root to convert the"
" configurations to the new format!")
props = self.zfs.get_dataset(dataset).properties
# Filter the props we want to convert.
prop_prefix = "org.freebsd.iocage"
key_and_value = {"host_domainname": "none"}
for key, prop in props.items():
if not key.startswith(prop_prefix):
continue
key = key.partition(":")[2]
value = prop.value
if key == "type":
if value == "basejail":
# These were just clones on master.
value = "jail"
key_and_value["basejail"] = "yes"
elif key == "hostname":
hostname = props[f'{prop_prefix}:host_hostname']
if value != hostname:
# This is safe to replace at this point.
# The user changed the wrong hostname key, we will move
# it to the right one now.
if hostname == uuid:
key_and_value["host_hostname"] = prop.value
continue
key_and_value[key] = value
if not skip:
# Set jailed=off and move the jailed dataset.
try:
self.zfs_set_property(f"{dataset}/root/data", "jailed", "off")
self.zfs.get_dataset(f"{dataset}/root/data").rename(
f"{dataset}/data")
self.zfs_set_property(f"{dataset}/data", jail_zfs_prop,
f"iocage/jails/{uuid}/data")
self.zfs_set_property(f"{dataset}/data", "jailed", "on")
except libzfs.ZFSException as err:
# The jailed dataset doesn't exist, which is OK.
pass
key_and_value["jail_zfs_dataset"] = f"iocage/jails/{uuid}/data"
self.json_write(key_and_value)
def _zfs_get_properties(self, identifier):
if "/" in identifier:
dataset = self.zfs.get_dataset(identifier)
return dataset.properties
else:
pool = self.zfs.get(identifier)
return pool.root_dataset.properties
def zfs_get_property(self, identifier, key):
try:
return self._zfs_get_properties(identifier)[key].value
except Exception:
return "-"
def zfs_set_property(self, identifier, key, value):
ds = self._zfs_get_properties(identifier)
if ":" in key:
ds[key] = libzfs.ZFSUserProperty(value)
else:
ds[key].value = value
def json_load(self):
"""Load the JSON at the location given. Returns a JSON object."""
pool, iocroot = _get_pool_and_iocroot()
version = self.json_get_version()
jail_type, jail_uuid = self.location.rsplit("/", 2)[-2:]
full_uuid = jail_uuid # Saves jail_uuid for legacy ZFS migration
legacy_short = False
try:
jail_dataset = self.zfs.get_dataset(
f"{pool}/iocage/{jail_type}/{jail_uuid}")
except libzfs.ZFSException as err:
if err.code == libzfs.Error.NOENT:
if os.path.isfile(self.location + "/config"):
iocage.lib.ioc_common.logit(
{
"level": "EXCEPTION",
"message": "iocage_legacy develop had a broken"
" hack88 implementation.\nPlease manually rename"
f" {jail_uuid} or destroy it with zfs."
},
exit_on_error=self.exit_on_error,
_callback=self.callback,
silent=self.silent)
jail_dataset = self.zfs.get_dataset_by_path(self.location)
full_uuid = jail_dataset.name.rsplit("/")[-1]
legacy_short = True
else:
raise()
skip = False
if jail_dataset.mountpoint is None:
try:
jail_dataset.mount_recursive()
except libzfs.ZFSException as err:
iocage.lib.ioc_common.logit(
{
"level": "EXCEPTION",
"message": err
},
exit_on_error=self.exit_on_error,
_callback=self.callback,
silent=self.silent)
try:
with open(self.location + "/config.json", "r") as conf:
conf = json.load(conf)
except FileNotFoundError:
try:
# If this is a legacy jail, it will be missing this file but
# not this key.
jail_dataset.properties["org.freebsd.iocage:host_hostuuid"]
except KeyError:
if os.path.isfile(f"{self.location}/config"):
# iocage legacy develop jail, not missing configuration
pass
else:
iocage.lib.ioc_common.logit(
{
"level":
"EXCEPTION",
"message":
f"{jail_uuid} is missing it's configuration,"
" please destroy this jail and recreate it."
},
exit_on_error=self.exit_on_error,
_callback=self.callback,
silent=self.silent)
if not self.force:
iocage.lib.ioc_common.logit(
{
"level":
"EXCEPTION",
"message":
"A renaming operation is required to continue.\n"
f"Please run iocage -f {sys.argv[-1]} as root."
},
exit_on_error=self.exit_on_error,
_callback=self.callback,
silent=self.silent)
if os.path.isfile(self.location + "/config"):
self.json_convert_from_ucl()
with open(self.location + "/config.json", "r") as conf:
conf = json.load(conf)
else:
try:
dataset = self.location.split("/")
for d in dataset:
if len(d) == 36:
uuid = d
elif len(d) == 8:
# Hack88 migration to a perm short UUID.
short_uuid = full_uuid[:8]
full_dataset = f"{pool}/iocage/jails/{full_uuid}"
short_dataset = f"{pool}/iocage/jails/{short_uuid}"
jail_hostname = self.zfs_get_property(
full_dataset,
'org.freebsd.iocage:host_hostname')
self.json_convert_from_zfs(full_uuid)
with open(self.location + "/config.json",
"r") as conf:
conf = json.load(conf)
iocage.lib.ioc_common.logit(
{
"level":
"INFO",
"message":
"hack88 is no longer supported."
f"\n{full_dataset} is being "
f"converted to {short_dataset}"
f" permanently."
},
_callback=self.callback,
silent=self.silent)
status, _ = iocage.lib.ioc_list.IOCList(
exit_on_error=self.exit_on_error).list_get_jid(
full_uuid)
if status:
iocage.lib.ioc_common.logit(
{
"level":
"INFO",
"message":
"Stopping jail to migrate UUIDs."
},
_callback=self.callback,
silent=self.silent)
iocage.lib.ioc_stop.IOCStop(
full_uuid,
self.location,
conf,
exit_on_error=self.exit_on_error,
silent=True)
jail_zfs_prop = \
"org.freebsd.iocage:jail_zfs_dataset"
uuid_prop = "org.freebsd.iocage:host_hostuuid"
host_prop = "org.freebsd.iocage:host_hostname"
# Set jailed=off and move the jailed dataset.
self.zfs_set_property(f"{full_dataset}/data",
'jailed', 'off')
# We don't want to change a real hostname.
if jail_hostname == full_uuid:
self.zfs_set_property(full_dataset, host_prop,
short_uuid)
self.zfs_set_property(full_dataset, uuid_prop,
short_uuid)
self.zfs_set_property(f"{full_dataset}/data",
jail_zfs_prop,
f"iocage/jails/"
f"{short_uuid}/data")
self.zfs.get_dataset(full_dataset).rename(
short_dataset)
self.zfs_set_property(f"{short_dataset}/data",
"jailed", "on")
uuid = short_uuid
self.location = f"{iocroot}/jails/{short_uuid}"
skip = True
if uuid is None:
iocage.lib.ioc_common.logit(
{
"level": "EXCEPTION",
"message": "Configuration could not be loaded,"
" is the jail dataset mounted?"
},
exit_on_error=self.exit_on_error,
_callback=self.callback,
silent=self.silent)
self.json_convert_from_zfs(uuid, skip=skip)
with open(self.location + "/config.json", "r") as conf:
conf = json.load(conf)
if legacy_short:
messages = collections.OrderedDict(
[("1-NOTICE", "*" * 80),
("2-WARNING",
f"Jail: {full_uuid} was renamed to {uuid}"),
("3-NOTICE",
f"{'*' * 80}\n"),
("4-EXCEPTION",
"Please issue your command again.")])
for level, msg in messages.items():
level = level.partition("-")[2]
iocage.lib.ioc_common.logit(
{
"level": level,
"message": msg
},
exit_on_error=self.exit_on_error,
_callback=self.callback,
silent=self.silent)
except su.CalledProcessError:
# At this point it should be a real misconfigured jail
raise RuntimeError("Configuration is missing!"
f" Please destroy {uuid} and recreate"
" it.")
try:
conf_version = conf["CONFIG_VERSION"]
if version != conf_version:
conf = self.json_check_config(conf)
except KeyError:
conf = self.json_check_config(conf)
return conf
def json_write(self, data, _file="/config.json"):
"""Write a JSON file at the location given with supplied data."""
with iocage.lib.ioc_common.open_atomic(self.location + _file,
'w') as out:
json.dump(data, out, sort_keys=True, indent=4, ensure_ascii=False)
def _upgrade_pool(self, pool):
if os.geteuid() != 0:
raise RuntimeError("Run as root to migrate old pool"
" activation property!")
self.zfs_set_property(pool, "org.freebsd.ioc:active", "yes")
self.zfs_set_property(pool, "comment", "-")
def json_get_value(self, prop, default=False):
"""Returns a string with the specified prop's value."""
old = False
zpools = list(map(lambda x: x.name, list(self.zfs.pools)))
if default:
_, iocroot = _get_pool_and_iocroot()
with open(f"{iocroot}/defaults.json", "r") as default_json:
conf = json.load(default_json)
if prop == "all":
return conf
return conf[prop]
if prop == "pool":
match = 0
for pool in zpools:
prop_ioc_active = self.zfs_get_property(
pool, "org.freebsd.ioc:active")
prop_comment = self.zfs_get_property(pool, "comment")
if prop_ioc_active == "yes":
_dataset = pool
match += 1
elif prop_comment == "iocage":
_dataset = pool
match += 1
old = True
if match == 1:
if old:
self._upgrade_pool(_dataset)
return _dataset
elif match >= 2:
iocage.lib.ioc_common.logit(
{
"level": "ERROR",
"message": "Pools:"
},
_callback=self.callback,
silent=self.silent)
for zpool in zpools:
iocage.lib.ioc_common.logit(
{
"level": "ERROR",
"message": f" {zpool}"
},
_callback=self.callback,
silent=self.silent)
raise RuntimeError(f"You have {match} pools marked active"
" for iocage usage.\n Run \"iocage"
f" activate ZPOOL\" on the preferred"
" pool.\n")
else:
if len(sys.argv) >= 2 and "activate" in sys.argv[1:]:
pass
else:
# We use the first zpool the user has, they are free to
# change it.
try:
zpool = zpools[0]
except IndexError:
iocage.lib.ioc_common.logit(
{
"level":
"EXCEPTION",
"message":
"No zpools found! Please create one "
"before using iocage."
},
exit_on_error=self.exit_on_error,
_callback=self.callback,
silent=self.silent)
if os.geteuid() != 0:
raise RuntimeError("Run as root to automatically "
"activate the first zpool!")
iocage_skip = os.environ.get("IOCAGE_SKIP", "FALSE")
if iocage_skip == "TRUE":
iocage.lib.ioc_common.logit(
{
"level":
"EXCEPTION",
"message":
"IOCAGE_SKIP is TRUE or an RC operation, not"
" activating a pool.\nPlease manually issue"
" iocage activate POOL"
},
_callback=self.callback,
silent=self.silent)
if zpool == "freenas-boot":
try:
zpool = zpools[1]
except IndexError:
raise RuntimeError("Please specify a pool to "
"activate with iocage activate "
"POOL")
iocage.lib.ioc_common.logit(
{
"level":
"INFO",
"message":
f"Setting up zpool [{zpool}] for"
" iocage usage\n If you wish to change"
" please use \"iocage activate\""
},
_callback=self.callback,
silent=self.silent)
self.zfs_set_property(zpool, "org.freebsd.ioc:active",
"yes")
return zpool
elif prop == "iocroot":
# Location in this case is actually the zpool.
try:
loc = f"{self.location}/iocage"
mount = self.zfs_get_property(loc, "mountpoint")
if mount != "none":
return mount
else:
raise RuntimeError(f"Please set a mountpoint on {loc}")
except Exception:
raise RuntimeError(f"{self.location} not found!")
elif prop == "all":
conf = self.json_load()
return conf
else:
conf = self.json_load()
if prop == "last_started" and conf[prop] == "none":
return "never"
else:
return conf[prop]
def json_set_value(self, prop, _import=False, default=False):
"""Set a property for the specified jail."""
key, _, value = prop.partition("=")
if not default:
conf = self.json_load()
uuid = conf["host_hostuuid"]
status, jid = iocage.lib.ioc_list.IOCList().list_get_jid(uuid)
conf[key] = value
sysctls_cmd = ["sysctl", "-d", "security.jail.param"]
jail_param_regex = re.compile("security.jail.param.")
sysctls_list = su.Popen(
sysctls_cmd,
stdout=su.PIPE).communicate()[0].decode("utf-8").split()
jail_params = [
p.replace("security.jail.param.", "").replace(":", "")
for p in sysctls_list if re.match(jail_param_regex, p)
]
single_period = [
"allow_raw_sockets", "allow_socket_af", "allow_set_hostname"
]
if key == "template":
pool, iocroot = _get_pool_and_iocroot()
old_location = f"{pool}/iocage/jails/{uuid}"
new_location = f"{pool}/iocage/templates/{uuid}"
if status:
iocage.lib.ioc_common.logit(
{
"level": "EXCEPTION",
"message":
f"{uuid} is running.\nPlease stop it first!"
},
exit_on_error=self.exit_on_error,
_callback=self.callback,
silent=self.silent)
jails = iocage.lib.ioc_list.IOCList(
"uuid", exit_on_error=self.exit_on_error).list_datasets()
for j in jails:
_uuid = jails[j]
_path = f"{jails[j]}/root"
t_old_path = f"{old_location}/root@{_uuid}"
t_path = f"{new_location}/root@{_uuid}"
if _uuid == uuid:
continue
origin = self.zfs_get_property(_path, 'origin')
if origin == t_old_path or origin == t_path:
_status, _ = iocage.lib.ioc_list.IOCList(
).list_get_jid(_uuid)
if _status:
iocage.lib.ioc_common.logit(
{
"level":
"EXCEPTION",
"message":
f"{uuid} is running.\n"
"Please stop it first!"
},
exit_on_error=self.exit_on_error,
_callback=self.callback,
silent=self.silent)
if value == "yes":
try:
jail_zfs_dataset = f"{pool}/" \
f"{conf['jail_zfs_dataset']}"
self.zfs_set_property(jail_zfs_dataset, "jailed",
"off")
except libzfs.ZFSException as err:
# The dataset doesn't exist, that's OK
if err.code == libzfs.Error.NOENT:
pass
else:
iocage.lib.ioc_common.logit(
{
"level": "EXCEPTION",
"message": err
},
_callback=self.callback)
try:
self.zfs.get_dataset(old_location).rename(new_location)
except libzfs.ZFSException as err:
# cannot rename
iocage.lib.ioc_common.logit(
{
"level": "EXCEPTION",
"message": f"Cannot rename zfs dataset: {err}"
},
_callback=self.callback)
conf["type"] = "template"
self.location = new_location.lstrip(pool).replace(
"/iocage", iocroot)
iocage.lib.ioc_common.logit(
{
"level": "INFO",
"message": f"{uuid} converted to a template."
},
_callback=self.callback,
silent=self.silent)
# Writing these now since the dataset will be readonly
self.json_check_prop(key, value, conf)
self.json_write(conf)
iocage.lib.ioc_common.logit(
{
"level":
"INFO",
"message":
f"Property: {key} has been updated to {value}"
},
_callback=self.callback,
silent=self.silent)
self.zfs_set_property(new_location, "readonly", "on")
return
elif value == "no":
if not _import:
self.zfs.get_dataset(new_location).rename(old_location)
conf["type"] = "jail"
self.location = old_location.lstrip(pool).replace(
"/iocage", iocroot)
self.zfs_set_property(old_location, "readonly", "off")
iocage.lib.ioc_common.logit(
{
"level": "INFO",
"message": f"{uuid} converted to a jail."
},
_callback=self.callback,
silent=self.silent)
self.lgr.disabled = True
if key[:8] == "jail_zfs":
if status:
iocage.lib.ioc_common.logit(
{
"level": "EXCEPTION",
"message":
f"{uuid} is running.\nPlease stop it first!"
},
exit_on_error=self.exit_on_error,
_callback=self.callback,
silent=self.silent)
elif key == "dhcp":
if status:
iocage.lib.ioc_common.logit(
{
"level": "EXCEPTION",
"message":
f"{uuid} is running.\nPlease stop it first!"
},
exit_on_error=self.exit_on_error,
_callback=self.callback,
silent=self.silent)
else:
_, iocroot = _get_pool_and_iocroot()
with open(f"{iocroot}/defaults.json", "r") as default_json:
conf = json.load(default_json)
if not default:
value, conf = self.json_check_prop(key, value, conf)
self.json_write(conf)
iocage.lib.ioc_common.logit(
{
"level": "INFO",
"message": f"Property: {key} has been updated to {value}"
},
_callback=self.callback,
silent=self.silent)
# We can attempt to set a property in realtime to jail.
if status:
if key in single_period:
key = key.replace("_", ".", 1)
else:
key = key.replace("_", ".")
if key in jail_params:
if conf["vnet"] == "on" and key == "ip4.addr" or key == \
"ip6.addr":
return
try:
ip = True if key == "ip4.addr" or key == "ip6.addr" \
else False
if ip and value.lower() == "none":
return
if key == "vnet":
# We can't switch vnet dynamically
iocage.lib.ioc_common.logit(
{
"level":
"INFO",
"message":
"vnet changes require a jail restart"
},
_callback=self.callback,
silent=self.silent)
return
iocage.lib.ioc_common.checkoutput(
["jail", "-m", f"jid={jid}", f"{key}={value}"],
stderr=su.STDOUT)
except su.CalledProcessError as err:
raise RuntimeError(
f"{err.output.decode('utf-8').rstrip()}")
else:
if key in conf:
conf[key] = value
self.json_write(conf, "/defaults.json")
iocage.lib.ioc_common.logit(
{
"level":
"INFO",
"message":
f"Default Property: {key} has been updated to {value}"
},
_callback=self.callback,
silent=self.silent)
else:
iocage.lib.ioc_common.logit(
{
"level": "EXCEPTION",
"message":
f"{key} is not a valid property for default!"
},
exit_on_error=self.exit_on_error,
_callback=self.callback,
silent=self.silent)
@staticmethod
def json_get_version():
"""Sets the iocage configuration version."""
version = "11"
return version
def json_check_config(self, conf, default=False):
"""
Takes JSON as input and checks to see what is missing and adds the
new keys with their default values if missing.
"""
_, iocroot = _get_pool_and_iocroot()
renamed = False
if os.geteuid() != 0:
iocage.lib.ioc_common.logit(
{
"level":
"EXCEPTION",
"message":
"You need to be root to convert the"
" configurations to the new format!"
},
exit_on_error=self.exit_on_error,
_callback=self.callback,
silent=self.silent)
# Version 2 keys
try:
sysvmsg = conf["sysvmsg"]
sysvsem = conf["sysvsem"]
sysvshm = conf["sysvshm"]
except KeyError:
sysvmsg = "new"
sysvsem = "new"
sysvshm = "new"
# Set all keys, even if it's the same value.
conf["sysvmsg"] = sysvmsg
conf["sysvsem"] = sysvsem
conf["sysvshm"] = sysvshm
# Version 3 keys
if not default:
release = conf.get("release", None)
if release is None:
err_name = self.location.rsplit("/", 1)[-1]
iocage.lib.ioc_common.logit(
{
"level":
"EXCEPTION",
"message":
f"{err_name} has a corrupt configuration,"
" please destroy the jail."
},
exit_on_error=self.exit_on_error,
_callback=self.callback,
silent=self.silent)
release = release.rsplit("-p", 1)[0]
cloned_release = conf.get("cloned_release", "LEGACY_JAIL")
try:
freebsd_version = f"{iocroot}/releases/{release}/root/bin/" \
"freebsd-version"
except FileNotFoundError:
freebsd_version = f"{iocroot}/templates/" \
f"{conf['host_hostuuid']}" \
"/root/bin/freebsd-version"
except KeyError:
# At this point it should be a real misconfigured jail
uuid = self.location.rsplit("/", 1)[-1]
raise RuntimeError("Configuration is missing!"
f" Please destroy {uuid} and recreate"
" it.")
if release[:4].endswith("-"):
# 9.3-RELEASE and under don't actually have this binary.
release = conf["release"]
else:
with open(freebsd_version, "r") as r:
for line in r:
if line.startswith("USERLAND_VERSION"):
release = line.rstrip().partition("=")[2]
release = release.strip('"')
cloned_release = conf["release"]
# Set all Version 3 keys
conf["release"] = release
conf["cloned_release"] = cloned_release
# Version 4 keys
try:
basejail = conf["basejail"]
except KeyError:
basejail = "no"
# Set all keys, even if it's the same value.
conf["basejail"] = basejail
# Version 5 keys
try:
comment = conf["comment"]
except KeyError:
comment = "none"
# Set all keys, even if it's the same value.
conf["comment"] = comment
# Version 6 keys
conf["host_time"] = "yes"
# Version 7 keys
conf["depends"] = "none"
# Version 8 migration from uuid to tag named dataset
try:
tag = conf["tag"]
uuid = conf["host_hostuuid"]
try:
state = iocage.lib.ioc_common.checkoutput(
["jls", "-j", f"ioc-{uuid.replace('.', '_')}"],
stderr=su.PIPE).split()[5]
except su.CalledProcessError:
state = False
if tag != uuid:
if not self.force:
iocage.lib.ioc_common.logit(
{
"level":
"EXCEPTION",
"message":
"A renaming operation is required to continue.\n"
f"Please run iocage -f {sys.argv[-1]} as root."
},
exit_on_error=self.exit_on_error,
_callback=self.callback,
silent=self.silent)
conf, rtrn, date = self.json_migrate_uuid_to_tag(
uuid, tag, state, conf)
conf["jail_zfs_dataset"] = f"iocage/jails/{tag}/data"
if not date:
# The jail's tag was not a date, so it was renamed. Fix
# fstab
for line in fileinput.input(
f"{iocroot}/jails/{tag}/fstab", inplace=1):
print(line.replace(f'{uuid}', f'{tag}').rstrip())
renamed = True
if rtrn:
# They want to stop the jail, not attempt to migrate before
return conf
except KeyError:
# New jail creation