summaryrefslogtreecommitdiffstats
path: root/samples/services/nginx/docker/grpc/nginx_grpc_server.py
blob: 1dfe708af77fff5420af7a1f8c6e3e4653d3cfac (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
# Copyright (c) Authors of Clover
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0


from concurrent import futures
import time
import sys
import grpc
import subprocess
import pickle
import logging
import nginx_pb2
import nginx_pb2_grpc

from jinja2 import Template

_ONE_DAY_IN_SECONDS = 60 * 60 * 24
GRPC_PORT = '[::]:50054'


class Controller(nginx_pb2_grpc.ControllerServicer):

    def __init__(self, service_type):
        logging.basicConfig(filename='nginx.log', level=logging.DEBUG)
        self.service_type = service_type
        self.out_file = '/etc/nginx/nginx.conf'
        # self.out_file = 'testfile'
        if service_type == "proxy":
            # self.template_file = 'templates/proxy.template'
            self.template_file = '/grpc/templates/proxy.template'
            self.ModifyProxy(nginx_pb2.ConfigProxy(
                server_port='9180', server_name='proxy-access-control',
                location_path='/', proxy_path='http://http-lb:9180',
                mirror_path='http://snort-ids:80'), "")
        if service_type == "server":
            # self.template_file = 'templates/server.template'
            self.template_file = '/grpc/templates/server.template'
            self.ModifyServer(nginx_pb2.ConfigServer(
                server_port='9180', server_name='clover-server',
                site_root='/var/www/html',
                site_index='index.nginx-debian.html'), "")
        if service_type == "lb":
            # self.template_file = 'templates/lb.template'
            self.template_file = '/grpc/templates/lb.template'
            slb_list = pickle.dumps(
                    ['clover-server1:9180', 'clover-server2:9180',
                        'clover-server3:9180'])
            self.ModifyLB(nginx_pb2.ConfigLB(
                server_port='9180', server_name='http-lb',
                slb_list=slb_list,
                slb_group='cloverlb', lb_path='/'), "")

    def ModifyProxy(self, r, context):
        try:
            with open(self.template_file) as f:
                tmpl = Template(f.read())
            output = tmpl.render(
                server_port=r.server_port,
                server_name=r.server_name,
                location_path=r.location_path,
                proxy_path=r.proxy_path,
                mirror_path=r.mirror_path
            )
            with open(self.out_file, "wb") as fh:
                fh.write(output)
            msg = "Modified nginx config"
            self.RestartNginx()
        except Exception as e:
            logging.debug(e)
            msg = "Failed to modify nginx config"
        return nginx_pb2.NginxReply(message=msg)

    def ModifyServer(self, r, context):
        try:
            with open(self.template_file) as f:
                tmpl = Template(f.read())
            output = tmpl.render(
                server_port=r.server_port,
                server_name=r.server_name,
                site_root=r.site_root,
                site_index=r.site_index
            )
            with open(self.out_file, "wb") as fh:
                fh.write(output)
            msg = "Modified nginx config"
            self.RestartNginx()
        except Exception as e:
            logging.debug(e)
            msg = "Failed to modify nginx config"
        return nginx_pb2.NginxReply(message=msg)

    def ModifyLB(self, r, context):
        try:
            with open(self.template_file) as f:
                tmpl = Template(f.read())
            output = tmpl.render(
                server_port=r.server_port,
                server_name=r.server_name,
                slb_list=pickle.loads(r.slb_list),
                slb_group=r.slb_group,
                lb_path=r.lb_path
            )
            with open(self.out_file, "wb") as fh:
                fh.write(output)
            msg = "Modified nginx config"
            self.RestartNginx()
        except Exception as e:
            logging.debug(e)
            msg = "Failed to modify nginx config"
        return nginx_pb2.NginxReply(message=msg)

    def RestartNginx(self):
        subprocess.Popen(
                  ["service nginx restart"], shell=True)

    def ProcessAlerts(self, request, context):
        try:
            msg = "Processed alert"
        except Exception as e:
            logging.debug(e)
            msg = "Failed to process alert"
        return nginx_pb2.NginxReply(message=msg)


def serve(service_type):
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    nginx_pb2_grpc.add_ControllerServicer_to_server(
                    Controller(service_type), server)
    server.add_insecure_port(GRPC_PORT)
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)


if __name__ == '__main__':
    serve(sys.argv[1])