/
main.go
166 lines (146 loc) · 5.27 KB
/
main.go
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
// Copyright 2022 Google LLC
//
// 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
//
// https://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.
// Package exists for running host orchestrator(HO) server.
package main
import (
"flag"
"fmt"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/user"
"path/filepath"
"sync"
"time"
"github.com/google/android-cuttlefish/frontend/src/host_orchestrator/orchestrator"
"github.com/google/android-cuttlefish/frontend/src/host_orchestrator/orchestrator/debug"
"github.com/gorilla/mux"
"github.com/google/uuid"
)
const (
defaultTLSCertDir = "/etc/cuttlefish-common/host_orchestrator/cert"
defaultAndroidBuildURL = "https://androidbuildinternal.googleapis.com"
DefaultListenAddress = "127.0.0.1"
)
func defaultCVDArtifactsDir() string {
u, err := user.Current()
if err != nil {
log.Fatalf("Unable to get current user uid: %v", err)
}
return fmt.Sprintf("/tmp/cvd/%s/artifacts", u.Uid)
}
func startHttpServer(addr string, port int) error {
log.Printf("Host Orchestrator is listening at http://%s:%d", addr, port)
// handler is nil, so DefaultServeMux is used.
return http.ListenAndServe(fmt.Sprintf("%s:%d", addr, port), nil)
}
func startHttpsServer(addr string, port int, certPath string, keyPath string) error {
log.Printf("Host Orchestrator is listening at https://%s:%d", addr, port)
return http.ListenAndServeTLS(fmt.Sprintf("%s:%d", addr, port),
certPath,
keyPath,
// handler is nil, so DefaultServeMux is used.
//
// Using DefaultServerMux in both servers (http and https) is not a problem
// as http.ServeMux instances are thread safe.
nil)
}
func fromEnvOrDefault(key string, def string) string {
if val, ok := os.LookupEnv(key); ok {
return val
}
return def
}
func start(starters []func() error) {
wg := new(sync.WaitGroup)
wg.Add(len(starters))
for _, starter := range starters {
go func(f func() error) {
defer wg.Done()
if err := f(); err != nil {
log.Fatal(err)
}
}(starter)
}
wg.Wait()
}
func newOperatorProxy(port int) *httputil.ReverseProxy {
if port <= 0 {
log.Fatal("The host orchestrator requires access to the operator")
}
operatorURL, err := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", port))
if err != nil {
log.Fatalf("Invalid operator port (%d): %v", port, err)
}
return httputil.NewSingleHostReverseProxy(operatorURL)
}
func main() {
httpPort := flag.Int("http_port", 2080, "Port to listen on for HTTP requests.")
httpsPort := flag.Int("https_port", -1, "Port to listen on for HTTPS requests.")
tlsCertDir := flag.String("tls_cert_dir", defaultTLSCertDir, "Directory with the TLS certificate.")
cvdUser := flag.String("cvd_user", "", "User to execute cvd as.")
cvdCreationTimeoutSecs := flag.Int("cvd_creation_timeout_secs", 420, "CVD creation timeout in seconds")
operatorPort := flag.Int("operator_http_port", 1080, "Port where the operator is listening.")
abURL := flag.String("android_build_url", defaultAndroidBuildURL, "URL to an Android Build API.")
imRootDir := flag.String("cvd_artifacts_dir", defaultCVDArtifactsDir(), "Directory where cvd will download android build artifacts to.")
address := flag.String("listen_addr", DefaultListenAddress, "IP address to listen for requests.")
flag.Parse()
certPath := filepath.Join(*tlsCertDir, "cert.pem")
keyPath := filepath.Join(*tlsCertDir, "key.pem")
if err := os.MkdirAll(*imRootDir, 0774); err != nil {
log.Fatalf("Unable to create artifacts directory: %v", err)
}
imPaths := orchestrator.IMPaths{
RootDir: *imRootDir,
ArtifactsRootDir: filepath.Join(*imRootDir, "artifacts"),
}
om := orchestrator.NewMapOM()
uamOpts := orchestrator.UserArtifactsManagerOpts{
RootDir: filepath.Join(*imRootDir, "user_artifacts"),
NameFactory: func() string { return uuid.New().String() },
}
uam := orchestrator.NewUserArtifactsManagerImpl(uamOpts)
debugStaticVars := debug.StaticVariables{}
debugVarsManager := debug.NewVariablesManager(debugStaticVars)
imController := orchestrator.Controller{
Config: orchestrator.Config{
Paths: imPaths,
AndroidBuildServiceURL: *abURL,
CVDCreationTimeout: time.Duration(*cvdCreationTimeoutSecs) * time.Second,
CVDUser: *cvdUser,
},
OperationManager: om,
WaitOperationDuration: 2 * time.Minute,
UserArtifactsManager: uam,
DebugVariablesManager: debugVarsManager,
}
proxy := newOperatorProxy(*operatorPort)
r := mux.NewRouter()
imController.AddRoutes(r)
// Defer to the operator for every route not covered by the orchestrator. That
// includes web UI and other static files.
r.PathPrefix("/").Handler(proxy)
http.Handle("/", r)
starters := []func() error{
func() error { return startHttpServer(*address, *httpPort) },
}
if *httpsPort > 0 {
starters = append(starters, func() error {
return startHttpsServer(*address, *httpsPort, certPath, keyPath)
})
}
start(starters)
}