-
Notifications
You must be signed in to change notification settings - Fork 2
/
initIOCs.py
executable file
·997 lines (775 loc) · 40 KB
/
initIOCs.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
#!/usr/bin/env python3
"""Script for auto initialization of IOCs from CONFIGURE file.
This script was taken from the installSynApps set of scripts.
Usage instructions can be found in the README.md file in this repo.
Author: Jakub Wlodek
"""
# imports
import os
import re
import time
import shutil
import subprocess
import argparse
import datetime
import sys
WITH_YAML=True
try:
import yaml
except ImportError:
WITH_YAML=False
from sys import platform
# variables used to allow for printing text to GUI or stdout depending on usage
USING_GUI=False
GUI_TOP_WINDOW=None
# version number
__version__ = "v0.1.0"
#-------------------------------------------------
#-------- CONSTANTS AND REQ. DATA STRUCTS --------
#-------------------------------------------------
# Bash shebang length limit is 127 characters, so we need to make sure we account for that
KERNEL_PATH_LIMIT = 127
# list of currently supported drivers (for template based generation). Also used for dropdown in GUI
supported_drivers = [
'ADProsilica',
'ADUVC',
'ADPointGrey',
'ADLambda',
'ADSimDetector',
'ADMerlin',
'ADPerkinElmer',
'ADPilatus',
'ADSpinnaker',
'ADAndor3',
'ADURL',
'ADPSL',
'ADEiger',
]
# Tooltip messages for the configuration options
config_tooltips = {
'IOC_DIR' : 'Top level IOC output directory',
'TOP_BINARY_DIR' : 'Location of compiled binaries on your system.',
'PREFIX' : 'Generic prefix added to start of each IOC PV name. Unique portion will be autogenerated',
'ENGINEER' : 'Engineer deploying the IOCs',
'HOSTNAME' : 'Hostname of IOC server on which it will be deployed',
'CA_ADDRESS' : 'Channel access address list IP'
}
# Some default values for generating a temporary CONFIGURE file.
base_configuration = {
'ioc_dir' : '/epics/iocs',
'bundle_location' : '/epics/src',
'beamline_prefix' : 'DEVEL1:',
'engineer' : 'C. Engineer',
'hostname' : 'localhost',
'ca_address_ip' : '127.0.0.255'
}
existing_connection_parameter = {
"ADEiger" : "EIGER_IP",
"ADAravis" : "CAMERA_NAME",
"ADVimba" : "CAMERA_ID",
"ADSpinnaker" : "CAMERA_ID",
"ADUVC" : "UVC_SERIAL"
}
# On windows default to C directory
if platform == 'win32':
base_configuration['ioc_dir'] = 'C:' + base_configuration['ioc_dir']
base_configuration['bundle_location'] = 'C:' + base_configuration['bundle_location']
# External areaDetector plugins
ad_plugins = ['ADCompVision', 'ADPluginBar', 'ADPluginEdge', 'ADPluginDmtx']
#-------------------------------------------------
#------------ INTERNAL DATA MODEL CLASS ----------
#-------------------------------------------------
def initIOC_path_join(path_A, path_B):
"""Function that joins two paths.
All paths use / instead of \\ for simplicity.
"""
output_path = path_A
if not path_A.endswith('/'):
output_path = output_path + '/'
if path_B.startswith('/'):
output_path = output_path + path_B[1:]
else:
output_path = output_path + path_B
if output_path.endswith('/'):
output_path = output_path[:-1]
return output_path
class IOCActionManager:
def __init__(self, ioc_top, binary_location, set_lib_path, use_template, with_deps, use_links):
self.ioc_top = ioc_top
self.ioc_top_created = False
self.binary_location = binary_location
self.binaries_flat = self.check_binaries_flat()
self.set_lib_path = set_lib_path
self.use_template = use_template
self.with_deps = with_deps
self.use_links = use_links
self.processed_actions = []
self.update_mod_paths()
def check_binaries_flat(self):
if os.path.exists(initIOC_path_join(self.binary_location, 'support')):
return False
return True
def deployment_info(self, action):
"""Function that generates string of info for current IOCAction
"""
info = ''
info = info + '#\n# {} IOC deployed using initIOC {}\n'.format(action.ioc_type, __version__)
info = info + '# Initial target bundle location: {}\n'.format(self.binary_location)
if self.use_template:
info = info + '# IOC generated from: https://github.com/epicsNSLS2-deploy/ioc-template\n'
else:
_, _, iocBoot_path = self.find_paths_for_action(action.ioc_type)
if iocBoot_path is not None:
info = info + '# IOC generated from: {}\n'.format(iocBoot_path)
info = info + '#{}\n'.format('-' * 64)
return info
def update_mod_paths(self):
"""Function that sets the paths of core modules based on binary location and format
"""
self.binaries_flat = self.check_binaries_flat()
self.base_path = initIOC_path_join(self.binary_location, 'base')
if self.binaries_flat:
self.support_path = self.binary_location
else:
self.support_path = initIOC_path_join(self.binary_location, 'support')
self.areaDetector_path = initIOC_path_join(self.support_path, 'areaDetector')
def find_paths_for_action(self, ioc_type):
"""Finds ioc_top, executable, and iocBoot folder for IOCAction
"""
try:
driver_path = initIOC_path_join(self.areaDetector_path, ioc_type)
# identify the IOCs folder
for name in os.listdir(driver_path):
if "ioc" == name or "iocs" == name:
driver_path = initIOC_path_join(driver_path, name)
break
# identify the IOC
for name in os.listdir(driver_path):
# Add check to see if NOIOC in name - occasional problems generating ADSimDetector
if ("IOC" in name or "ioc" in name) and "NOIOC" not in name.upper():
driver_path = initIOC_path_join(driver_path, name)
break
ioc_top_path = driver_path
# find the driver executable
executable_path = initIOC_path_join(driver_path, "bin")
# There should only be one architecture in the bundle
for name in os.listdir(executable_path):
executable_path = initIOC_path_join(executable_path, name)
break
# We look for the executable that ends with App
for name in os.listdir(executable_path):
if 'App' in name:
executable_path = initIOC_path_join(executable_path, name)
break
iocBoot_path = initIOC_path_join(driver_path, 'iocBoot')
for dir in os.listdir(iocBoot_path):
if dir.startswith('ioc') and os.path.isdir(initIOC_path_join(iocBoot_path, dir)) and not dir.endswith('Test'):
iocBoot_path = initIOC_path_join(iocBoot_path, dir)
break
return ioc_top_path, executable_path, iocBoot_path
except:
return None, None, None
def get_lib_path_for_module(self, module_path, architecture, delimeter):
"""Generates a library path for specific module
"""
bin_loc = initIOC_path_join(module_path, 'bin')
bin_loc = initIOC_path_join(bin_loc, architecture)
lib_loc = initIOC_path_join(module_path, 'lib')
lib_loc = initIOC_path_join(lib_loc, architecture)
return bin_loc + delimeter + lib_loc + delimeter
def get_lib_path_str(self, action):
"""Function that generates library path for shared built iocs
Parameters
----------
action : IOCAction
ioc action for which we are generating lib path.
Returns
-------
lib_path : str
Library path set in form of str
"""
lib_path_str = ''
if platform == "win32":
delimeter = ';'
closer = '%PATH%"'
arch='windows-x64-static'
else:
arch = 'linux-x86_64'
delimeter = ':'
closer = '$LD_LIBRARY_PATH'
if platform == "win32":
lib_path_str = lib_path_str + 'SET "PATH='
else:
lib_path_str = lib_path_str + 'export LD_LIBRARY_PATH='
lib_path_str = lib_path_str + self.get_lib_path_for_module(self.base_path, arch, delimeter)
if os.path.exists(self.support_path) and os.path.isdir(self.support_path):
for dir in os.listdir(self.support_path):
mod_path = initIOC_path_join(self.support_path, dir)
if os.path.isdir(mod_path) and dir != "base" and dir != "areaDetector":
lib_path_str = lib_path_str + self.get_lib_path_for_module(mod_path, arch, delimeter)
if os.path.exists(self.areaDetector_path) and os.path.isdir(self.areaDetector_path):
for dir in os.listdir(self.areaDetector_path):
mod_path = initIOC_path_join(self.areaDetector_path, dir)
if os.path.isdir(mod_path) and (dir == 'ADCore' or dir == 'ADSupport' or dir in ad_plugins or dir == action.ioc_type):
lib_path_str = lib_path_str + self.get_lib_path_for_module(mod_path, arch, delimeter)
lib_path_str = lib_path_str + closer
return lib_path_str
def initialize_ioc_directory(self):
"""Function used to create a new IOC directory if it does not already exist
"""
if not os.path.exists(os.path.dirname(self.ioc_top)):
initIOC_print('ERROR - IOC top directory {} could not be created'.format(self.ioc_top))
else:
if os.path.exists(self.ioc_top):
initIOC_print('IOC top directory already exists.\n')
else:
try:
initIOC_print('Creating IOC directory at {}.\n'.format(self.ioc_top))
os.mkdir(self.ioc_top)
except PermissionError:
initIOC_print('ERROR - You do not have permissions to write to specified directory!')
return False
self.ioc_top_created = True
return True
def initialize_st_base_file(self, ioc_path, lib_path, executable_path):
"""Function responsible for handling executable path injection, and base file creation
"""
exec_written = False
if platform == 'win32':
# On windows, no shebangs, so st.cmd will always run executable followed by st_base.cmd
st_exe = open(initIOC_path_join(ioc_path, 'st.cmd'), 'w+')
st_exe.write('@echo OFF\n\n{}\n\n{} st_base.cmd\n'.format(lib_path, executable_path))
st_exe.close()
st = open(initIOC_path_join(ioc_path, "st_base.cmd"), "w+")
exec_written = True
elif len(executable_path) > KERNEL_PATH_LIMIT or self.set_lib_path:
if len(executable_path) > KERNEL_PATH_LIMIT:
# The path length limit for shebangs (#!/) on linux is usually kernel based and set to 127
initIOC_print('WARNING - Path to executable exceeds legal bash shebang limit, splitting into st.cmd and st_base.cmd')
else:
# If we want to set LD_LIBRARY_PATH we do that here.
initIOC_print('Appending library path to start of st.cmd...')
st_exe = open(initIOC_path_join(ioc_path, 'st.cmd'), 'w+')
st_exe.write('#!/bin/bash\n\n{}\n\n{} st_base.cmd\n'.format(lib_path, executable_path))
st_exe.close()
st = open(initIOC_path_join(ioc_path, "st_base.cmd"), "w+")
exec_written = True
else:
st = open(initIOC_path_join(ioc_path, "st.cmd"), "w+")
return st, exec_written
def genertate_st_cmd(self, action, executable_path, st_base_path):
initIOC_print('Generating st.cmd using base file:\n{}'.format(st_base_path))
ioc_path = initIOC_path_join(self.ioc_top, action.ioc_name)
lib_path = ''
if self.set_lib_path:
lib_path = self.get_lib_path_str(action)
# Create base st.cmd, add call to executable
st, exec_written = self.initialize_st_base_file(ioc_path, lib_path, executable_path)
# If the executable will be in the base file, write the shebang
if not exec_written:
st.write('#!{}\n\n'.format(executable_path))
# Define envPaths
st.write('< envPaths\n\n')
# Open existing st.cmd base file
st_base_fp = open(st_base_path, 'r')
# Read through the lines, add a 'unique.cmd' call after all env sets, and add envSet calls to action environment
lines = st_base_fp.readlines()
wrote_unique = False
for line in lines:
if line.startswith('#!') or 'unique.cmd' in line or 'envPaths' in line:
pass
elif line.startswith('#'):
st.write(line)
elif 'Config(' in line and not wrote_unique:
st.write('\n< unique.cmd\n\n')
st.write(line)
wrote_unique = True
elif line.startswith('epicsEnvSet'):
action.add_to_environment(line)
st.write(line)
else:
st.write(line)
st_base_fp.close()
st.close()
# Collect environment variables set in any other files
self.grab_additional_env(action, st_base_path)
# Make st.cmd executable.
os.chmod(initIOC_path_join(ioc_path, "st.cmd"), 0o755)
def grab_additional_env(self, action, st_base_path):
"""Function that collects any additional environment variables for IOC
"""
iocBoot_dir = os.path.dirname(st_base_path)
st_file = os.path.basename(st_base_path)
for file in os.listdir(iocBoot_dir):
# For any file that isnt the base file, add environment variables.
if file.startswith('st') and file.endswith('.cmd') and file != st_file:
fp = open(os.path.join(iocBoot_dir, file), 'r')
lines = fp.readlines()
for line in lines:
if line.startswith('epicsEnvSet'):
action.add_to_environment(line)
fp.close()
def generate_unique_cmd(self, action):
initIOC_print('Generating unique.cmd from detected environment...')
ioc_path = initIOC_path_join(self.ioc_top, action.ioc_name)
unique_fp = open(initIOC_path_join(ioc_path, 'unique.cmd'), 'w')
unique_fp.write('#############################################\n')
unique_fp.write('# initIOC Auto-Generated Unique File #\n')
unique_fp.write('# Generated: {:<31}#\n'.format(str(datetime.datetime.now())))
if 'ENGINEER' in action.epics_environment.keys():
unique_fp.write('# Deploying Engineer: {:<22}#\n'.format(action.epics_environment['ENGINEER']))
unique_fp.write('#############################################\n\n\n')
unique_fp.write(self.deployment_info(action)+'\n\n')
for env_var in action.epics_environment.keys():
if env_var in existing_connection_parameter.keys():
unique_fp.write('epicsEnvSet("{}",{}"{}"'.format(env_var, ' ' * (32 - len(env_var)), action.connection))
else:
unique_fp.write('epicsEnvSet("{}",{}"{}")\n'.format(env_var, ' ' * (32 - len(env_var)), action.epics_environment[env_var]))
unique_fp.close()
def get_env_paths_name(self, module):
if module == 'seq':
return 'SNCSEQ'
elif module == 'iocStats':
return 'DEVIOCSTATS'
elif module == 'areaDetector':
return 'AREA_DETECTOR'
else:
return module.upper()
def generate_env_paths(self, ioc_top_path, ioc_boot_path, target, action):
if not self.use_links:
initIOC_print('Generating envPaths based on discovered compiled binaries...')
ioc_path = initIOC_path_join(self.ioc_top, action.ioc_name)
envPaths_fp = open(initIOC_path_join(ioc_path, 'envPaths'), 'w')
arch='linux-x86_64'
if platform == 'win32':
arch = 'windows-x64-static'
envPaths_fp.write('# Path propagated to remaining envPaths (binary bundle location)\nepicsEnvSet("BINARY_TOP", "{}")\n\n'.format(self.binary_location))
envPaths_fp.write('epicsEnvSet("ARCH", "{}")\n'.format(arch))
envPaths_fp.write('epicsEnvSet("TOP", "{}")\n'.format(ioc_top_path))
base_path = initIOC_path_join('$(BINARY_TOP)', 'base')
envPaths_fp.write('epicsEnvSet("EPICS_BASE",{}"{}")\n'.format((' ' * 14), base_path))
support_path = "$(BINARY_TOP)"
if not self.binaries_flat:
support_path = initIOC_path_join(support_path, "support")
envPaths_fp.write('epicsEnvSet("SUPPORT",{}"{}")\n\n'.format((' ' * 17), support_path))
for dir in os.listdir(self.support_path):
mod_path = initIOC_path_join(self.support_path, dir)
if os.path.isdir(mod_path) and dir not in ['base', 'configure', 'utils', 'documentation', '.git', 'lib', 'bin']:
mod_path = initIOC_path_join('$(SUPPORT)', dir)
envPaths_fp.write('epicsEnvSet("{}",{}"{}")\n'.format(self.get_env_paths_name(dir), ' ' * (24 - len(self.get_env_paths_name(dir))), mod_path))
envPaths_fp.write('\n')
for dir in os.listdir(self.areaDetector_path):
mod_path = initIOC_path_join(self.areaDetector_path, dir)
if os.path.isdir(mod_path) and dir not in ['configure', 'docs', 'documentation', 'ci', '.git', '']:
mod_path = initIOC_path_join('$(AREA_DETECTOR)', dir)
envPaths_fp.write('epicsEnvSet("{}",{}"{}")\n'.format(self.get_env_paths_name(dir), ' ' * (24 - len(self.get_env_paths_name(dir))), mod_path))
envPaths_fp.close()
else:
os.symlink(initIOC_path_join(ioc_boot_path, 'envPaths'), initIOC_path_join(target, 'envPaths'))
def process_action(self, action):
if not self.ioc_top_created:
ret = self.initialize_ioc_directory()
if not ret:
return
initIOC_print("-------------------------------------------")
initIOC_print("Setup process for IOC " + action.ioc_name)
initIOC_print("-------------------------------------------")
from_template = self.use_template
ioc_top_path, executable_path, iocBoot_path = self.find_paths_for_action(action.ioc_type)
if executable_path is None:
initIOC_print('ERROR - Could not find binary for {}, skipping...'.format(action.ioc_type))
initIOC_print('Make sure binary for {} exists at binary path:\n{}'.format(action.ioc_type, self.binary_location))
return
elif ioc_top_path is None or iocBoot_path is None:
if not from_template:
initIOC_print('WARNING - Could not find ioc top and iocBoot folder, defaulting to use template.')
from_template = True
if os.path.exists(initIOC_path_join(self.ioc_top, action.ioc_name)):
initIOC_print('ERROR - IOC with name {} already exists in {}.'.format(action.ioc_name, self.ioc_top))
return
if not from_template:
self.create_ioc_from_bundle(action, ioc_top_path, executable_path, iocBoot_path)
else:
self.create_ioc_from_template(action, executable_path)
self.create_config_file(action)
#self.make_ignore_files(action) TODO
initIOC_print('Done.\n')
def create_config_file(self, action):
initIOC_print('Generating config file for use with procServ...')
ioc_path = initIOC_path_join(self.ioc_top, action.ioc_name)
config_fp = open(initIOC_path_join(ioc_path, 'config'), 'w')
config_fp.write('NAME={}\nPORT={}\nUSER=softioc\nHOST={}\n'.format(action.ioc_name, action.ioc_port, action.epics_environment['HOSTNAME']))
config_fp.close()
def create_ioc_from_bundle(self, action, ioc_top_path, executable_path, iocBoot_path):
initIOC_print('Generating IOC from detected bundle located at: {}'.format(self.binary_location))
time.sleep(0.3)
ioc_path = initIOC_path_join(self.ioc_top, action.ioc_name)
os.mkdir(ioc_path)
os.mkdir(initIOC_path_join(ioc_path, 'autosave'))
current_base_len = 0
current_base = None
for file in os.listdir(iocBoot_path):
next = initIOC_path_join(iocBoot_path, file)
if os.path.isfile(next) and file.startswith('st'):
fp = open(next, 'r')
lines = fp.readlines()
fp.close()
if len(lines) > current_base_len:
current_base = next
current_base_len = len(lines)
if current_base is None:
initIOC_print('ERROR - Could not fine suitable st_base file. Aborting...')
return
self.genertate_st_cmd(action, executable_path, current_base)
self.generate_unique_cmd(action)
self.generate_env_paths(ioc_top_path, iocBoot_path, ioc_path, action)
self.grab_dependencies_from_bundle(ioc_path, iocBoot_path)
def grab_dependencies_from_bundle(self, ioc_path, iocBoot_path):
initIOC_print('Collecting additional iocBoot files from bundle...')
for file in os.listdir(iocBoot_path):
target = initIOC_path_join(iocBoot_path, file)
if os.path.isfile(target):
if file == 'auto_settings.req':
if not self.use_links:
shutil.copyfile(target, initIOC_path_join(ioc_path, file))
else:
os.symlink(target, initIOC_path_join(ioc_path, file))
elif self.with_deps and not file.startswith(('Makefile', 'st', 'test', 'READ', 'dll', 'envPaths')):
shutil.copyfile(target, initIOC_path_join(ioc_path, file))
def create_ioc_from_template(self, action, executable_path):
ioc_path = initIOC_path_join(self.ioc_top, action.ioc_name)
# First, clone the template:
out = subprocess.call(["git", "clone", "--quiet", "https://github.com/epicsNSLS2-deploy/ioc-template", ioc_path])
if out != 0:
initIOC_print('ERROR - Failed to clone IOC template, aborting...')
else:
initIOC_print('Generating IOC from ioc-template (https://github.com/epicsNSLS2-deploy/ioc-temlpate)')
os.remove(initIOC_path_join(ioc_path, 'st.cmd'))
os.remove(initIOC_path_join(ioc_path, 'unique.cmd'))
os.remove(initIOC_path_join(ioc_path, 'envPaths'))
os.remove(initIOC_path_join(ioc_path, 'config'))
startup_scripts = initIOC_path_join(ioc_path, 'startupScripts')
self.genertate_st_cmd(action, executable_path, initIOC_path_join(startup_scripts, '{}St.cmd'.format(action.basename)))
self.generate_unique_cmd(action)
self.generate_env_paths(ioc_path, action)
autosave_file_path = initIOC_path_join(ioc_path, 'autosaveFiles')
dep_file_path = initIOC_path_join(ioc_path, 'dependancyFiles')
for file in os.listdir(autosave_file_path):
if file.startswith(action.basename):
shutil.copyfile(initIOC_path_join(autosave_file_path, file), initIOC_path_join(ioc_path, 'auto_settings.req'))
for file in os.listdir(dep_file_path):
if file.startswith(action.basename):
shutil.copyfile(initIOC_path_join(dep_file_path, file), initIOC_path_join(ioc_path, file.split('{}_'.format(action.basename))))
self.fix_macros(initIOC_path_join(ioc_path, file.split('{}_'.format(action.basename))), action)
self.cleanup_template(action, ioc_path)
def fix_macros(self, file_path, action):
"""
Function that replaces certain macros in given filepath (used primarily for substitution files)
Parameters
----------
file_path : str
path to the target file
"""
os.rename(file_path, file_path + '_OLD')
old = open(file_path+'_OLD', 'r')
contents = old.read()
contents = contents.replace('$(PREFIX)', action.ioc_prefix)
contents = contents.replace('$(PORT)', action.asyn_port)
new = open(file_path, 'w')
new.write(contents)
old.close()
new.close()
os.remove(file_path+'_OLD')
def cleanup_template(self, action, ioc_path):
initIOC_print('Performing cleanup for {}'.format(action.ioc_name))
try:
if platform == "win32":
cleanup_script = initIOC_path_join(ioc_path, 'cleanup.bat')
_ = subprocess.call([cleanup_script])
else:
cleanup_script = initIOC_path_join(ioc_path, 'cleanup.sh')
_ = subprocess.call(['bash', cleanup_script])
os.remove(cleanup_script)
except:
pass
class IOCAction:
"""Helper class that stores information and functions for each IOC in the CONFIGURE file
Attributes
----------
ioc_type : str
name of areaDetector driver instance the IOC is linked to ex. ADProsilica
ioc_name : str
name of the IOC ex. cam-ps1
ioc_prefix : str
Prefix used by the IOC
asyn_port : str
asyn port used for outputting NDArrays
ioc_port : str
telnet port on which procserver will run the IOC
connection : str
Value used to connect to the device ex. IP, serial num. etc.
"""
def __init__(self, ioc, bl_prefix):
"""Constructor for the IOCAction class
"""
self.epics_environment = {}
self.ioc_type = ioc['type']
self.basename = self.ioc_type[2:].lower()
# These epics environment variables are set by the user for each IOC
self.user_entered_env = ['ENGINEER', 'PORT', 'IOC', 'CAM-CONNECT', 'PREFIX', 'CTPREFIX', 'HOSTNAME', 'IOCNAME']
self.asyn_port = ioc['asyn_port']
self.epics_environment['PORT'] = self.asyn_port
self.epics_environment['IOC'] = 'ioc{}'.format(self.ioc_type)
self.epics_environment['EPICS_CA_AUTO_ADDR_LIST'] = 'NO'
self.epics_environment['EPICS_CA_ADDR_LIST'] = "NA"
self.epics_environment['EPICS_CA_MAX_ARRAY_BYTES'] = "6000000"
self.connection = ioc['connection']
self.ioc_prefix = ioc['device_prefix']
self.epics_environment['PREFIX'] = '{}{}'.format(bl_prefix, self.ioc_prefix)
self.epics_environment['CTPREFIX'] = '{}{}'.format(bl_prefix, self.ioc_prefix)
self.ioc_port = ioc['telnet_port']
self.ioc_name = ioc['name']
self.epics_environment['IOCNAME'] = self.ioc_name
def add_to_environment(self, line):
line_s = line.strip()
line_s = re.sub('"', '', line_s)
line_s = re.sub('\t', '', line_s)
line_s = re.sub(' +', '', line_s)
line_s = re.sub('epicsEnvSet', '', line_s)
temp = line_s.split(',')
if temp[0][1:] not in self.user_entered_env:
self.epics_environment[temp[0][1:]] = temp[1][:-1]
if self.ioc_type in existing_connection_parameter.keys():
if existing_connection_parameter[self.ioc_type] == temp[1][:-1]:
self.epics_environment[temp[0][1:]] = self.connection
#-------------------------------------------------
#----------------MAIN SCRIPT FUNCTIONS------------
#-------------------------------------------------
def read_ioc_config(config_path):
global WITH_YAML
if WITH_YAML:
with open(config_path, 'r') as configure:
config = yaml.full_load(configure)
return config
else:
initIOC_print('Error Python yaml library not installed!')
exit(-1)
def print_start_message():
"""Function for printing initial message
"""
initIOC_print("+----------------------------------------------------------------+")
initIOC_print("+ initIOCs, Version: " + __version__ +" +")
initIOC_print("+ Python Version: {}, OS platform: {:<27}+".format(sys.version.split()[0], platform))
initIOC_print("+ Copyright (c): Brookhaven National Laboratory 2018-2019 +")
initIOC_print("+ This software comes with NO warranty! +")
initIOC_print("+----------------------------------------------------------------+")
initIOC_print('')
def print_supported_drivers():
"""Function that prints list of supported drivers
"""
initIOC_print('Supported Drivers:')
initIOC_print("+-----------------------------+")
for driver in supported_drivers:
initIOC_print('+ {}'.format(driver))
initIOC_print('')
def prompt_for_top_dirs(with_welcome=True):
"""Function that asks user for target IOC and binary locations.
Parameters
----------
with_welcome : bool
If true, print welcome message
"""
ioc_top = ''
binaries_top = ''
if with_welcome:
print_start_message()
initIOC_print('Welcome to initIOC!')
valid = False
while not valid:
ioc_top = input('Enter the absolute ioc output location (/epics/iocs).\nUse "/" characters for delimeters.\n> ')
if not os.path.exists(os.path.dirname(ioc_top)):
initIOC_print('\nThe selected ioc output directory does not exist, please try again.\n')
elif os.path.isdir(ioc_top) and not os.access(ioc_top, os.W_OK):
initIOC_print('\nThe selected output directory exists, but you do not have required permissions.\n')
elif not os.access(os.path.dirname(ioc_top), os.W_OK):
initIOC_print('\nYou do not have permission to generate the IOC output directory.\n')
else:
valid = True
valid = False
while not valid:
binaries_top = input('\nEnter the absolute location of your compiled binaries (/ad-nfs/epics/production...).\nUse "/" characters for delimeters.\n> ')
if not os.path.exists(binaries_top):
initIOC_print('\nThe selected top binary directory does not exist, please try again.\n')
else:
ret = search_bundle_for_drivers(binaries_top)
if not ret:
initIOC_print('\nPlease enter a binary location that includes compiled drivers.\n')
else:
initIOC_print('')
valid = True
return ioc_top, binaries_top
def guided_init_iocs(manager):
"""Function that guides the user through generating a single IOC through the CLI
"""
initIOCs_config = {}
initIOCs_config['ioc_dir'] = manager.ioc_top
initIOCs_config['bundle_location'] = manager.binary_location
initIOCs_config['beamline_prefix'] = input('Enter the Beamline IOC Prefix (without the camera specific portion ex. XF:10IDC-BI).\n> ')
initIOCs_config['hostname'] = input('\nEnter the IOC server hostname.\n> ')
initIOCs_config['engineer'] = input('\nEnter your name and contact information.\n> ')
initIOCs_config['ca_address_ip'] = input('\nEnter the Channel Address subnet IP.\n> ')
initIOCs_config['iocs'] = []
another_ioc = True
while another_ioc:
current_ioc = {}
driver_type = None
while driver_type is None:
driver_type = input('\nWhat driver type would you like to generate?\n> ')
if driver_type not in supported_drivers and manager.use_template:
driver_type = None
initIOC_print('\nThe selected driver does not have a template. See list of supported drivers below.\n')
print_supported_drivers()
initIOC_print('You may alternatively try to generate from sources (without the -t flag).\n')
if driver_type is not None and not os.path.exists(os.path.join(manager.areaDetector_path, driver_type)):
initIOC_print('Could not find driver {} in {}.'.format(driver_type, os.path.join(manager.areaDetector_path, driver_type)))
driver_type = None
current_ioc['type'] = driver_type
# Ask for IOC name
valid = False
while not valid:
ioc_name = input('\nWhat should the IOC name be?\n> ')
if os.path.exists(initIOC_path_join(manager.ioc_top, ioc_name)):
initIOC_print('\nIOC with name {} already exists!\n'.format(ioc_name))
else:
valid = True
current_ioc['name'] = ioc_name
# Ask for camera specific information
current_ioc['device_prefix'] = input('\nPlease enter the device specific portion of the PV prefix (ex. {BlackFly-Cam:1})\n> ')
current_ioc['asyn_port'] = input('\nWhat asyn port should the IOC use? (ex. PS1).\n> ')
current_ioc['telnet_port'] = input('\nWhat telnet port should procServer use to run the IOC? (ex. 4000)\n> ')
current_ioc['connection'] = input('\nEnter the connection parameter for your device. (ex. IP, serial number etc.) Enter NA if not sure.\n> ')
# Generate a Data model IOCAction object, and initialize its environment.
ioc_action = IOCAction(current_ioc, initIOCs_config['beamline_prefix'])
ioc_action.epics_environment['HOSTNAME'] = initIOCs_config['hostname']
ioc_action.epics_environment['ENGINEER'] = initIOCs_config['engineer']
ioc_action.epics_environment['EPICS_CA_ADDR_LIST'] = initIOCs_config['ca_address_ip']
# Execute the action
manager.process_action(ioc_action)
initIOCs_config['iocs'].append(current_ioc)
try:
ioc_gen_config_path = os.path.join(manager.ioc_top, ioc_action.ioc_name, 'initIOCs.yml')
if os.path.exists(ioc_gen_config_path):
os.remove(ioc_gen_config_path)
global WITH_YAML
if WITH_YAML:
with open(ioc_gen_config_path, 'w') as config:
yaml.safe_dump(initIOCs_config, config)
except PermissionError:
initIOC_print('Could not save config, insufficient permissions.')
del initIOCs_config['iocs'][:]
another = input('Would you like to generate another IOC? (y/n).\n> ')
if another != 'y':
another_ioc = False
initIOC_print('Exiting...')
def init_iocs_cli(actions, manager):
"""Drives IOC generation from CONFIGURE file
Parameters
----------
actions : list of IOCAction
list of IOC actions to perform
manager : IOCActionManger
Manager object for executing IOC actions
"""
if len(actions) == 0:
initIOC_print('No IOCs detected in table.')
for action in actions:
if action.ioc_type not in supported_drivers and manager.use_template:
initIOC_print('ERROR - {} does not currently have a template!'.format(action.ioc_type))
print_supported_drivers()
initIOC_print('To request support for {} to be added to initIOC, please create an issue on:'.format(action.ioc_type))
initIOC_print('https://github.com/epicsNSLS2-deploy/initIOC/issues\n')
initIOC_print('Alternatively, you may try using the non-templated version. (Run without "-t" flag)')
else:
manager.process_action(action)
def initIOC_print(text):
"""A wrapper function for 'print' that allows for printing to CLI or to log
Parameters
----------
text : str
Text to print to console of log
"""
if USING_GUI and GUI_TOP_WINDOW is not None:
GUI_TOP_WINDOW.writeToLog(text + '\n')
else:
print(text)
def parse_args():
"""Function that parses the command line arguments
"""
parser = argparse.ArgumentParser(description='A script for auto-initializing areaDetector IOCs. Edit the CONFIGURE file and run without arguments for default operation.')
parser.add_argument('-c', '--configure', help='Add this flag and path to install script to use a run initIOCs given a configure file.')
parser.add_argument('-p', '--setlibrarypath', action='store_true', help='This flag should be added to set library path before startup script is run.')
parser.add_argument('-t', '--template', action='store_true', help='This flag will tell initIOC to use an st.cmd template. These are more likely to process without error, but may be somewhat out of date.')
parser.add_argument('-l', '--links', action='store_true', help='Add this flag if you would like initIOC to create copies of required helper files instead of links.')
parser.add_argument('-m', '--minimal', action='store_true', help='This flag specifies if initIOC should attempt to generate a minimal IOC. May result in some missing files that will need manual tweaks.')
parser.add_argument('-s', '--searchbundle', help='Add this flag, followed by a path to a binary bundle to get a list of driver executables that are included.')
arguments = vars(parser.parse_args())
return arguments
def search_bundle_for_drivers(bin_top):
initIOC_print('\nBundle selected: {}'.format(bin_top))
manager = IOCActionManager('.', bin_top, False, False, False, False)
initIOC_print('List of detected driver executables:\n+{}'.format('-' * 50))
if not os.path.exists(manager.areaDetector_path):
initIOC_print('ERROR - No binaries found in location {}\n'.format(bin_top))
return False
for dir in os.listdir(manager.areaDetector_path):
if os.path.isdir(os.path.join(manager.areaDetector_path, dir)):
_, bin_path, _ = manager.find_paths_for_action(dir)
if bin_path is not None:
initIOC_print('+ {:<16} - {}'.format(dir, bin_path))
return True
# Run the script
def main():
try:
arguments = parse_args()
if arguments['searchbundle'] is not None:
initIOC_print('\nSearching for driver executables...\n')
bin_top = arguments['searchbundle']
if not os.path.exists(bin_top):
initIOC_print('Selected bundle location does not exist.')
else:
_ = search_bundle_for_drivers(bin_top)
initIOC_print('')
exit()
if arguments['configure'] is not None:
try:
configuration = read_ioc_config(arguments['configure'])
actions = []
for ioc in configuration['iocs']:
actions.append(IOCAction(ioc, configuration['beamline_prefix']))
manager = IOCActionManager(configuration['ioc_dir'], configuration['bundle_location'], arguments['setlibrarypath'], arguments['template'], not arguments['minimal'], arguments['links'])
for action in actions:
# Add parameters to environment variables
action.epics_environment['ENGINEER'] = configuration['engineer']
action.epics_environment['HOSTNAME'] = configuration['hostname']
action.epics_environment['EPICS_CA_ADDR_LIST'] = configuration['ca_address_ip']
except KeyError:
initIOC_print('ERROR - Configure file could not be parsed successfully. Please ensure that it is valid!')
exit(-1)
print_start_message()
init_iocs_cli(actions, manager)
global WITH_YAML
if WITH_YAML:
for action in actions:
with open(os.path.join(manager.ioc_top, action.ioc_name, 'initIOCs.yml'), 'w') as config_file:
yaml.safe_dump(configuration, config_file)
else:
initIOC_print('Python yaml library not installed!')
else:
ioc_top, bin_top = prompt_for_top_dirs()
manager = IOCActionManager(ioc_top, bin_top, arguments['setlibrarypath'], arguments['template'], not arguments['minimal'], arguments['links'])
guided_init_iocs(manager)
except KeyboardInterrupt:
initIOC_print('\n\nExiting...')
exit()
if __name__ == '__main__':
main()