Merge "solving showing icon and filter by tags"
[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 import logging
19 import os
20 import time
21 from builtins import KeyboardInterrupt
22 from concurrent import futures
23 from pathlib import Path, PurePath
24
25 import grpc
26 from manager.servicer import ArtifactManagerServicer
27 from proto.BlueprintManagement_pb2_grpc import add_BlueprintManagementServiceServicer_to_server
28
29 from blueprints_grpc import BlueprintProcessing_pb2_grpc, ScriptExecutorConfiguration
30 from blueprints_grpc.blueprint_processing_server import BlueprintProcessingServer
31 from blueprints_grpc.request_header_validator_interceptor import RequestHeaderValidatorInterceptor
32
33 logger = logging.getLogger("Server")
34
35 _ONE_DAY_IN_SECONDS = 60 * 60 * 24
36
37
38 def serve(configuration: ScriptExecutorConfiguration):
39     port = configuration.script_executor_property('port')
40     authType = configuration.script_executor_property('authType')
41     maxWorkers = configuration.script_executor_property('maxWorkers')
42
43     if authType == 'tls-auth':
44         cert_chain_file = configuration.script_executor_property('certChain')
45         private_key_file = configuration.script_executor_property('privateKey')
46         logger.info("Setting GRPC server TLS authentication, cert file(%s) private key file(%s)", cert_chain_file,
47                     private_key_file)
48         # read in key and certificate
49         with open(cert_chain_file, 'rb') as f:
50             certificate_chain = f.read()
51         with open(private_key_file, 'rb') as f:
52             private_key = f.read()
53
54         # create server credentials
55         server_credentials = grpc.ssl_server_credentials(((private_key, certificate_chain),))
56
57         # create server
58         server = grpc.server(futures.ThreadPoolExecutor(max_workers=int(maxWorkers)))
59         BlueprintProcessing_pb2_grpc.add_BlueprintProcessingServiceServicer_to_server(
60             BlueprintProcessingServer(configuration), server
61         )
62         add_BlueprintManagementServiceServicer_to_server(ArtifactManagerServicer(), server)
63
64         # add secure port using credentials
65         server.add_secure_port('[::]:' + port, server_credentials)
66         server.start()
67     else:
68         logger.info("Setting GRPC server base authentication")
69         basic_auth = configuration.script_executor_property('token')
70         header_validator = RequestHeaderValidatorInterceptor(
71             'authorization', basic_auth, grpc.StatusCode.UNAUTHENTICATED,
72             'Access denied!')
73         # create server with token authentication interceptors
74         server = grpc.server(futures.ThreadPoolExecutor(max_workers=int(maxWorkers)),
75                              interceptors=(header_validator,))
76         BlueprintProcessing_pb2_grpc.add_BlueprintProcessingServiceServicer_to_server(
77             BlueprintProcessingServer(configuration), server
78         )
79         add_BlueprintManagementServiceServicer_to_server(ArtifactManagerServicer(), server)
80
81         server.add_insecure_port('[::]:' + port)
82         server.start()
83
84     logger.info("Command Executor Server started on %s" % port)
85
86     try:
87         while True:
88             time.sleep(_ONE_DAY_IN_SECONDS)
89     except KeyboardInterrupt:
90         server.stop(0)
91
92
93 if __name__ == '__main__':
94     default_configuration_file = str(PurePath(Path().absolute(), "../../configuration.ini"))
95     supplied_configuration_file = os.environ.get("CONFIGURATION")
96     config_file = str(os.path.expanduser(Path(supplied_configuration_file or default_configuration_file)))
97
98     configuration = ScriptExecutorConfiguration(config_file)
99     logging_formater = '%(asctime)s - %(name)s - %(threadName)s - %(levelname)s - %(message)s'
100     logging.basicConfig(filename=configuration.script_executor_property('logFile'),
101                         level=logging.DEBUG,
102                         format=logging_formater)
103     console = logging.StreamHandler()
104     console.setLevel(logging.INFO)
105     formatter = logging.Formatter(logging_formater)
106     console.setFormatter(formatter)
107     logging.getLogger('').addHandler(console)
108     serve(configuration)