aboutsummaryrefslogtreecommitdiffstats
path: root/installation/sdnc-web/src/main/scripts/core.py
blob: 6bdd4b590e6beee8994ac963d4c5c688d9b3b59b (plain)
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
###
# ============LICENSE_START=======================================================
# ONAP : ccsdk distribution web
# ================================================================================
# Copyright (C) 2020 highstreet technologies GmbH Intellectual Property.
# All rights reserved.
# ================================================================================
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============LICENSE_END=========================================================
###
import subprocess
import os
import json
import zipfile
import re
import uuid
import urllib3
import shutil
import re
import ssl
urllib3.disable_warnings()

APPLICATION_LISTFILE="/app/odlux.application.list"
INIT_FOLDER="/app/init.d"
ODLUX_BASE_FOLDER='/app/odlux'
INDEX_HTML=ODLUX_BASE_FOLDER+'/index.html'
INDEX_HTML_TEMPLATE=INDEX_HTML+'.template'
DEFAULT_APPLICATIONS=["connectApp" "faultApp" "maintenanceApp" "configurationApp" "performanceHistoryApp" "inventoryApp" "eventLogApp" "mediatorApp" "helpApp"]
http = urllib3.PoolManager(cert_reqs=ssl.CERT_NONE)
    
def exec(command):
    output = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE).stdout.read()
    return output
def execToStdOut(commandArray):
    process = subprocess.Popen(commandArray, shell=False)
    process.communicate()

def download(url, dst):
    print("downloading from {}...".format(url),end="")
    with open(dst, 'wb') as out_file:
        resp= http.request('GET',url, preload_content=False)
        shutil.copyfileobj(resp, out_file)
        resp.release_conn() 
    print("done")

def getEnv(key, defaultValue=None):
    x=os.getenv(key)
    return x if x is not None and len(x)>0 else defaultValue

def sedInFile(old, nu, fn):
    execToStdOut(['sed', '-i', 's|{}|{}|g'.format(old,nu),fn])

def add_application(name, index, file=None):
    apps = load_applications()
    if index==0:
        print("no index given. put it to last position")
        index=apps[len(apps)-1]['index']+10
    apps.append(dict(index=index,name=name))
    if file is not None and os.path.exists(file):
        extract(file)
    else:
        print('unable to find file {}'.format(file))
    write_applications(apps)
    print("{} installed on index {}".format(name, index)) 

def initial_load():
    files = os.listdir(INIT_FOLDER)
    regex = r"([0-9]+)([a-zA-Z]+)\.(jar|zip)"
    regexUrl = r"([0-9]+)([a-zA-Z]+)\.(url)"
    for file in files:
        matches = re.finditer(regex,file)
        match = next(matches, None)
        matchesUrl = re.finditer(regexUrl,file)
        matchUrl = next(matchesUrl, None)
        if match is not None:
            print("installing {}".format(file))
            index = int(match.group(1))
            name = match.group(2)
            add_application(name,index,INIT_FOLDER+'/'+file)
        elif matchUrl is not None:
            print("installing {}".format(file))
            index = int(match.group(1))
            name = match.group(2)
            add_application(name,index,INIT_FOLDER+'/'+file)
        else:
            print("no index naming format found. try to autodetect")
            infos = autoDetectInfosFromJar(file)
            if infos is None:
                print("unable to detect index and application name for {}".format(file))
            else:
               add_application(infos['name'],infos['index'],INIT_FOLDER+'/'+file) 



def containsBlueprintExpression(file) -> bool:
    print("check if file {} is blueprint".format(file))
    with open(file, 'r') as fp:
        lines = fp.readlines()
        for line in lines:
            if "<blueprint" in line:
                return True
        fp.close()
    return False

def findBlueprintXml(dir):
    result = [os.path.join(dp, f) for dp, dn, filenames in os.walk(dir) for f in filenames if os.path.splitext(f)[1] == '.xml']
    for file in result:
        if containsBlueprintExpression(file):
            return file
    return None

def autoDetectInfosFromJar(file):
    print("autodetect infos(appName and index) from jar {}".format(file))
    tmpDir=getRandomTempDir()
    regexBundleName = r"<property[\ ]+name=\"bundleName\"[\ ]+value=\"([^\"]+)\""
    regexIndex = r"<property[\ ]+name=\"index\"[\ ]+value=\"([^\"]+)\""
    name=None
    index=0
    with zipfile.ZipFile(file, 'r') as zip_ref:
        zip_ref.extractall(tmpDir)
        blueprint = findBlueprintXml(tmpDir)
        if blueprint is None:
            return None
        with open(blueprint) as fp:
            lines = fp.readlines()
            for line in lines:
                if name is None:
                    matches = re.finditer(regexBundleName, line)
                    match = next(matches,None)
                    if match is not None:
                        name = match.group(1)
                if index == 0:
                    matches = re.finditer(regexIndex, line)
                    match = next(matches,None)
                    if match is not None:
                        index = int(match.group(1))
       
            fp.close()
    print("found infos from jar: name={} index={}".format(name,index))
    return dict(index=index,name=name)
        
def getRandomTempDir(create=False):
    while(True):
        dir='/tmp/{}'.format(uuid.uuid4())
        if not os.path.exists(dir):
#            print("found random not-existing dir {}".format(dir))
            if create:
                os.makedirs(dir)
            return dir
#        print("dir {} already exists. try new".format(dir))
    return None

def getRandomTempFile():
    dir = getRandomTempDir(True)
    if dir is None:
        return None

    while True:
        file='{}/{}.dat'.format(dir,uuid.uuid4())
        if not os.path.exists(file):
#            print("found random not-existing file {}".format(file))
            return file
#        print("file {} already exists. try new".format(file))
    return None

def extract(fn):

    tmpDir=getRandomTempDir()  
    with zipfile.ZipFile(fn, 'r') as zip_ref:
        zip_ref.extractall(tmpDir)
        exec(" ".join(['cp','-r',tmpDir+'/odlux/*',ODLUX_BASE_FOLDER+'/']))
        zip_ref.close()


def load_applications():
    apps=[]
    if os.path.exists(APPLICATION_LISTFILE):
        with open(APPLICATION_LISTFILE,'r') as fp:
            lines= fp.readlines()
            for line in lines:
                if len(line.rstrip())<=0:
                    continue
                try:
                    hlp=line.split(' ')
                    apps.append(dict(index=int(hlp[0]),name=hlp[1].rstrip()))
                except:
                    print('problem reading line {}'.format(line))
            fp.close()
    else:
        index=10
        for app in DEFAULT_APPLICATIONS:
            apps.append(dict(index=index,name=app))
            index+=10
#    print('applications loaded={}'.format(apps))
    return sorted(apps, key=lambda d: d['index']) 
  
def write_applications(apps):
#    print('saving applications={}'.format(apps))
    apps = sorted(apps, key=lambda d: d['index'])
    os.remove(APPLICATION_LISTFILE)
    with open(APPLICATION_LISTFILE,'w') as fp:
        for app in apps:
            fp.write('{} {}\n'.format(app['index'], app['name']))
        fp.close()

def update_index_html(apps=None):
 
#     # Backup the index.html file
    if not os.path.exists(INDEX_HTML_TEMPLATE):
        execToStdOut(['cp',INDEX_HTML,INDEX_HTML_TEMPLATE])
    else:
        execToStdOut(['cp',INDEX_HTML_TEMPLATE,INDEX_HTML])
#     #default values
    if apps is None:
        apps=load_applications()
    ODLUX_AUTH_METHOD="basic"
    ENABLE_ODLUX_RBAC=getEnv('ENABLE_ODLUX_RBAC','false')
    TRPCEGUIURL=getEnv('TRPCEGUIURL')

    if getEnv('ENABLE_OAUTH') == "true":
        ODLUX_AUTH_METHOD="oauth"
    ODLUX_CONFIG=dict(authentication=ODLUX_AUTH_METHOD,enablePolicy=ENABLE_ODLUX_RBAC == 'true')
    print("authentication is {}".format(ODLUX_AUTH_METHOD))
    print("rbac access is enabled: {}".format(ENABLE_ODLUX_RBAC))
   
    if TRPCEGUIURL is not None:
        ODLUX_CONFIG['transportpceUrl']=TRPCEGUIURL
        print("trpce gui url is: {}".format(TRPCEGUIURL))

#    sed -z 's/<script>[^<]*<\/script>/<script>\n    \/\/ run the application \n  require\(\[\"connectApp\",\"faultApp\",\"maintenanceApp\",\"configurationApp\",\"performanceHistoryApp\",\"inventoryApp\",\"eventLogApp\",\"mediatorApp\",\"networkMapApp\",\"linkCalculationApp\",\"helpApp\",\"run\"\], function \(connectApp,faultApp,maintenanceApp,configurationApp,performanceHistoryApp,inventoryApp,eventLogApp,mediatorApp,networkMapApp,linkCalculationApp,helpApp,run\) \{ \n run.configure('$ODLUX_CONFIG'); \n    connectApp.register\(\); \n  faultApp.register\(\);\n    maintenanceApp.register\(\); \n     configurationApp.register\(\);\n    performanceHistoryApp.register\(\); \n    inventoryApp.register\(\);\n    eventLogApp.register\(\);\n   mediatorApp.register\(\);\n   networkMapApp.register\(\);\n   linkCalculationApp.register\(\);\n     helpApp.register\(\);\n      run.runApplication();\n    \}\);\n  <\/script>/' -i /opt/bitnami/nginx/html/odlux/index.html 
    requireArg=""
    fnArgs=""
    appCalls=""
    for app in apps:
        requireArg+='"{}",'.format(app['name'])
        fnArgs+='{},'.format(app['name'])
        appCalls+='{}.register();\\n'.format(app['name'])
    #replace require expression
    execToStdOut(['sed', '-z', 's/require(\["run"\],\ function\ (run)/require\(\[{}\"run\"\], function \({}run\)/'.format(requireArg,fnArgs), '-i', INDEX_HTML]) 
    #replace run.runApplication expression
    execToStdOut(['sed','-z', 's/run.runApplication();/{}run.runApplication();/'.format(appCalls), '-i',INDEX_HTML])
    #replace run.configure expression if exists
    execToStdOut(['sed', '-z', 's|run.configureApplication([^)]\+)|run.configureApplication({});|'.format(json.dumps(ODLUX_CONFIG)), '-i', INDEX_HTML]) 
  

def check_for_rule_template():
    if os.path.exists('/opt/bitnami/nginx/conf/server_blocks/location.rules.tmpl'):
        print("using template for forwarding rules")
        execToStdOut(['cp','/opt/bitnami/nginx/conf/server_blocks/location.rules.tmpl','/opt/bitnami/nginx/conf/server_blocks/location.rules'])

def update_nginx_site_conf():
    FN=None
    if getEnv('WEBPROTOCOL') == "HTTPS":
        FN='/opt/bitnami/nginx/conf/server_blocks/https_site.conf'
        execToStdOut(['rm', '/opt/bitnami/nginx/conf/server_blocks/http_site.conf'])
        SSL_CERT_DIR=getEnv('SSL_CERT_DIR')
        SSL_CERTIFICATE=getEnv('SSL_CERTIFICATE')
        SSL_CERTIFICATE_KEY=getEnv('SSL_CERTIFICATE_KEY')
        sedInFile('SSL_CERTIFICATE_KEY',SSL_CERTIFICATE_KEY,FN)
        sedInFile('SSL_CERT_DIR',SSL_CERT_DIR,FN)
        sedInFile('SSL_CERTIFICATE',SSL_CERTIFICATE, FN)
        
    elif getEnv('WEBPROTOCOL') == "HTTP":
        FN='/opt/bitnami/nginx/conf/server_blocks/http_site.conf'
        execToStdOut(['rm', '/opt/bitnami/nginx/conf/server_blocks/https_site.conf'])

    WEBPROTOCOL=getEnv('WEBPROTOCOL')
    WEBPORT=getEnv('WEBPORT')
    SDNRPROTOCOL=getEnv('SDNRPROTOCOL')
    SDNCWEBHOST=getEnv('HOSTNAME')
    SDNRHOST=getEnv('SDNRHOST')
    if SDNRHOST == "sdnc.onap":
        # Request is from K8s
        SDNCWEBHOSTINDEX=SDNCWEBHOST[SDNCWEBHOST.rindex("-")+1:]
        SDNRHOST = "sdnc-" + SDNCWEBHOSTINDEX + ".onap" 
    SDNRPORT=getEnv('SDNRPORT')
    SDNRWEBSOCKETPORT=getEnv('SDNRWEBSOCKETPORT',SDNRPORT)
    DNS_RESOLVER=getEnv('DNS_RESOLVER')
    DNS_INTERNAL_RESOLVER=getEnv('DNS_INTERNAL_RESOLVER')
    if FN is None:
        print("unknown env WEBPROTOCOL: {}".format(WEBPROTOCOL))
        exit(1)
    
    # replace needed base parameters
    sedInFile('WEBPORT',WEBPORT,FN)

    FN='/opt/bitnami/nginx/conf/server_blocks/location.rules'
    # replace needed parameters in forwarding rules
    sedInFile('WEBPORT',WEBPORT,FN)
    sedInFile('SDNRPROTOCOL',SDNRPROTOCOL,FN)
    sedInFile('SDNRHOST',SDNRHOST ,FN)
    sedInFile('SDNRPORT',SDNRPORT,FN)
    sedInFile('SDNRWEBSOCKETPORT',SDNRWEBSOCKETPORT, FN)
    sedInFile('DNS_RESOLVER',DNS_RESOLVER ,FN)
    sedInFile('DNS_INTERNAL_RESOLVER',DNS_INTERNAL_RESOLVER ,FN)

    TRPCEURL=getEnv('TRPCEURL')
    TOPOURL=getEnv('TOPOURL')
    SITEDOCURL=getEnv('SITEDOCURL')
    TILEURL=getEnv('TILEURL')
    DATAPROVIDERURL=getEnv('DATAPROVIDERURL')
    TERRAINURL=getEnv('TERRAINURL')
    # handle optional parameters
    if TRPCEURL is None:
        print("transportPCE forwarding disabled")
        sedInFile('proxy_pass TRPCEURL/$1;','return 404;',FN)
    else:
        sedInFile('TRPCEURL',TRPCEURL ,FN)

    if TOPOURL is None:
        print("topology api forwarding disabled")
        sedInFile('proxy_pass TOPOURL;','return 404;',FN)
    else:
        sedInFile('TOPOURL',TOPOURL ,FN)
    
    if SITEDOCURL is None:
        print("sitedoc api forwarding disabled")
        sedInFile('proxy_pass SITEDOCURL/topology/stadok/$1;','return 404;', FN)
    else:
        sedInFile('SITEDOCURL',SITEDOCURL, FN)
    
    if TILEURL is None:
        print("tile server forwarding disabled")
        sedInFile('proxy_pass TILEURL/$1;','return 404;',FN)
    else:
        sedInFile('TILEURL',TILEURL ,FN)
    
    if DATAPROVIDERURL is None:
        print("data provider forwarding disabled")
        sedInFile('proxy_pass DATAPROVIDERURL/$1;','return 404;',FN)
    else:
        sedInFile('DATAPROVIDERURL',DATAPROVIDERURL ,FN)
    
    if TERRAINURL is None:
        print("terrain server forwarding disabled")
        sedInFile('proxy_pass TERRAINURL/$1;','return 404;',FN)
    else:
        sedInFile('TERRAINURL',TERRAINURL ,FN)