1import os 2import shutil 3import subprocess 4 5from unit.applications.proto import TestApplicationProto 6from unit.option import option 7 8 9class TestApplicationGo(TestApplicationProto): 10 @staticmethod 11 def prepare_env(script, name='app', static=False): 12 try: 13 subprocess.check_output(['which', 'go']) 14 except subprocess.CalledProcessError: 15 return None 16 17 temp_dir = option.temp_dir + '/go/' 18 19 if not os.path.exists(temp_dir): 20 os.mkdir(temp_dir) 21 22 cache_dir = option.cache_dir + '/go-build' 23 24 if not os.path.exists(cache_dir): 25 os.mkdir(cache_dir) 26 27 env = os.environ.copy() 28 env['GOPATH'] = option.current_dir + '/build/go' 29 env['GOCACHE'] = cache_dir 30 31 shutil.copy2( 32 option.test_dir + '/go/' + script + '/' + name + '.go', temp_dir 33 ) 34 35 if static: 36 args = [ 37 'go', 38 'build', 39 '-tags', 40 'netgo', 41 '-ldflags', 42 '-extldflags "-static"', 43 '-o', 44 temp_dir + name, 45 temp_dir + name + '.go', 46 ] 47 else: 48 args = [ 49 'go', 50 'build', 51 '-o', 52 temp_dir + name, 53 temp_dir + name + '.go', 54 ] 55 56 replace_path = option.current_dir + '/build/go/src/unit.nginx.org/go' 57 58 with open(temp_dir + 'go.mod', 'w') as f: 59 f.write( 60 f"""module test/app 61require unit.nginx.org/go v0.0.0 62replace unit.nginx.org/go => {replace_path} 63""" 64 ) 65 66 if option.detailed: 67 print("\n$ GOPATH=" + env['GOPATH'] + " " + " ".join(args)) 68 69 try: 70 process = subprocess.run(args, env=env, cwd=temp_dir) 71 72 except KeyboardInterrupt: 73 raise 74 75 except subprocess.CalledProcessError: 76 return None 77 78 return process 79 80 def load(self, script, name='app', **kwargs): 81 static_build = False 82 83 wdir = option.test_dir + "/go/" + script 84 executable = option.temp_dir + "/go/" + name 85 86 if 'isolation' in kwargs and 'rootfs' in kwargs['isolation']: 87 wdir = "/go/" 88 executable = "/go/" + name 89 static_build = True 90 91 TestApplicationGo.prepare_env(script, name, static=static_build) 92 93 conf = { 94 "listeners": {"*:7080": {"pass": "applications/" + script}}, 95 "applications": { 96 script: { 97 "type": "external", 98 "processes": {"spare": 0}, 99 "working_directory": wdir, 100 "executable": executable, 101 }, 102 }, 103 } 104 105 self._load_conf(conf, **kwargs) 106