-
Notifications
You must be signed in to change notification settings - Fork 37
/
create_engine.go
235 lines (209 loc) · 8.87 KB
/
create_engine.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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package engine_functions
import (
"context"
"fmt"
"github.com/docker/go-connections/nat"
"github.com/kurtosis-tech/kurtosis/container-engine-lib/lib/backend_impls/docker/docker_kurtosis_backend/consts"
"github.com/kurtosis-tech/kurtosis/container-engine-lib/lib/backend_impls/docker/docker_kurtosis_backend/logs_aggregator_functions"
"github.com/kurtosis-tech/kurtosis/container-engine-lib/lib/backend_impls/docker/docker_kurtosis_backend/logs_aggregator_functions/implementations/vector"
"github.com/kurtosis-tech/kurtosis/container-engine-lib/lib/backend_impls/docker/docker_kurtosis_backend/shared_helpers"
"github.com/kurtosis-tech/kurtosis/container-engine-lib/lib/backend_impls/docker/docker_manager"
"github.com/kurtosis-tech/kurtosis/container-engine-lib/lib/backend_impls/docker/docker_manager/types"
"github.com/kurtosis-tech/kurtosis/container-engine-lib/lib/backend_impls/docker/object_attributes_provider"
"github.com/kurtosis-tech/kurtosis/container-engine-lib/lib/backend_interface/objects/engine"
"github.com/kurtosis-tech/kurtosis/container-engine-lib/lib/backend_interface/objects/port_spec"
"github.com/kurtosis-tech/kurtosis/container-engine-lib/lib/uuid_generator"
"github.com/kurtosis-tech/kurtosis/engine/launcher/args"
"github.com/kurtosis-tech/stacktrace"
"github.com/sirupsen/logrus"
"time"
)
const (
//TODO: pass this parameter
frontendPortSpec = 9711
maxWaitForEngineAvailabilityRetries = 10
timeBetweenWaitForEngineAvailabilityRetries = 1 * time.Second
logsStorageDirpath = "/var/log/kurtosis/"
)
func CreateEngine(
ctx context.Context,
imageOrgAndRepo string,
imageVersionTag string,
grpcPortNum uint16,
envVars map[string]string,
dockerManager *docker_manager.DockerManager,
objAttrsProvider object_attributes_provider.DockerObjectAttributesProvider,
) (
*engine.Engine,
error,
) {
serverArgs, err := args.GetArgsFromEnvVars(envVars)
if err != nil {
return nil, stacktrace.Propagate(err, "Couldn't retrieve engine server args from the env vars")
}
engineGuidStr, err := uuid_generator.GenerateUUIDString()
if err != nil {
return nil, stacktrace.Propagate(err, "An error occurred generating a UUID string for the engine")
}
engineGuid := engine.EngineGUID(engineGuidStr)
defaultWait, err := port_spec.CreateWaitWithDefaultValues()
if err != nil {
return nil, stacktrace.Propagate(err, "An error occurred creating a wait with default values")
}
privateGrpcPortSpec, err := port_spec.NewPortSpec(grpcPortNum, consts.EngineTransportProtocol, consts.HttpApplicationProtocol, defaultWait)
if err != nil {
return nil, stacktrace.Propagate(
err,
"An error occurred creating the engine's private grpc port spec object using number '%v' and protocol '%v'",
grpcPortNum,
consts.EngineTransportProtocol.String(),
)
}
engineNetwork, err := shared_helpers.GetEngineAndLogsComponentsNetwork(ctx, dockerManager)
if err != nil {
return nil, stacktrace.Propagate(err, "An error occurred getting the engine network")
}
targetNetworkId := engineNetwork.GetId()
logrus.Infof("Starting the centralized logs components...")
logsStorageAttrs, err := objAttrsProvider.ForLogsStorageVolume()
if err != nil {
return nil, stacktrace.Propagate(err, "An error occurred retrieving logs storage object attributes.")
}
logsStorageVolNameStr := logsStorageAttrs.GetName().GetString()
volumeLabelStrs := map[string]string{}
for labelKey, labelValue := range logsStorageAttrs.GetLabels() {
volumeLabelStrs[labelKey.GetString()] = labelValue.GetString()
}
// Creation of volume should be idempotent because the volume with persisted logs in it could already exist
// Thus, we don't defer an undo volume if this operation fails
if err = dockerManager.CreateVolume(ctx, logsStorageVolNameStr, volumeLabelStrs); err != nil {
return nil, stacktrace.Propagate(err, "An error occurred creating logs storage.")
}
logsAggregatorContainer := vector.NewVectorLogsAggregatorContainer() // Declaring implementation
_, removeLogsAggregatorFunc, err := logs_aggregator_functions.CreateLogsAggregator(
ctx,
logsAggregatorContainer,
dockerManager,
objAttrsProvider)
if err != nil {
return nil, stacktrace.Propagate(err,
"An error occurred attempting to create logging components for engine with GUID '%v' in Docker network with network id '%v'.", engineGuidStr, targetNetworkId)
}
shouldRemoveCentralizedLogComponents := true
defer func() {
if shouldRemoveCentralizedLogComponents {
removeLogsAggregatorFunc()
}
}()
logrus.Infof("Centralized logs components started.")
httpPortSpec, err := port_spec.NewPortSpec(uint16(frontendPortSpec), consts.EngineTransportProtocol, consts.HttpApplicationProtocol, defaultWait)
if err != nil {
return nil, stacktrace.Propagate(
err,
"An error occurred creating the engine's http port spec object using number '%v' and protocol '%v'",
frontendPortSpec,
consts.EngineTransportProtocol.String(),
)
}
engineAttrs, err := objAttrsProvider.ForEngineServer(
engineGuid,
consts.KurtosisInternalContainerGrpcPortId,
privateGrpcPortSpec,
)
if err != nil {
return nil, stacktrace.Propagate(
err,
"An error occurred getting the engine server container attributes using GUID '%v' and GRPC port num '%v'",
engineGuid,
grpcPortNum,
)
}
privateGrpcDockerPort, err := shared_helpers.TransformPortSpecToDockerPort(privateGrpcPortSpec)
if err != nil {
return nil, stacktrace.Propagate(err, "An error occurred transforming the private grpc port spec to a Docker port")
}
httpDockerPort, err := shared_helpers.TransformPortSpecToDockerPort(httpPortSpec)
if err != nil {
return nil, stacktrace.Propagate(err, "An error occurred transforming the private http port spec to a Docker port")
}
usedPorts := map[nat.Port]docker_manager.PortPublishSpec{
privateGrpcDockerPort: docker_manager.NewManualPublishingSpec(grpcPortNum),
httpDockerPort: docker_manager.NewManualPublishingSpec(uint16(frontendPortSpec)),
}
bindMounts := map[string]string{
// Necessary so that the engine server can interact with the Docker engine
consts.DockerSocketFilepath: consts.DockerSocketFilepath,
}
volumeMounts := map[string]string{
logsStorageVolNameStr: logsStorageDirpath,
}
if serverArgs.OnBastionHost {
// Mount the host engine config directory so the engine can access files like the remote backend config.
bindMounts[consts.HostEngineConfigDirToMount] = consts.EngineConfigLocalDir
}
containerImageAndTag := fmt.Sprintf(
"%v:%v",
imageOrgAndRepo,
imageVersionTag,
)
labelStrs := map[string]string{}
for labelKey, labelValue := range engineAttrs.GetLabels() {
labelStrs[labelKey.GetString()] = labelValue.GetString()
}
createAndStartArgs := docker_manager.NewCreateAndStartContainerArgsBuilder(
containerImageAndTag,
engineAttrs.GetName().GetString(),
targetNetworkId,
).WithEnvironmentVariables(
envVars,
).WithBindMounts(
bindMounts,
).WithVolumeMounts(
volumeMounts,
).WithUsedPorts(
usedPorts,
).WithLabels(
labelStrs,
).Build()
// Best-effort pull attempt
if err = dockerManager.FetchImage(ctx, containerImageAndTag); err != nil {
logrus.Warnf("Failed to pull the latest version of engine server image '%v'; you may be running an out-of-date version", containerImageAndTag)
}
containerId, hostMachinePortBindings, err := dockerManager.CreateAndStartContainer(ctx, createAndStartArgs)
if err != nil {
return nil, stacktrace.Propagate(err, "An error occurred starting the Kurtosis engine container")
}
shouldKillEngineContainer := true
defer func() {
if shouldKillEngineContainer {
// NOTE: We use the background context here so that the kill will still go off even if the reason for
// the failure was the original context being cancelled
if err := dockerManager.KillContainer(context.Background(), containerId); err != nil {
logrus.Errorf(
"Launching the engine server with GUID '%v' and container ID '%v' didn't complete successfully so we "+
"tried to kill the container we started, but doing so exited with an error:\n%v",
engineGuid,
containerId,
err)
logrus.Errorf("ACTION REQUIRED: You'll need to manually stop engine server with GUID '%v'!!!!!!", engineGuid)
}
}
}()
if err := shared_helpers.WaitForPortAvailabilityUsingNetstat(
ctx,
dockerManager,
containerId,
privateGrpcPortSpec,
maxWaitForEngineAvailabilityRetries,
timeBetweenWaitForEngineAvailabilityRetries,
); err != nil {
return nil, stacktrace.Propagate(err, "An error occurred waiting for the engine server's grpc port to become available")
}
result, err := getEngineObjectFromContainerInfo(containerId, labelStrs, types.ContainerStatus_Running, hostMachinePortBindings)
if err != nil {
return nil, stacktrace.Propagate(err, "An error occurred creating an engine object from container with GUID '%v'", containerId)
}
shouldRemoveCentralizedLogComponents = false
shouldKillEngineContainer = false
return result, nil
}