-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathwindows.go
More file actions
399 lines (377 loc) · 12.3 KB
/
Copy pathwindows.go
File metadata and controls
399 lines (377 loc) · 12.3 KB
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
package windows
import (
_ "embed"
"fmt"
"github.com/go-playground/validator/v10"
"github.com/pulumi/pulumi-aws/sdk/v7/go/aws/ec2"
"github.com/pulumi/pulumi/sdk/v3/go/auto"
"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
"github.com/redhat-developer/mapt/pkg/manager"
mc "github.com/redhat-developer/mapt/pkg/manager/context"
infra "github.com/redhat-developer/mapt/pkg/provider"
cr "github.com/redhat-developer/mapt/pkg/provider/api/compute-request"
spotTypes "github.com/redhat-developer/mapt/pkg/provider/api/spot"
"github.com/redhat-developer/mapt/pkg/provider/aws"
awsConstants "github.com/redhat-developer/mapt/pkg/provider/aws/constants"
"github.com/redhat-developer/mapt/pkg/provider/aws/data"
"github.com/redhat-developer/mapt/pkg/provider/aws/modules/allocation"
amiCopy "github.com/redhat-developer/mapt/pkg/provider/aws/modules/ami"
"github.com/redhat-developer/mapt/pkg/provider/aws/modules/bastion"
"github.com/redhat-developer/mapt/pkg/provider/aws/modules/ec2/compute"
"github.com/redhat-developer/mapt/pkg/provider/aws/modules/network"
"github.com/redhat-developer/mapt/pkg/provider/aws/modules/serverless"
"github.com/redhat-developer/mapt/pkg/provider/aws/modules/spot"
amiSVC "github.com/redhat-developer/mapt/pkg/provider/aws/services/ec2/ami"
"github.com/redhat-developer/mapt/pkg/provider/aws/services/ec2/keypair"
securityGroup "github.com/redhat-developer/mapt/pkg/provider/aws/services/ec2/security-group"
"github.com/redhat-developer/mapt/pkg/provider/util/command"
"github.com/redhat-developer/mapt/pkg/provider/util/output"
"github.com/redhat-developer/mapt/pkg/provider/util/security"
cloudConfigWindowsServer "github.com/redhat-developer/mapt/pkg/target/host/windows-server"
"github.com/redhat-developer/mapt/pkg/util"
"github.com/redhat-developer/mapt/pkg/util/logging"
resourcesUtil "github.com/redhat-developer/mapt/pkg/util/resources"
)
// add proxy https://github.com/ptcodes/proxy-server-with-terraform/blob/master/main.tf
type WindowsServerArgs struct {
Prefix string
// AMI info. Optional. User and Owner only applied
// if AMIName is set
AMIName string
AMIUser string
AMIOwner string
AMILang string
AMIKeepCopy bool
// Machine params
ComputeRequest *cr.ComputeRequestArgs
Spot *spotTypes.SpotArgs
Airgap bool
ServiceEndpoints []string
VpcID *string
// If timeout is set a severless scheduled task will be created to self destroy the resources
Timeout string
}
type windowsServerRequest struct {
mCtx *mc.Context
prefix *string
amiName *string
amiUser *string
amiOwner *string
amiLang *string
amiKeepCopy *bool
spot bool
timeout *string
serviceEndpoints []string
vpcID *string
allocationData *allocation.AllocationResult
airgap *bool
diskSize *int
// internal management
// For airgap scenario there is an orchestation of
// a phase with connectivity on the machine (allowing bootstraping)
// a pahase with connectivyt off where the subnet for the target lost the nat gateway
airgapPhaseConnectivity network.Connectivity
}
func (r *windowsServerRequest) validate() error {
v := validator.New(validator.WithRequiredStructEnabled())
err := v.Var(r.mCtx, "required")
if err != nil {
return err
}
return v.Struct(r)
}
// Create orchestrate 3 stacks:
// If spot is enable it will run best spot option to get the best option to spin the machine
// Then it will run the stack for windows dedicated host
func Create(mCtxArgs *mc.ContextArgs, args *WindowsServerArgs) (err error) {
// Create mapt Context
mCtx, err := mc.Init(mCtxArgs, aws.Provider())
if err != nil {
return err
}
if len(args.AMIName) == 0 {
args.AMIName = amiNameDefault
args.AMIUser = amiUserDefault
args.AMIOwner = amiOwnerDefault
}
if len(args.AMILang) > 0 && args.AMILang == amiLangNonEng {
args.AMIName = amiNonEngNameDefault
}
// Compose request
if args.VpcID != nil && args.Airgap {
return fmt.Errorf("--vpc-id and --airgap are mutually exclusive")
}
prefix := util.If(len(args.Prefix) > 0, args.Prefix, "main")
r := windowsServerRequest{
mCtx: mCtx,
prefix: &prefix,
amiName: &args.AMIName,
amiUser: &args.AMIUser,
amiOwner: &args.AMIOwner,
amiKeepCopy: &args.AMIKeepCopy,
amiLang: &args.AMILang,
timeout: &args.Timeout,
serviceEndpoints: args.ServiceEndpoints,
vpcID: args.VpcID,
airgap: &args.Airgap,
}
if args.ComputeRequest != nil {
r.diskSize = args.ComputeRequest.DiskSize
}
if args.Spot != nil {
r.spot = args.Spot.Spot
}
r.allocationData, err = allocation.Allocation(mCtx,
&allocation.AllocationArgs{
Prefix: &args.Prefix,
ComputeRequest: args.ComputeRequest,
AMIProductDescription: &amiProduct,
Spot: args.Spot,
VpcID: args.VpcID,
})
if err != nil {
return err
}
isAMIOffered, _, err := data.IsAMIOffered(
mCtx.Context(),
data.ImageRequest{
Name: r.amiName,
Region: r.allocationData.Region})
if err != nil {
return err
}
// If it is not offered need to create a copy on the target region
if !isAMIOffered {
acr := amiCopy.CopyAMIRequest{
MCtx: mCtx,
Prefix: *r.prefix,
ID: awsWindowsDedicatedID,
AMISourceName: r.amiName,
AMISourceArch: nil,
AMITargetRegion: r.allocationData.Region,
AMIKeepCopy: *r.amiKeepCopy,
FastLaunch: amiFastLaunch,
MaxParallel: int32(amiFastLaunchMaxParallel),
}
if err := acr.Create(); err != nil {
return err
}
}
// if not only host the mac machine will be created
if !*r.airgap {
return r.createMachine()
}
// Airgap scneario requires orchestration
return r.createAirgapMachine()
}
// Will destroy resources related to machine
func Destroy(mCtxArgs *mc.ContextArgs) (err error) {
logging.Debug("Run windows destroy")
// Create mapt Context
mCtx, err := mc.Init(mCtxArgs, aws.Provider())
if err != nil {
return err
}
if err := aws.DestroyStack(
mCtx,
aws.DestroyStackRequest{
Stackname: stackName,
}); err != nil {
return err
}
if amiCopy.Exist(mCtx) {
err = amiCopy.Destroy(mCtx)
if err != nil {
return
}
}
if spot.Exist(mCtx) {
if err := spot.Destroy(mCtx); err != nil {
return err
}
}
// Cleanup S3 state after all stacks have been destroyed
return aws.CleanupState(mCtx)
}
func (r *windowsServerRequest) createMachine() error {
cs := manager.Stack{
StackName: r.mCtx.StackNameByProject(stackName),
ProjectName: r.mCtx.ProjectName(),
BackedURL: r.mCtx.BackedURL(),
ProviderCredentials: aws.GetClouProviderCredentials(
map[string]string{
awsConstants.CONFIG_AWS_REGION: *r.allocationData.Region}),
DeployFunc: r.deploy,
}
sr, err := manager.UpStack(r.mCtx, cs)
if err != nil {
return err
}
return manageResults(r.mCtx, sr, r.prefix, r.airgap)
}
// Abstract this with a stackAirgapHandle receives a fn (connectivty on / off) err executes
// first on then off
func (r *windowsServerRequest) createAirgapMachine() error {
r.airgapPhaseConnectivity = network.ON
err := r.createMachine()
if err != nil {
return nil
}
r.airgapPhaseConnectivity = network.OFF
return r.createMachine()
}
// function wil all the logic to deploy resources required by windows
// * create AMI Copy if needed
// * networking
// * key
// * security group
// * compute
// * checks
func (r *windowsServerRequest) deploy(ctx *pulumi.Context) error {
if err := r.validate(); err != nil {
return err
}
// Get AMI ref
// ami, err := amiSVC.GetAMIByName(ctx, r.AMIName, r.AMIOwner, nil)
ami, err := amiSVC.GetAMIByName(ctx,
fmt.Sprintf("%s*", *r.amiName),
[]string{*r.amiOwner}, nil)
if err != nil {
return err
}
// Networking
nw, err := network.Create(ctx, r.mCtx,
&network.NetworkArgs{
Prefix: *r.prefix,
ID: awsWindowsDedicatedID,
Region: *r.allocationData.Region,
AZ: *r.allocationData.AZ,
CreateLoadBalancer: r.spot,
Airgap: *r.airgap,
AirgapPhaseConnectivity: r.airgapPhaseConnectivity,
ServiceEndpoints: r.serviceEndpoints,
VpcID: r.vpcID,
})
if err != nil {
return err
}
// Create Keypair
kpr := keypair.KeyPairRequest{
Name: resourcesUtil.GetResourceName(
*r.prefix, awsWindowsDedicatedID, "pk")}
keyResources, err := kpr.Create(ctx, r.mCtx)
if err != nil {
return err
}
ctx.Export(fmt.Sprintf("%s-%s", *r.prefix, outputUserPrivateKey),
keyResources.PrivateKey.PrivateKeyPem)
// Security groups
securityGroups, err := securityGroups(ctx, r.mCtx, r.prefix, nw.Vpc)
if err != nil {
return err
}
// Compute
password, err := security.CreatePassword(ctx,
resourcesUtil.GetResourceName(
*r.prefix, awsWindowsDedicatedID, "password"))
if err != nil {
return err
}
// Generate userdata
userDataB64, err := cloudConfigWindowsServer.GenerateUserdata(ctx, &amiUserDefault, password, keyResources, r.mCtx.RunID())
if err != nil {
return err
}
effectiveDiskSize := diskSize
if r.diskSize != nil {
effectiveDiskSize = *r.diskSize
}
cr := compute.ComputeRequest{
MCtx: r.mCtx,
Prefix: *r.prefix,
ID: awsWindowsDedicatedID,
VPC: nw.Vpc,
Subnet: nw.Subnet,
AMI: ami,
UserDataAsBase64: userDataB64,
KeyResources: keyResources,
SecurityGroups: securityGroups,
InstaceTypes: requiredInstanceTypes,
DiskSize: &effectiveDiskSize,
Airgap: *r.airgap,
LB: nw.LoadBalancer,
Eip: nw.Eip,
LBTargetGroups: []int{22, 3389}}
if r.allocationData.SpotPrice != nil {
cr.Spot = true
cr.SpotPrice = *r.allocationData.SpotPrice
}
c, err := cr.NewCompute(ctx)
if err != nil {
return err
}
ctx.Export(fmt.Sprintf("%s-%s", *r.prefix, outputUsername),
pulumi.String(*r.amiUser))
ctx.Export(fmt.Sprintf("%s-%s", *r.prefix, outputUserPassword),
password.Result)
ctx.Export(fmt.Sprintf("%s-%s", *r.prefix, outputHost),
c.GetHostDnsName(!*r.airgap))
if len(*r.timeout) > 0 {
if err = serverless.OneTimeDelayedTask(ctx, r.mCtx,
*r.allocationData.Region, *r.prefix,
awsWindowsDedicatedID,
fmt.Sprintf("aws %s destroy --project-name %s --backed-url %s --serverless",
"windows",
r.mCtx.ProjectName(),
r.mCtx.BackedURL()),
*r.timeout); err != nil {
return err
}
}
return c.Readiness(ctx, command.CommandPing, *r.prefix, awsWindowsDedicatedID,
keyResources.PrivateKey, *r.amiUser, nw.Bastion, c.Dependencies)
}
// Write exported values in context to files o a selected target folder
func manageResults(mCtx *mc.Context, stackResult auto.UpResult, prefix *string, airgap *bool) error {
results := map[string]string{
fmt.Sprintf("%s-%s", *prefix, outputUsername): "username",
fmt.Sprintf("%s-%s", *prefix, outputUserPassword): "userpassword",
fmt.Sprintf("%s-%s", *prefix, outputUserPrivateKey): "id_rsa",
fmt.Sprintf("%s-%s", *prefix, outputHost): "host",
}
if *airgap {
err := bastion.WriteOutputs(stackResult, *prefix, mCtx.GetResultsOutputPath())
if err != nil {
return err
}
}
return output.Write(stackResult, mCtx.GetResultsOutputPath(), results)
}
// security group for mac machine with ingress rules for ssh and vnc
func securityGroups(ctx *pulumi.Context, mCtx *mc.Context, prefix *string,
vpc *ec2.Vpc) (pulumi.StringArray, error) {
// ingress for ssh access from 0.0.0.0
sshIngressRule := securityGroup.SSH_TCP
sshIngressRule.CidrBlocks = infra.NETWORKING_CIDR_ANY_IPV4
rdpIngressRule := securityGroup.RDP_TCP
rdpIngressRule.CidrBlocks = infra.NETWORKING_CIDR_ANY_IPV4
// Create SG with ingress rules
sg, err := securityGroup.SGRequest{
Name: resourcesUtil.GetResourceName(*prefix, awsWindowsDedicatedID, "sg"),
VPC: vpc,
Description: fmt.Sprintf("sg for %s", awsWindowsDedicatedID),
IngressRules: []securityGroup.IngressRules{
sshIngressRule, rdpIngressRule},
}.Create(ctx, mCtx)
if err != nil {
return nil, err
}
// Convert to an array of IDs
sgs := util.ArrayConvert([]*ec2.SecurityGroup{sg.SG},
func(sg *ec2.SecurityGroup) pulumi.StringInput {
return sg.ID()
})
return pulumi.StringArray(sgs[:]), nil
}
// Need to add custom listener for RDP or should we use 22 tunneling through the bastion?
// func addCustomListeners(){}