blob: 57ef9cd023805daf73ef41ba120b58e78be120b8 [file] [log] [blame]
Author Namea594e632018-08-10 11:33:58 -04001/*
2 Copyright 2017 the original author or authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15*/
16
17package main
18
19import (
20 "flag"
21 "fmt"
22 "log"
23 "net"
24 "net/http"
25 "os"
26 "strings"
27
28 "gerrit.opencord.org/abstract-olt/api"
29 "gerrit.opencord.org/abstract-olt/internal/pkg/settings"
30 "github.com/grpc-ecosystem/grpc-gateway/runtime"
31 "golang.org/x/net/context"
32 "google.golang.org/grpc"
33 "google.golang.org/grpc/credentials"
34 "google.golang.org/grpc/metadata"
35)
36
37// private type for Context keys
38type contextKey int
39
40const (
41 clientIDKey contextKey = iota
42)
43
44/*
45GetLogger - returns the logger
46*/
47func credMatcher(headerName string) (mdName string, ok bool) {
48 if headerName == "Login" || headerName == "Password" {
49 return headerName, true
50 }
51 return "", false
52}
53
54// authenticateAgent check the client credentials
55func authenticateClient(ctx context.Context, s *api.Server) (string, error) {
56 if md, ok := metadata.FromIncomingContext(ctx); ok {
57 clientLogin := strings.Join(md["login"], "")
58 clientPassword := strings.Join(md["password"], "")
59
60 if clientLogin != "john" {
61 return "", fmt.Errorf("unknown user %s", clientLogin)
62 }
63 if clientPassword != "doe" {
64 return "", fmt.Errorf("bad password %s", clientPassword)
65 }
66
67 log.Printf("authenticated client: %s", clientLogin)
68 return "42", nil
69 }
70 return "", fmt.Errorf("missing credentials")
71}
72
73// unaryInterceptor call authenticateClient with current context
74func unaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
75 s, ok := info.Server.(*api.Server)
76 if !ok {
77 return nil, fmt.Errorf("unable to cast server")
78 }
79 clientID, err := authenticateClient(ctx, s)
80 if err != nil {
81 return nil, err
82 }
83
84 ctx = context.WithValue(ctx, clientIDKey, clientID)
85 return handler(ctx, req)
86}
87
88func startGRPCServer(address, certFile, keyFile string) error {
89 // create a listener on TCP port
90 lis, err := net.Listen("tcp", address)
91 if err != nil {
92 return fmt.Errorf("failed to listen: %v", err)
93 }
94
95 // create a server instance
96 s := api.Server{}
97
98 // Create the TLS credentials
99 creds, err := credentials.NewServerTLSFromFile(certFile, keyFile)
100 if err != nil {
101 return fmt.Errorf("could not load TLS keys: %s", err)
102 }
103
104 // Create an array of gRPC options with the credentials
105 opts := []grpc.ServerOption{grpc.Creds(creds),
106 grpc.UnaryInterceptor(unaryInterceptor)}
107
108 // create a gRPC server object
109 grpcServer := grpc.NewServer(opts...)
110
111 // attach the Ping service to the server
donNewtonAlpha5234b132018-08-16 14:12:28 -0400112 api.RegisterAbstractOLTServer(grpcServer, &s)
Author Namea594e632018-08-10 11:33:58 -0400113
114 // start the server
115 log.Printf("starting HTTP/2 gRPC server on %s", address)
116 if err := grpcServer.Serve(lis); err != nil {
117 return fmt.Errorf("failed to serve: %s", err)
118 }
119
120 return nil
121}
122func startRESTServer(address, grpcAddress, certFile string) error {
123 ctx := context.Background()
124 ctx, cancel := context.WithCancel(ctx)
125 defer cancel()
126
127 mux := runtime.NewServeMux(runtime.WithIncomingHeaderMatcher(credMatcher))
128 creds, err := credentials.NewClientTLSFromFile(certFile, "")
129 if err != nil {
130 return fmt.Errorf("could not load TLS certificate: %s", err)
131 }
132
133 // Setup the client gRPC options
134 opts := []grpc.DialOption{grpc.WithTransportCredentials(creds)}
donNewtonAlpha5234b132018-08-16 14:12:28 -0400135 err = api.RegisterAbstractOLTHandlerFromEndpoint(ctx, mux, grpcAddress, opts)
Author Namea594e632018-08-10 11:33:58 -0400136 if err != nil {
137 return fmt.Errorf("could not register service Ping: %s", err)
138 }
139
140 log.Printf("starting HTTP/1.1 REST server on %s", address)
141 http.ListenAndServe(address, mux)
142
143 return nil
144}
145func main() {
146 debugPtr := flag.Bool("d", false, "Log Level Debug")
147 flag.Parse()
148 settings.SetDebug(*debugPtr)
149
150 file, err := os.OpenFile("AbstractOLT.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
151 if err != nil {
152 log.Fatalln("Failed to open log file", file, ":", err)
153 }
154 log.SetOutput(file)
155 log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Lshortfile)
156 log.Printf("Setting Debug to %t\n", settings.GetDebug())
157
158 grpcAddress := fmt.Sprintf("%s:%d", "AbstractOLT.dev.atl.foundry.att.com", 7777)
159 restAddress := fmt.Sprintf("%s:%d", "AbstractOLT.dev.atl.foundry.att.com", 7778)
160 certFile := "cert/server.crt"
161 keyFile := "cert/server.key"
162
163 // fire the gRPC server in a goroutine
164 go func() {
165 err := startGRPCServer(grpcAddress, certFile, keyFile)
166 if err != nil {
167 log.Fatalf("failed to start gRPC server: %s", err)
168 }
169 }()
170
171 // fire the REST server in a goroutine
172 go func() {
173 err := startRESTServer(restAddress, grpcAddress, certFile)
174 if err != nil {
175 log.Fatalf("failed to start gRPC server: %s", err)
176 }
177 }()
178
179 // infinite loop
180 log.Printf("Entering infinite loop")
181 select {}
182 fmt.Println("AbstractOLT")
183}