-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker_config.py
More file actions
993 lines (830 loc) · 44.1 KB
/
docker_config.py
File metadata and controls
993 lines (830 loc) · 44.1 KB
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
import os
import yaml
import json
import subprocess
import tempfile
import logging
from typing import Dict, Any, List, Optional
class DockerConfigGenerator:
def __init__(self):
self.output_dir = "generated_configs"
self.ensure_output_dir()
def ensure_output_dir(self):
"""Ensure output directory exists"""
if not os.path.exists(self.output_dir):
os.makedirs(self.output_dir)
def generate_docker_compose(self, config: Dict[str, Any]) -> str:
"""Generate docker-compose.yml content for Dockur Windows"""
# Basic service configuration
service_config = {
'image': 'dockurr/windows',
'container_name': config.get('name', 'windows'),
'environment': self._generate_environment_dict(config),
'devices': ['/dev/kvm', '/dev/net/tun'],
'cap_add': ['NET_ADMIN'],
'stop_grace_period': '2m',
'restart': 'on-failure'
}
# Add ports only if not using macvlan
# (macvlan exposes all ports by default)
if config.get('network_mode') != 'macvlan':
service_config['ports'] = [
f"{config.get('rdp_port', '3389')}:3389/tcp",
f"{config.get('vnc_port', '8006')}:8006/tcp"
]
# Add DHCP-specific devices and cgroup rules for macvlan
is_macvlan_dhcp = (config.get('network_mode') == 'macvlan' and
config.get('macvlan_dhcp'))
if is_macvlan_dhcp:
service_config['devices'].append('/dev/vhost-net')
service_config['device_cgroup_rules'] = ['c *:* rwm']
compose_config = {
'version': '3.8',
'services': {
config.get('name', 'windows'): service_config
}
}
# Add volumes if specified
volumes = self._generate_volumes(config)
if volumes:
service = compose_config['services'][config.get('name', 'windows')]
service['volumes'] = volumes
# Add Docker volume definitions if using named volumes
docker_volumes = self._generate_docker_volumes(config)
if docker_volumes:
compose_config['volumes'] = docker_volumes
# Add network configuration
networks = self._generate_networks(config)
if networks:
if 'networks' not in compose_config:
compose_config['networks'] = {}
compose_config['networks'].update(networks)
# Connect service to networks
service_networks = self._generate_service_networks(config)
if service_networks:
service_name = config.get('name', 'windows')
service = compose_config['services'][service_name]
service['networks'] = service_networks
elif config.get('network_mode') == 'host':
service_config['network_mode'] = 'host'
elif config.get('network_mode') == 'static':
# Static IP configuration
if config.get('static_ip'):
compose_config['networks'] = {
'dockwinterface_net': {
'driver': 'bridge',
'ipam': {
'config': [{
'subnet': config.get('subnet', '172.20.0.0/16'),
'gateway': config.get('gateway', '172.20.0.1')
}]
}
}
}
service_config['networks'] = {
'dockwinterface_net': {
'ipv4_address': config['static_ip']
}
}
elif config.get('network_mode') == 'none':
service_config['network_mode'] = 'none'
print(f"DEBUG: Checking network_mode: {config.get('network_mode')}")
print(f"DEBUG: Available config keys: {list(config.keys())}")
elif config.get('network_mode') == 'macvlan':
# For macvlan, reference the external network
network_name = config.get('macvlan_network_name', 'macvlan')
service = compose_config['services'][config.get('name', 'windows')]
service['networks'] = {network_name: {}}
if config.get('macvlan_ip'):
ipv4 = config['macvlan_ip']
service['networks'][network_name]['ipv4_address'] = ipv4
# Add external network reference
compose_config['networks'] = {
network_name: {
'external': True
}
}
elif (config.get('network_mode') and
config.get('network_mode') not in ['static', 'macvlan']):
service = compose_config['services'][config.get('name', 'windows')]
service['network_mode'] = config['network_mode']
# Add resource limits if specified
if config.get('cpu_limit') or config.get('memory_limit'):
deploy_config = {}
if config.get('cpu_limit'):
deploy_config['resources'] = {
'limits': {'cpus': str(config['cpu_limit'])}
}
if config.get('memory_limit'):
if 'resources' not in deploy_config:
deploy_config['resources'] = {'limits': {}}
mem_limit = config['memory_limit']
deploy_config['resources']['limits']['memory'] = mem_limit
service = compose_config['services'][config.get('name', 'windows')]
service['deploy'] = deploy_config
return yaml.dump(compose_config, default_flow_style=False, sort_keys=False, indent=2)
def _generate_environment_vars(self, config: Dict[str, Any], for_env_file: bool = False) -> List[str]:
"""Generate environment variables for the container"""
env_vars = []
# Basic Windows configuration
if config.get('username'):
username = self._escape_env_value(config['username'], for_env_file)
env_vars.append(f"USERNAME={username}")
if config.get('password'):
password = self._escape_env_value(config['password'], for_env_file)
env_vars.append(f"PASSWORD={password}")
# Windows version
if config.get('version'):
env_vars.append(f"VERSION={config['version']}")
# Version selection and keyboard settings
if config.get('language'):
env_vars.append(f"LANGUAGE={config['language']}")
if config.get('keyboard'):
env_vars.append(f"KEYBOARD={config['keyboard']}")
# System resources
if config.get('cpu_cores'):
env_vars.append(f"CPU_CORES={config['cpu_cores']}")
if config.get('ram_size'):
ram = config['ram_size']
ram_str = str(ram)
if isinstance(ram, int) or ram_str.isdigit():
ram_str = f"{ram_str}G"
env_vars.append(f"RAM_SIZE={ram_str}")
# Storage configuration
if config.get('disk_size'):
disk = config['disk_size']
disk_str = str(disk)
if isinstance(disk, int) or disk_str.isdigit():
disk_str = f"{disk_str}G"
env_vars.append(f"DISK_SIZE={disk_str}")
# Screen resolution (if provided)
if config.get('screen_resolution'):
env_vars.append(f"SCREEN={config['screen_resolution']}")
# Additional options
if config.get('enable_kvm', True):
env_vars.append("KVM=Y")
if config.get('debug', False):
env_vars.append("DEBUG=Y")
# Use proper RFC 1918 private IP for internal VM network (instead of Microsoft public IP 20.20.20.21)
env_vars.append("VM_NET_IP=192.168.250.21")
# Network configuration
if config.get('dns_servers'):
env_vars.append(f"DNS={config['dns_servers']}")
# Macvlan DHCP mode
is_macvlan_dhcp = (config.get('network_mode') == 'macvlan' and
config.get('macvlan_dhcp'))
if is_macvlan_dhcp:
env_vars.append("DHCP=Y")
# Static IP configuration
if config.get('network_mode') == 'static':
if config.get('static_ip'):
env_vars.append(f"IP={config['static_ip']}")
if config.get('gateway'):
env_vars.append(f"GATEWAY={config['gateway']}")
if config.get('subnet_mask'):
env_vars.append(f"NETMASK={config['subnet_mask']}")
# SNMP configuration
if config.get('enable_snmp'):
env_vars.append("SNMP_ENABLED=Y")
if config.get('snmp_community'):
env_vars.append(f"SNMP_COMMUNITY={config['snmp_community']}")
if config.get('snmp_port'):
env_vars.append(f"SNMP_PORT={config['snmp_port']}")
if config.get('snmp_location'):
env_vars.append(f"SNMP_LOCATION={config['snmp_location']}")
if config.get('snmp_contact'):
env_vars.append(f"SNMP_CONTACT={config['snmp_contact']}")
if config.get('snmp_trap_destinations'):
# Convert multiline trap destinations to comma-separated list
traps = config['snmp_trap_destinations'].strip().replace('\n', ',')
env_vars.append(f"SNMP_TRAPS={traps}")
# Logging configuration
if config.get('enable_logging'):
env_vars.append("LOGGING_ENABLED=Y")
if config.get('log_server_host'):
env_vars.append(f"LOG_SERVER={config['log_server_host']}")
if config.get('log_server_port'):
env_vars.append(f"LOG_PORT={config['log_server_port']}")
if config.get('log_protocol'):
env_vars.append(f"LOG_PROTOCOL={config['log_protocol']}")
if config.get('log_format'):
env_vars.append(f"LOG_FORMAT={config['log_format']}")
# Log sources
log_sources = []
if config.get('log_windows_events'):
log_sources.append('windows_events')
if config.get('log_snmp_traps'):
log_sources.append('snmp_traps')
if config.get('log_performance_metrics'):
log_sources.append('performance_metrics')
if config.get('log_application_traces'):
log_sources.append('application_traces')
if log_sources:
env_vars.append(f"LOG_SOURCES={','.join(log_sources)}")
return env_vars
def _generate_environment_dict(self, config: Dict[str, Any]) -> Dict[str, str]:
"""Generate environment variables as dictionary for direct YAML embedding"""
env_dict = {}
# Basic Windows configuration
if config.get('username'):
env_dict['USERNAME'] = str(config['username'])
if config.get('password'):
# Properly escape password to prevent Docker variable substitution
password = str(config['password'])
# For Docker Compose, wrap passwords with $ in quotes to prevent substitution
if '$' in password:
# Escape any existing quotes and wrap in double quotes
escaped_password = password.replace('"', '\\"')
env_dict['PASSWORD'] = f'"{escaped_password}"'
else:
env_dict['PASSWORD'] = password
# Version selection and keyboard settings
if config.get('language'):
env_dict['LANGUAGE'] = str(config['language'])
if config.get('keyboard'):
env_dict['KEYBOARD'] = str(config['keyboard'])
# System resources
if config.get('cpu_cores'):
env_dict['CPU_CORES'] = str(config['cpu_cores'])
if config.get('ram_size'):
env_dict['RAM_SIZE'] = f"{config['ram_size']}G"
# Windows version
if config.get('version'):
env_dict['VERSION'] = str(config['version'])
# Storage configuration
if config.get('disk_size'):
env_dict['DISK_SIZE'] = f"{config['disk_size']}G"
# Network configuration
if config.get('network_mode') == 'host':
env_dict['NETWORK'] = 'host'
print(f"DEBUG: Checking network_mode: {config.get('network_mode')}")
print(f"DEBUG: Available config keys: {list(config.keys())}")
elif config.get('network_mode') == 'macvlan':
env_dict['NETWORK'] = 'macvlan'
if config.get('macvlan_container_ip'):
env_dict['IP'] = str(config['macvlan_container_ip'])
elif config.get('network_mode') == 'static':
if config.get('static_ip'):
env_dict['IP'] = str(config['static_ip'])
# Additional features
if config.get('remote_desktop', True):
env_dict['RDP'] = 'true'
if config.get('web_interface', True):
env_dict['VNC'] = 'true'
# Use proper RFC 1918 private IP for internal VM network
env_dict["VM_NET_IP"] = "192.168.250.21"
# GPU support
if config.get('gpu_support'):
env_dict['GPU'] = 'true'
# Audio support
if config.get('audio_support'):
env_dict['AUDIO'] = 'true'
# USB support
if config.get('usb_support'):
env_dict['USB'] = 'true'
# File sharing
if config.get('file_sharing'):
env_dict['SHARE'] = 'true'
# SNMP configuration
if config.get('enable_snmp'):
env_dict['SNMP_ENABLED'] = 'Y'
if config.get('snmp_community'):
env_dict['SNMP_COMMUNITY'] = str(config['snmp_community'])
if config.get('snmp_port'):
env_dict['SNMP_PORT'] = str(config['snmp_port'])
if config.get('snmp_location'):
env_dict['SNMP_LOCATION'] = str(config['snmp_location'])
if config.get('snmp_contact'):
env_dict['SNMP_CONTACT'] = str(config['snmp_contact'])
if config.get('snmp_trap_destinations'):
# Convert multiline trap destinations to comma-separated list
traps = config['snmp_trap_destinations'].strip().replace('\n', ',')
env_dict['SNMP_TRAPS'] = traps
# Logging configuration
if config.get('enable_logging'):
env_dict['LOGGING_ENABLED'] = 'Y'
if config.get('log_server_host'):
env_dict['LOG_SERVER'] = str(config['log_server_host'])
if config.get('log_server_port'):
env_dict['LOG_PORT'] = str(config['log_server_port'])
if config.get('log_protocol'):
env_dict['LOG_PROTOCOL'] = str(config['log_protocol'])
if config.get('log_format'):
env_dict['LOG_FORMAT'] = str(config['log_format'])
# Log sources
log_sources = []
if config.get('log_windows_events'):
log_sources.append('windows_events')
if config.get('log_snmp_traps'):
log_sources.append('snmp_traps')
if config.get('log_performance_metrics'):
log_sources.append('performance_metrics')
if config.get('log_application_traces'):
log_sources.append('application_traces')
if log_sources:
env_dict['LOG_SOURCES'] = ','.join(log_sources)
return env_dict
def _escape_env_value(self, value: str, for_env_file: bool = False) -> str:
"""Escape special characters in environment variable values"""
if not isinstance(value, str):
return str(value)
if for_env_file:
# For .env files, use single quotes to prevent variable substitution
if '$' in value:
# Use single quotes to prevent any variable substitution
escaped = value.replace("'", "\\'")
return f"'{escaped}'"
# For values without $, use double quotes if they contain special characters
elif any(char in value for char in [' ', '"', '\\', '&', '|', ';', '(', ')', '<', '>', '`']):
escaped = value.replace('"', '\\"')
return f'"{escaped}"'
return value
else:
# For Docker Compose YAML, only quote if value contains spaces
if ' ' in value:
escaped = value.replace('"', '\\"')
escaped = f'"{escaped}"'
return escaped
return value
def _ensure_volume_directory(self, volume_path: str) -> bool:
"""Ensure the volume directory exists with proper permissions"""
try:
import os
if not os.path.exists(volume_path):
os.makedirs(volume_path, mode=0o755, exist_ok=True)
logging.info(f"Created volume directory: {volume_path}")
# Only try to change permissions if we can (don't fail if we can't)
try:
os.chmod(volume_path, 0o755)
logging.debug(f"Updated permissions for volume directory: {volume_path}")
except PermissionError:
# Directory exists and we have access, just log and continue
logging.debug(f"Volume directory {volume_path} exists with current permissions")
return True
except Exception as e:
logging.warning(f"Could not create volume directory {volume_path}: {e}")
return False
def _get_version_specific_volume_path(self, version: str) -> str:
"""Get the appropriate volume path based on Windows version"""
if not version:
return "/opt/windows/xfer" # Default fallback
version_lower = version.lower()
# Windows Server 2022 variants
if any(v in version_lower for v in ['2022', 'server-2022']):
return "/opt/windows/xfer2"
# Windows Server 2025 variants
elif any(v in version_lower for v in ['2025', 'server-2025']):
return "/opt/windows/xfer3"
# Windows Server 2019 variants
elif any(v in version_lower for v in ['2019', 'server-2019']):
return "/opt/windows/xfer4"
# All Windows 10 and 11 variants use the original path
else:
return "/opt/windows/xfer"
def _generate_volumes(self, config: Dict[str, Any]) -> List[str]:
"""Generate volume mappings with Docker volumes by default, host paths optional"""
volumes = []
# Main OS/image storage - use Docker volume by default
storage_type = config.get('storage_type', 'docker_volume') # 'docker_volume' or 'host_directory'
if storage_type == 'host_directory' and config.get('data_volume'):
# Use explicitly provided host directory path
volumes.append(f"{config['data_volume']}:/storage")
logging.info(f"Using host directory for OS storage: {config['data_volume']}")
else:
# Use Docker named volume (default)
container_name = config.get('name', 'windows')
volume_name = f"{container_name}_os_data"
volumes.append(f"{volume_name}:/storage")
logging.info(f"Using Docker volume for OS storage: {volume_name}")
# File sharing volume (optional) - for sharing files between host and container
if config.get('enable_file_sharing', False):
# Auto-select based on Windows version for file sharing path
version = config.get('version', '')
file_share_path = self._get_version_specific_volume_path(version)
# Ensure the volume directory exists
if not self._ensure_volume_directory(file_share_path):
logging.warning(f"Failed to create file sharing directory {file_share_path}, using default")
file_share_path = "/opt/windows/xfer"
# Mount file sharing directory to a different location than OS storage
volumes.append(f"{file_share_path}:/file_share")
logging.info(f"Added file sharing mount: {file_share_path}:/file_share")
# Additional volumes
if config.get('additional_volumes'):
for volume in config['additional_volumes']:
if isinstance(volume, dict) and 'host' in volume and 'container' in volume:
volumes.append(f"{volume['host']}:{volume['container']}")
elif isinstance(volume, str):
volumes.append(volume)
return volumes
def _generate_docker_volumes(self, config: Dict[str, Any]) -> Dict[str, Any]:
"""Generate Docker volume definitions for named volumes"""
volumes = {}
# Only create volume definitions if using Docker volumes (not host directories)
storage_type = config.get('storage_type', 'docker_volume')
if storage_type == 'docker_volume':
container_name = config.get('name', 'windows')
volume_name = f"{container_name}_os_data"
volumes[volume_name] = {
'driver': 'local',
'name': volume_name
}
logging.info(f"Added Docker volume definition: {volume_name}")
return volumes
def _generate_networks(self, config: Dict[str, Any]) -> Dict[str, Any]:
"""Generate Docker networks configuration"""
networks = {}
# Static IP network configuration
if config.get('network_mode') == 'static':
network_name = config.get('network_name', 'dokwinter-network')
networks[network_name] = {
'driver': 'bridge',
'ipam': {
'config': [{
'subnet': self._calculate_subnet(config.get('static_ip', ''), config.get('subnet_mask', '255.255.255.0')),
'gateway': config.get('gateway')
}]
}
}
# Note: Macvlan networks are created externally, not in docker-compose
# Additional network interfaces
if config.get('additional_networks'):
for i, network_config in enumerate(config['additional_networks']):
if isinstance(network_config, dict) and network_config.get('network'):
net_name = network_config['network']
networks[net_name] = {
'driver': 'bridge'
}
if network_config.get('ip') and network_config.get('subnet'):
networks[net_name]['ipam'] = {
'config': [{
'subnet': self._calculate_subnet(network_config.get('ip', ''), network_config.get('subnet', '255.255.255.0'))
}]
}
return networks
def _generate_service_networks(self, config: Dict[str, Any]) -> Dict[str, Any]:
"""Generate service network configuration"""
service_networks = {}
# Static IP configuration
if config.get('network_mode') == 'static' and config.get('static_ip'):
network_name = config.get('network_name', 'dokwinter-network')
service_networks[network_name] = {
'ipv4_address': config['static_ip']
}
# Additional network interfaces
if config.get('additional_networks'):
for network_config in config['additional_networks']:
if isinstance(network_config, dict) and network_config.get('network'):
net_name = network_config['network']
service_networks[net_name] = {}
if network_config.get('ip'):
service_networks[net_name]['ipv4_address'] = network_config['ip']
return service_networks
def _calculate_subnet(self, ip_address: str, subnet_mask: str) -> str:
"""Calculate subnet CIDR from IP and mask"""
if not ip_address or not subnet_mask:
return "172.20.0.0/16" # Default subnet
try:
# Convert subnet mask to CIDR notation
mask_parts = subnet_mask.split('.')
if len(mask_parts) == 4:
cidr = sum([bin(int(part)).count('1') for part in mask_parts])
ip_parts = ip_address.split('.')
if len(ip_parts) == 4:
# Calculate network address
network_parts = []
for i in range(4):
network_parts.append(str(int(ip_parts[i]) & int(mask_parts[i])))
return f"{'.'.join(network_parts)}/{cidr}"
except (ValueError, IndexError):
pass
return "172.20.0.0/16" # Fallback subnet
def generate_macvlan_setup_script(self, config: Dict[str, Any]) -> str:
"""Generate script to create macvlan network"""
network_name = config.get('macvlan_network_name', 'macvlan')
parent_interface = config.get('macvlan_parent', 'eth0')
subnet = config.get('macvlan_subnet', '192.168.1.0/24')
gateway = config.get('macvlan_gateway', '192.168.1.1')
ip_range = config.get('macvlan_ip_range', '192.168.1.192/27')
aux_address = config.get('macvlan_aux_address', '')
script = "#!/bin/bash\n\n"
script += "# DockWINterface Macvlan Network Setup Script\n"
script += f"# Generated for container: {config.get('name', 'windows')}\n\n"
script += "# Check if network already exists\n"
script += f"if docker network ls | grep -q '{network_name}'; then\n"
script += f" echo 'Network {network_name} already exists'\n"
script += "else\n"
script += " echo 'Creating macvlan network...'\n"
script += " docker network create -d macvlan \\\n"
script += f" --subnet={subnet} \\\n"
script += f" --gateway={gateway} \\\n"
script += f" --ip-range={ip_range} \\\n"
if aux_address:
script += f" --aux-address='host={aux_address}' \\\n"
script += f" -o parent={parent_interface} \\\n"
script += f" {network_name}\n"
script += "fi\n\n"
# Add host access configuration if aux_address is provided
if aux_address and config.get('macvlan_enable_host_access'):
shim_name = f"{network_name}-shim"
script += "# Configure host access to macvlan network\n"
script += f"echo 'Setting up host access via {shim_name}...'\n"
script += f"sudo ip link add {shim_name} link {parent_interface} type macvlan mode bridge\n"
script += f"sudo ip addr add {aux_address}/32 dev {shim_name}\n"
script += f"sudo ip link set {shim_name} up\n"
script += f"sudo ip route add {ip_range} dev {shim_name}\n"
script += f"echo 'Host can now communicate with containers via {aux_address}'\n\n"
script += "echo 'Macvlan network setup complete!'\n"
return script
def generate_env_file(self, config: Dict[str, Any]) -> str:
"""Generate .env file content"""
env_content = "# DockWINterface Generated Environment File\n"
env_content += f"# Generated for container: {config.get('name', 'windows')}\n\n"
env_vars = self._generate_environment_vars(config, for_env_file=True)
for var in env_vars:
env_content += f"{var}\n"
# Debug logging for password escaping
if config.get('password'):
logging.info(f"Original password: {config.get('password')}")
escaped_password = self._escape_env_value(config.get('password'), for_env_file=True)
logging.info(f"Escaped password: {escaped_password}")
# Additional Docker-specific settings
env_content += "\n# Container Configuration\n"
env_content += f"CONTAINER_NAME={config.get('name', 'windows')}\n"
env_content += f"RDP_PORT={config.get('rdp_port', '3389')}\n"
env_content += f"VNC_PORT={config.get('vnc_port', '8006')}\n"
logging.info(f"Generated .env file content:\n{env_content}")
return env_content
def validate_macvlan_config(self, config: Dict[str, Any]) -> List[str]:
"""Validate macvlan-specific configuration"""
errors = []
if config.get('network_mode') == 'macvlan':
# Check required macvlan fields
if not config.get('macvlan_subnet'):
errors.append("Macvlan subnet is required (e.g., 192.168.1.0/24)")
if not config.get('macvlan_gateway'):
errors.append("Macvlan gateway is required (e.g., 192.168.1.1)")
if not config.get('macvlan_parent'):
errors.append("Parent network interface is required (e.g., eth0)")
# Validate IP format if static IP is provided
if config.get('macvlan_ip'):
import re
ip_pattern = r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$'
if not re.match(ip_pattern, config['macvlan_ip']):
errors.append("Invalid macvlan IP address format")
# Validate subnet format
if config.get('macvlan_subnet'):
import re
subnet_pattern = r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/\d{1,2}$'
if not re.match(subnet_pattern, config['macvlan_subnet']):
errors.append("Invalid subnet format (use CIDR notation, e.g., 192.168.1.0/24)")
return errors
def validate_config(self, config: Dict[str, Any]) -> Dict[str, Any]:
"""Validate configuration parameters"""
errors = []
warnings = []
# Required fields
required_fields = ['name', 'version', 'username', 'password']
for field in required_fields:
if not config.get(field):
errors.append(f"Missing required field: {field}")
# Validate container name
if config.get('name'):
name = config['name']
if not name.replace('-', '').replace('_', '').isalnum():
errors.append("Container name can only contain letters, numbers, hyphens, and underscores")
# Validate password strength
password = config.get('password', '')
if password and len(password) < 8:
warnings.append("Password should be at least 8 characters long")
# Validate resource limits
if config.get('cpu_cores'):
try:
cpu_cores = int(config['cpu_cores'])
if cpu_cores < 1 or cpu_cores > 32:
warnings.append("CPU cores should be between 1 and 32")
except ValueError:
errors.append("CPU cores must be a valid number")
if config.get('ram_size'):
try:
ram_size = int(config['ram_size'])
if ram_size < 2 or ram_size > 128:
warnings.append("RAM size should be between 2GB and 128GB")
except ValueError:
errors.append("RAM size must be a valid number")
if config.get('disk_size'):
try:
disk_size = int(config['disk_size'])
if disk_size < 20 or disk_size > 1000:
warnings.append("Disk size should be between 20GB and 1000GB")
except ValueError:
errors.append("Disk size must be a valid number")
# Validate ports
for port_field in ['rdp_port', 'vnc_port']:
if config.get(port_field):
try:
port = int(config[port_field])
if port < 1024 or port > 65535:
warnings.append(f"{port_field} should be between 1024 and 65535")
except ValueError:
errors.append(f"{port_field} must be a valid port number")
# Validate macvlan configuration if applicable
macvlan_errors = self.validate_macvlan_config(config)
errors.extend(macvlan_errors)
return {
'valid': len(errors) == 0,
'errors': errors,
'warnings': warnings
}
def save_config_files(self, config: Dict[str, Any]):
"""Save generated configuration files to disk"""
container_name = config.get('name', 'windows')
# Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
# Generate content
docker_compose = self.generate_docker_compose(config)
env_file = self.generate_env_file(config)
# Save docker-compose.yml
compose_path = os.path.join(self.output_dir, f"{container_name}-docker-compose.yml")
with open(compose_path, 'w') as f:
f.write(docker_compose)
# Save .env file
env_path = os.path.join(self.output_dir, f"{container_name}.env")
with open(env_path, 'w') as f:
f.write(env_file)
# Save configuration JSON for reference
config_path = os.path.join(self.output_dir, f"{container_name}-config.json")
with open(config_path, 'w') as f:
json.dump(config, f, indent=2)
# Save macvlan setup script if using macvlan
script_path = None
if config.get('network_mode') == 'macvlan':
macvlan_script = self.generate_macvlan_setup_script(config)
script_path = os.path.join(self.output_dir, f"{container_name}-setup-macvlan.sh")
with open(script_path, 'w') as f:
f.write(macvlan_script)
# Make script executable
os.chmod(script_path, 0o755)
logging.info(f"Configuration files saved for {container_name}")
result = {
'docker_compose_path': compose_path,
'env_path': env_path,
'config_path': config_path
}
if script_path:
result['macvlan_script_path'] = script_path
return result
class RemoteDockerDeployer:
def __init__(self, docker_host: str):
self.docker_host = docker_host
def deploy(self, config: Dict[str, Any], docker_compose: str, env_file: str = None) -> Dict[str, Any]:
"""Deploy container to remote Docker host"""
try:
container_name = config.get('name', 'windows')
# Parse docker-compose YAML to extract configuration
import yaml
compose_data = yaml.safe_load(docker_compose)
service_config = compose_data.get('services', {}).get(container_name, {})
# Set DOCKER_HOST environment variable only for TCP connections
env = os.environ.copy()
if self.docker_host.startswith('tcp://'):
env['DOCKER_HOST'] = self.docker_host
# Build docker run command
cmd = ['docker', 'run', '-d', '--name', container_name]
# Add ports
if 'ports' in service_config:
for port in service_config['ports']:
cmd.extend(['-p', port])
# Add environment variables
# Use proper RFC 1918 private IP for internal VM network instead of Microsoft public IP space
if "VM_NET_IP" not in service_config.get("environment", {}):
cmd_parts.extend(["-e", "VM_NET_IP=192.168.250.21"])
if 'environment' in service_config:
for key, value in service_config['environment'].items():
# Ensure value is a string and properly formatted
value_str = str(value) if value is not None else ''
cmd.extend(['-e', f"{key}={value_str}"])
# Add volumes
if 'volumes' in service_config:
for volume in service_config['volumes']:
cmd.extend(['-v', volume])
# Add restart policy
if 'restart' in service_config:
cmd.extend(['--restart', service_config['restart']])
# Add network mode
if 'network_mode' in service_config:
cmd.extend(['--network', service_config['network_mode']])
# Add privileged if needed
if service_config.get('privileged'):
cmd.append('--privileged')
# Add capabilities
if 'cap_add' in service_config:
for cap in service_config['cap_add']:
cmd.extend(['--cap-add', cap])
# Add devices - check if they exist first
if 'devices' in service_config:
for device in service_config['devices']:
# Skip /dev/kvm if it doesn't exist (common in containers)
if device == '/dev/kvm' and not os.path.exists(device):
logging.warning(f"Skipping device {device} as it doesn't exist")
continue
cmd.extend(['--device', device])
# Add image - ensure it exists
image = service_config.get('image', 'dockurr/windows')
cmd.append(image)
logging.info(f"Deploying container with command: {' '.join(cmd)}")
print(f"DEBUG: Docker command: {' '.join(cmd)}") # Debug output
# First, stop and remove any existing container with the same name
stop_cmd = ['docker', 'stop', container_name]
subprocess.run(stop_cmd, env=env, capture_output=True, text=True, timeout=30)
rm_cmd = ['docker', 'rm', container_name]
subprocess.run(rm_cmd, env=env, capture_output=True, text=True, timeout=30)
# Deploy container
result = subprocess.run(cmd, env=env, capture_output=True, text=True, timeout=300)
print(f"DEBUG: Docker run result - returncode: {result.returncode}, stdout: {result.stdout}, stderr: {result.stderr}") # Debug output
if result.returncode == 0:
container_id = result.stdout.strip()
# Handle post-creation network connection for macvlan
if (config.get("network_mode") == "macvlan" and config.get("macvlan_ip") and
service_config.get("network_mode") != "macvlan"):
# Container was created with bridge network, now connect to macvlan
network_name = config.get("macvlan_network_name", "macvlan")
macvlan_ip = config["macvlan_ip"]
logging.info(f"Connecting container to macvlan network {network_name} with IP {macvlan_ip}")
# Disconnect from bridge network first
disconnect_cmd = ["docker", "network", "disconnect", "bridge", container_name]
disconnect_result = subprocess.run(disconnect_cmd, env=env, capture_output=True, text=True, timeout=30)
# Connect to macvlan network with specific IP
connect_cmd = ["docker", "network", "connect", "--ip", macvlan_ip, network_name, container_name]
connect_result = subprocess.run(connect_cmd, env=env, capture_output=True, text=True, timeout=30)
if connect_result.returncode != 0:
logging.warning(f"Failed to connect to macvlan network: {connect_result.stderr}")
else:
logging.info(f"Successfully connected container to macvlan network with IP {macvlan_ip}")
return {
'success': True,
'container_id': container_id,
'output': f"Container {container_name} deployed successfully"
}
else:
return {
'success': False,
'error': f"Docker deployment failed: {result.stderr}",
'output': result.stdout
}
except subprocess.TimeoutExpired:
return {
'success': False,
'error': 'Deployment timed out after 5 minutes'
}
except Exception as e:
logging.error(f"Remote deployment error: {str(e)}", exc_info=True)
return {
'success': False,
'error': f"Deployment failed: {str(e)}"
}
def fix_container_network_post_deployment(self, config: Dict[str, Any]) -> Dict[str, Any]:
"""
Universal network fixer that runs after deployment to ensure containers
are connected to the correct network, regardless of deployment method.
"""
try:
container_name = config.get('name', 'windows')
# Check if this is a macvlan configuration that needs network fixing
if (config.get('network_mode') == 'macvlan' and config.get('macvlan_ip')):
network_name = config.get('macvlan_network_name', 'macvlan')
macvlan_ip = config['macvlan_ip']
logging.info(f"Post-deployment network check for {container_name}")
# Check current network configuration
inspect_cmd = ['docker', 'inspect', container_name, '--format={{json .NetworkSettings.Networks}}']
result = subprocess.run(inspect_cmd, capture_output=True, text=True, timeout=30)
if result.returncode == 0:
import json
networks = json.loads(result.stdout)
# Check if container is on macvlan network with correct IP
macvlan_network = networks.get(network_name)
if not macvlan_network or macvlan_network.get('IPAddress') != macvlan_ip:
logging.info(f"Container {container_name} needs network fix - connecting to {network_name} with IP {macvlan_ip}")
# Stop container first
subprocess.run(['docker', 'stop', container_name], capture_output=True, timeout=30)
# Disconnect from bridge network if connected
if 'bridge' in networks:
subprocess.run(['docker', 'network', 'disconnect', 'bridge', container_name],
capture_output=True, timeout=30)
# Connect to macvlan network
connect_cmd = ['docker', 'network', 'connect', '--ip', macvlan_ip, network_name, container_name]
connect_result = subprocess.run(connect_cmd, capture_output=True, text=True, timeout=30)
# Start container
subprocess.run(['docker', 'start', container_name], capture_output=True, timeout=30)
if connect_result.returncode == 0:
logging.info(f"Successfully fixed network for {container_name}")
return {'success': True, 'message': 'Network configuration fixed'}
else:
logging.error(f"Failed to fix network: {connect_result.stderr}")
return {'success': False, 'error': f'Network fix failed: {connect_result.stderr}'}
else:
logging.info(f"Container {container_name} already has correct network configuration")
return {'success': True, 'message': 'Network already correctly configured'}
return {'success': True, 'message': 'No network fix needed'}
except Exception as e:
logging.error(f"Post-deployment network fix error: {str(e)}")
return {'success': False, 'error': f'Network fix failed: {str(e)}'}