Merge "Description: Create RESTCONF based vLB CBA Blueprint"
[ccsdk/cds.git] / ms / py-executor / server.py
1 #!/usr/bin/python
2 #
3 #  Copyright (C) 2019 Bell Canada.
4 #  Modifications Copyright © 2018-2019 AT&T Intellectual Property.
5 #
6 #  Licensed under the Apache License, Version 2.0 (the "License");
7 #  you may not use this file except in compliance with the License.
8 #  You may obtain a copy of the License at
9 #
10 #      http://www.apache.org/licenses/LICENSE-2.0
11 #
12 #  Unless required by applicable law or agreed to in writing, software
13 #  distributed under the License is distributed on an "AS IS" BASIS,
14 #  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 #  See the License for the specific language governing permissions and
16 #  limitations under the License.
17
18 from builtins import KeyboardInterrupt
19 from concurrent import futures
20 import logging
21 import time
22 import grpc
23 from pathlib import Path, PurePath
24 from blueprints_grpc import BluePrintProcessing_pb2_grpc
25 from blueprints_grpc.request_header_validator_interceptor import RequestHeaderValidatorInterceptor
26 from blueprints_grpc.blueprint_processing_server import BluePrintProcessingServer
27 from blueprints_grpc import ScriptExecutorConfiguration
28
29 logger = logging.getLogger("Server")
30
31 _ONE_DAY_IN_SECONDS = 60 * 60 * 24
32
33
34 def serve(configuration: ScriptExecutorConfiguration):
35     port = configuration.script_executor_property('port')
36     authType = configuration.script_executor_property('authType')
37     maxWorkers = configuration.script_executor_property('maxWorkers')
38
39     if authType == 'tls-auth':
40         cert_chain_file = configuration.script_executor_property('certChain')
41         private_key_file = configuration.script_executor_property('privateKey')
42         logger.info("Setting GRPC server TLS authentication, cert file(%s) private key file(%s)", cert_chain_file,
43                     private_key_file)
44         # read in key and certificate
45         with open(cert_chain_file, 'rb') as f:
46             certificate_chain = f.read()
47         with open(private_key_file, 'rb') as f:
48             private_key = f.read()
49
50         # create server credentials
51         server_credentials = grpc.ssl_server_credentials(((private_key, certificate_chain),))
52
53         # create server
54         server = grpc.server(futures.ThreadPoolExecutor(max_workers=int(maxWorkers)))
55         BluePrintProcessing_pb2_grpc.add_BluePrintProcessingServiceServicer_to_server(
56             BluePrintProcessingServer(configuration), server)
57
58         # add secure port using credentials
59         server.add_secure_port('[::]:' + port, server_credentials)
60         server.start()
61     else:
62         logger.info("Setting GRPC server base authentication")
63         basic_auth = configuration.script_executor_property('token')
64         header_validator = RequestHeaderValidatorInterceptor(
65             'authorization', basic_auth, grpc.StatusCode.UNAUTHENTICATED,
66             'Access denied!')
67         # create server with token authentication interceptors
68         server = grpc.server(futures.ThreadPoolExecutor(max_workers=int(maxWorkers)),
69                              interceptors=(header_validator,))
70         BluePrintProcessing_pb2_grpc.add_BluePrintProcessingServiceServicer_to_server(
71             BluePrintProcessingServer(configuration), server)
72
73         server.add_insecure_port('[::]:' + port)
74         server.start()
75
76     logger.info("Command Executor Server started on %s" % port)
77
78     try:
79         while True:
80             time.sleep(_ONE_DAY_IN_SECONDS)
81     except KeyboardInterrupt:
82         server.stop(0)
83
84
85 if __name__ == '__main__':
86     config_file = str(PurePath(Path().absolute())) + '/configuration.ini'
87     configuration = ScriptExecutorConfiguration(config_file)
88     logging_formater = '%(asctime)s - %(name)s - %(threadName)s - %(levelname)s - %(message)s'
89     logging.basicConfig(filename=configuration.script_executor_property('logFile'),
90                         level=logging.DEBUG,
91                         format=logging_formater)
92     console = logging.StreamHandler()
93     console.setLevel(logging.INFO)
94     formatter = logging.Formatter(logging_formater)
95     console.setFormatter(formatter)
96     logging.getLogger('').addHandler(console)
97     serve(configuration)