forked from lnxbil/docker-machine-driver-proxmox-ve
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxmoxdriver.go
752 lines (652 loc) · 18.9 KB
/
proxmoxdriver.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
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
package dockermachinedriverproxmoxve
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
"os"
"path"
"regexp"
"strings"
"time"
"golang.org/x/crypto/ssh"
resty "gopkg.in/resty.v1"
sshrw "github.com/mosolovsa/go_cat_sshfilerw"
"github.com/docker/machine/libmachine/drivers"
"github.com/docker/machine/libmachine/mcnflag"
"github.com/docker/machine/libmachine/state"
"github.com/labstack/gommon/log"
)
//Define driver name
var dName string = "proxmoxve"
// Driver for Proxmox VE
type Driver struct {
*drivers.BaseDriver
driver *ProxmoxVE
// Basic Authentication for Proxmox VE
Host string // Host to connect to
Node string // optional, node to create VM on, host used if omitted but must match internal node name
User string // username
Password string // password
Realm string // realm, e.g. pam, pve, etc.
// File to load as boot image RancherOS/Boot2Docker
ImageFile string // in the format <storagename>:iso/<filename>.iso
Pool string // pool to add the VM to (necessary for users with only pool permission)
Storage string // internal PVE storage name
StorageType string // Type of the storage (currently QCOW2 and RAW)
DiskSize string // disk size in GB
Memory int // memory in GB
StorageFilename string
NetBridge string // bridge applied to network interface
NetVlanTag int // vlan tag
VMID string // VM ID only filled by create()
GuestUsername string // user to log into the guest OS to copy the public key
GuestPassword string // password to log into the guest OS to copy the public key
GuestSSHPort int // ssh port to log into the guest OS to copy the public key
Cores string
CPU string
SCSIArgs string
SCSIControl string
NUMA string
OnBoot string // boot vm on starting service
driverDebug bool // driver debugging
restyDebug bool // enable resty debugging
UUID string
}
func (d *Driver) debugf(format string, v ...interface{}) {
if d.driverDebug {
log.Infof(format, v...)
}
}
func (d *Driver) debug(v ...interface{}) {
if d.driverDebug {
log.Info(v...)
}
}
func getUUIDFromSmbios1(str string) string {
var re = regexp.MustCompile(`(?m)uuid=([\d\w-]{1,})[,]{0,1}.*$`)
return re.FindStringSubmatch(fmt.Sprintf("%s", str))[1]
}
func (d *Driver) checkVmidEquality() (bool, error) {
output, err := d.driver.NodesNodeQemuVMIDConfigGet(d.Node, d.VMID)
if err != nil {
return false, err
}
proxmoxVMUUID := getUUIDFromSmbios1(fmt.Sprintf("%s", output["smbios1"]))
if proxmoxVMUUID != "" && d.UUID != "" && proxmoxVMUUID == d.UUID {
return true, nil
}
return false, nil
}
func (d *Driver) connectAPI() error {
if d.driver == nil {
d.debugf("Create called")
d.debugf("Connecting to %s as %s@%s with password '%s'", d.Host, d.User, d.Realm, d.Password)
c, err := GetProxmoxVEConnectionByValues(d.User, d.Password, d.Realm, d.Host)
d.driver = c
if err != nil {
return fmt.Errorf("Could not connect to host '%s' with '%s@%s'", d.Host, d.User, d.Realm)
}
if d.restyDebug {
c.EnableDebugging()
}
d.debugf("Connected to PVE version '" + d.driver.Version + "'")
}
return nil
}
// GetCreateFlags returns the argument flags for the program
func (d *Driver) GetCreateFlags() []mcnflag.Flag {
driverName := d.DriverName()
upperDriverName := strings.ToUpper(driverName)
return []mcnflag.Flag{
mcnflag.StringFlag{
EnvVar: upperDriverName + "_PROXMOX_HOST",
Name: driverName + "-proxmox-host",
Usage: "Host to connect to",
Value: "192.168.1.253",
},
mcnflag.StringFlag{
EnvVar: upperDriverName + "_PROXMOX_NODE",
Name: driverName + "-proxmox-node",
Usage: "to to use (defaults to host)",
Value: "",
},
mcnflag.StringFlag{
EnvVar: upperDriverName + "_PROXMOX_USER_NAME",
Name: driverName + "-proxmox-user-name",
Usage: "User to connect as",
Value: "root",
},
mcnflag.StringFlag{
EnvVar: upperDriverName + "_PROXMOX_USER_PASSWORD",
Name: driverName + "-proxmox-user-password",
Usage: "Password to connect with",
Value: "",
},
mcnflag.StringFlag{
EnvVar: upperDriverName + "_PROXMOX_REALM",
Name: driverName + "-proxmox-realm",
Usage: "Realm to connect to (default: pam)",
Value: "pam",
},
mcnflag.StringFlag{
EnvVar: upperDriverName + "_PROXMOX_POOL",
Name: driverName + "-proxmox-pool",
Usage: "pool to attach to",
Value: "",
},
mcnflag.StringFlag{
EnvVar: upperDriverName + "_VM_STORAGE_PATH",
Name: driverName + "-vm-storage-path",
Usage: "storage to create the VM volume on",
Value: "local",
},
mcnflag.StringFlag{
EnvVar: upperDriverName + "_VM_STORAGE_SIZE",
Name: driverName + "-vm-storage-size",
Usage: "disk size in GB",
Value: "16",
},
mcnflag.StringFlag{
EnvVar: upperDriverName + "_VM_STORAGE_TYPE",
Name: driverName + "-vm-storage-type",
Usage: "storage type to use (QCOW2 or RAW)",
Value: "raw",
},
mcnflag.IntFlag{
EnvVar: upperDriverName + "_VM_MEMORY",
Name: driverName + "-vm-memory",
Usage: "memory in GB",
Value: 8,
},
mcnflag.StringFlag{
EnvVar: upperDriverName + "_VM_SCSI_ARGS",
Name: driverName + "-vm-scsi-args",
Usage: "additional scsi settings",
},
mcnflag.StringFlag{
EnvVar: upperDriverName + "_VM_SCSI_CONTROLLER",
Name: driverName + "-vm-scsi-controller",
Usage: "set scsi controller model",
Value: "lsi",
},
mcnflag.StringFlag{
EnvVar: upperDriverName + "_VM_CPU",
Name: driverName + "-vm-cpu-cores",
Usage: "number of cpu cores",
Value: "2",
},
mcnflag.StringFlag{
EnvVar: upperDriverName + "_VM_CPU_ARGS",
Name: driverName + "-vm-cpu-args",
Usage: "additional cpu settings",
Value: "",
},
mcnflag.StringFlag{
EnvVar: upperDriverName + "_VM_IMAGE_FILE",
Name: driverName + "-vm-image-file",
Usage: "storage of the image file (e.g. local:iso/rancheros-proxmoxve-autoformat.iso)",
Value: "",
},
mcnflag.StringFlag{
EnvVar: upperDriverName + "_VM_NET_BRIDGE",
Name: driverName + "-vm-net-bridge",
Usage: "bridge to attach network to",
Value: "vmbr0",
},
mcnflag.IntFlag{
EnvVar: upperDriverName + "_VM_NET_TAG",
Name: driverName + "-vm-net-tag",
Usage: "vlan tag",
Value: 0,
},
mcnflag.StringFlag{
EnvVar: upperDriverName + "_ONBOOT",
Name: driverName + "-vm-onboot",
Usage: "enable/disable vm boot on proxmox start",
Value: "0",
},
mcnflag.StringFlag{
EnvVar: upperDriverName + "_NUMA",
Name: driverName + "-vm-numa",
Usage: "enable/disable NUMA",
Value: "0",
},
mcnflag.StringFlag{
EnvVar: upperDriverName + "_SSH_USERNAME",
Name: driverName + "-ssh-username",
Usage: "Username to log in to the guest OS (default docker for rancheros)",
Value: "docker",
},
mcnflag.StringFlag{
EnvVar: upperDriverName + "_SSH_PASSWORD",
Name: driverName + "-ssh-password",
Usage: "Password to log in to the guest OS (default tcuser for rancheros)",
Value: "tcuser",
},
mcnflag.IntFlag{
EnvVar: upperDriverName + "_SSH_PORT",
Name: driverName + "-ssh-port",
Usage: "SSH port in the guest to log in to (defaults to 22)",
Value: 22,
},
mcnflag.BoolFlag{
EnvVar: upperDriverName + "_DEBUG_RESTY",
Name: driverName + "-debug-resty",
Usage: "enables the resty debugging",
},
mcnflag.BoolFlag{
EnvVar: upperDriverName + "_DEBUG_DRIVER",
Name: driverName + "-debug-driver",
Usage: "enables debugging in the driver",
},
}
}
func (d *Driver) ping() bool {
if d.driver == nil {
return false
}
command := NodesNodeQemuVMIDAgentPostParameter{Command: "ping"}
err := d.driver.NodesNodeQemuVMIDAgentPost(d.Node, d.VMID, &command)
if err != nil {
d.debug(err)
return false
}
return true
}
// DriverName returns the name of the driver
func (d *Driver) DriverName() string {
return dName
}
// SetConfigFromFlags configures all command line arguments
func (d *Driver) SetConfigFromFlags(flags drivers.DriverOptions) error {
d.debug("SetConfigFromFlags called")
driverName := d.DriverName()
// PROXMOX API Connection settings
d.Host = flags.String(driverName + "-proxmox-host")
d.Node = flags.String(driverName + "-proxmox-node")
if len(d.Node) == 0 {
d.Node = d.Host
}
d.User = flags.String(driverName + "-proxmox-user-name")
d.Password = flags.String(driverName + "-proxmox-user-password")
d.Realm = flags.String(driverName + "-proxmox-realm")
d.Pool = flags.String(driverName + "-proxmox-pool")
/* VM configuration */
d.OnBoot = flags.String(driverName + "-vm-onboot")
// Disk configuration
d.DiskSize = flags.String(driverName + "-vm-storage-size")
d.Storage = flags.String(driverName + "-vm-storage-path")
d.StorageType = strings.ToLower(flags.String(driverName + "-vm-storage-type"))
d.ImageFile = flags.String(driverName + "-vm-image-file")
// SCSI configuration
d.SCSIControl = flags.String(driverName + "-vm-scsi-controller")
d.SCSIArgs = flags.String(driverName + "-vm-scsi-args")
// Memory configuration
d.Memory = flags.Int(driverName + "-vm-memory")
d.Memory *= 1024
d.NUMA = flags.String(driverName + "-vm-numa")
// Processor configuration
d.Cores = flags.String(driverName + "-vm-cpu-cores")
d.CPU = flags.String(driverName + "-vm-cpu-args")
// Network configuration
d.NetBridge = flags.String(driverName + "-vm-net-bridge")
d.NetVlanTag = flags.Int(driverName + "-vm-net-tag")
//SSH connection settings
d.GuestSSHPort = flags.Int(driverName + "-ssh-port")
d.GuestUsername = flags.String(driverName + "-ssh-username")
d.GuestPassword = flags.String(driverName + "-ssh-password")
//SWARM Settings
d.SwarmMaster = flags.Bool("swarm-master")
d.SwarmHost = flags.String("swarm-host")
//Debug option
d.driverDebug = flags.Bool(driverName + "-debug-driver")
d.restyDebug = flags.Bool(driverName + "-debug-resty")
if d.restyDebug {
d.debug("enabling Resty debugging")
resty.SetLogger(log.Output())
resty.SetDebug(true)
}
return nil
}
// GetURL returns the URL for the target docker daemon
func (d *Driver) GetURL() (string, error) {
ip, err := d.GetIP()
if err != nil {
return "", err
}
if ip == "" {
return "", nil
}
return fmt.Sprintf("tcp://%s:2376", ip), nil
}
// GetMachineName returns the machine name
func (d *Driver) GetMachineName() string {
return d.MachineName
}
// GetNetBridge returns the bridge
func (d *Driver) GetNetBridge() string {
return d.NetBridge
}
// GetNetVlanTag returns the vlan tag
func (d *Driver) GetNetVlanTag() int {
return d.NetVlanTag
}
// GetIP returns the ip
func (d *Driver) GetIP() (string, error) {
d.connectAPI()
return d.driver.GetEth0IPv4(d.Node, d.VMID)
}
// GetSSHHostname returns the ssh host returned by the API
func (d *Driver) GetSSHHostname() (string, error) {
return d.GetIP()
}
// GetSSHPort returns the ssh port, 22 if not specified
func (d *Driver) GetSSHPort() (int, error) {
return d.GuestSSHPort, nil
}
// GetSSHUsername returns the ssh user name, root if not specified
func (d *Driver) GetSSHUsername() string {
return d.GuestUsername
}
// GetState returns the state of the VM
func (d *Driver) GetState() (state.State, error) {
err := d.connectAPI()
if err != nil {
return state.Paused, err
}
if d.ping() {
return state.Running, nil
}
return state.Paused, nil
}
// PreCreateCheck is called to enforce pre-creation steps
func (d *Driver) PreCreateCheck() error {
switch d.StorageType {
case "raw":
fallthrough
case "qcow2":
break
default:
return fmt.Errorf("storage type '%s' is not supported", d.StorageType)
}
err := d.connectAPI()
if err != nil {
return err
}
d.debug("Retrieving next ID")
id, err := d.driver.ClusterNextIDGet(0)
if err != nil {
return err
}
d.debugf("Next ID was '%s'", id)
d.VMID = id
storageType, err := d.driver.GetStorageType(d.Node, d.Storage)
if err != nil {
return err
}
filename := "vm-" + d.VMID + "-disk-1"
switch storageType {
case "lvmthin":
fallthrough
case "zfs":
fallthrough
case "ceph":
if d.StorageType != "raw" {
return fmt.Errorf("type '%s' on storage '%s' does only support raw", storageType, d.Storage)
}
case "nfs":
fallthrough
case "dir":
filename += "." + d.StorageType
}
d.StorageFilename = filename
// create and save a new SSH key pair
keyfile := d.GetSSHKeyPath()
keypath := path.Dir(keyfile)
d.debugf("Generating new key pair at path '%s'", keypath)
err = os.MkdirAll(keypath, 0755)
if err != nil {
return err
}
_, _, err = GetKeyPair(keyfile)
return err
}
// Create creates a new VM with storage
func (d *Driver) Create() error {
volume := NodesNodeStorageStorageContentPostParameter{
Filename: d.StorageFilename,
Size: d.DiskSize + "G",
VMID: d.VMID,
}
d.debugf("Creating disk volume '%s' with size '%s'", volume.Filename, volume.Size)
diskname, err := d.driver.NodesNodeStorageStorageContentPost(d.Node, d.Storage, &volume)
if err != nil {
return err
}
if !strings.HasSuffix(diskname, d.StorageFilename) {
return fmt.Errorf("returned diskname is not correct: should be '%s' but was '%s'", d.StorageFilename, diskname)
}
net0 := fmt.Sprintf("virtio,bridge=%s", d.NetBridge)
npp := NodesNodeQemuPostParameter{
VMID: d.VMID,
Agent: "1",
Autostart: "1",
Memory: d.Memory,
Cores: d.Cores,
Net0: net0,
SCSI0: d.StorageFilename,
SCSIHw: d.SCSIControl,
Ostype: "l26",
Name: d.BaseDriver.MachineName,
KVM: "1", // if you test in a nested environment, you may have to change this to 0 if you do not have nested virtualization
Cdrom: d.ImageFile,
Pool: d.Pool,
CPU: d.CPU,
OnBoot: d.OnBoot,
NUMA: d.NUMA,
}
if d.NetVlanTag != 0 {
npp.Net0 += fmt.Sprintf(",tag=%d", d.NetVlanTag)
}
if d.StorageType == "qcow2" {
npp.SCSI0 = d.Storage + ":" + d.VMID + "/" + volume.Filename
} else if d.StorageType == "raw" {
if strings.HasSuffix(volume.Filename, ".raw") {
// raw files (having .raw) should have the VMID in the path
npp.SCSI0 = d.Storage + ":" + d.VMID + "/" + volume.Filename
} else {
npp.SCSI0 = d.Storage + ":" + volume.Filename
}
}
if d.SCSIArgs != "" {
npp.SCSI0 += "," + d.SCSIArgs
}
d.debugf("Creating VM '%s' with '%d' of memory", npp.VMID, npp.Memory)
taskid, err := d.driver.NodesNodeQemuPost(d.Node, &npp)
if err != nil {
return err
}
err = d.driver.WaitForTaskToComplete(d.Node, taskid)
if err != nil {
return err
}
output, err := d.driver.NodesNodeQemuVMIDConfigGet(d.Node, d.VMID)
if err != nil {
return err
}
d.UUID = getUUIDFromSmbios1(fmt.Sprintf("%s", output["smbios1"]))
err = d.Start()
if err != nil {
return err
}
return d.waitAndPrepareSSH()
}
func (d *Driver) waitAndPrepareSSH() error {
d.debugf("waiting for VM to become active, first wait 10 seconds")
time.Sleep(10 * time.Second)
for !d.ping() {
d.debugf("waiting for VM to become active")
time.Sleep(2 * time.Second)
}
d.debugf("VM is active waiting more")
time.Sleep(2 * time.Second)
sshConfig := &ssh.ClientConfig{
User: d.GetSSHUsername(),
Auth: []ssh.AuthMethod{
ssh.Password(d.GuestPassword)},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
sshbasedir := "/home/" + d.GetSSHUsername() + "/.ssh"
hostname, _ := d.GetSSHHostname()
port, _ := d.GetSSHPort()
clientstr := fmt.Sprintf("%s:%d", hostname, port)
d.debugf("Creating directory '%s'", sshbasedir)
conn, err := ssh.Dial("tcp", clientstr, sshConfig)
if err != nil {
return err
}
session, err := conn.NewSession()
if err != nil {
return err
}
ip, err := d.GetIP()
if err != nil {
return err
}
d.IPAddress = ip
d.debugf("driver IP is set as '%s'", d.IPAddress)
var stdoutBuf bytes.Buffer
session.Stdout = &stdoutBuf
session.Run("mkdir -p " + sshbasedir)
d.debugf(fmt.Sprintf("%s -> %s", hostname, stdoutBuf.String()))
session.Close()
d.debugf("Trying to copy to %s:%s", clientstr, sshbasedir)
c, err := sshrw.NewSSHclt(clientstr, sshConfig)
if err != nil {
return err
}
// Open a file
f, err := os.Open(d.GetSSHKeyPath() + ".pub")
if err != nil {
return err
}
// TODO: always fails with return status 127, but file was copied correclty
c.WriteFile(f, sshbasedir+"/authorized_keys")
// if err = c.WriteFile(f, sshbasedir+"/authorized_keys"); err != nil {
// d.debugf("Error on file write: ", err)
// }
// Close the file after it has been copied
defer f.Close()
return err
}
// Start starts the VM
func (d *Driver) Start() error {
err := d.connectAPI()
if err != nil {
return err
}
taskid, err := d.driver.NodesNodeQemuVMIDStatusStartPost(d.Node, d.VMID)
if err != nil {
return err
}
err = d.driver.WaitForTaskToComplete(d.Node, taskid)
return err
}
// Stop stopps the VM
func (d *Driver) Stop() error {
return nil
}
// Restart restarts the VM
func (d *Driver) Restart() error {
d.Stop()
d.Start()
return nil
}
// Kill is currently a NOOP
func (d *Driver) Kill() error {
return nil
}
// Remove removes the VM
func (d *Driver) Remove() error {
err := d.connectAPI()
if err != nil {
return err
}
fmt.Println("Check equality of local and remote VMID")
if equal, err := d.checkVmidEquality(); err != nil || !equal {
return err
}
taskid, err := d.driver.NodesNodeQemuVMIDDelete(d.Node, d.VMID)
if err != nil {
return err
}
err = d.driver.WaitForTaskToComplete(d.Node, taskid)
return err
}
// Upgrade is currently a NOOP
func (d *Driver) Upgrade() error {
return nil
}
// NewDriver returns a new driver
func NewDriver(hostName, storePath string) drivers.Driver {
return &Driver{
BaseDriver: &drivers.BaseDriver{
SSHUser: "docker",
MachineName: hostName,
StorePath: storePath,
},
}
}
// GetKeyPair returns a public/private key pair and an optional error
func GetKeyPair(file string) (string, string, error) {
// read keys from file
_, err := os.Stat(file)
if err == nil {
priv, err := ioutil.ReadFile(file)
if err != nil {
fmt.Printf("Failed to read file - %s", err)
goto genKeys
}
pub, err := ioutil.ReadFile(file + ".pub")
if err != nil {
fmt.Printf("Failed to read pub file - %s", err)
goto genKeys
}
return string(pub), string(priv), nil
}
// generate keys and save to file
genKeys:
pub, priv, err := GenKeyPair()
err = ioutil.WriteFile(file, []byte(priv), 0600)
if err != nil {
return "", "", fmt.Errorf("Failed to write file - %s", err)
}
err = ioutil.WriteFile(file+".pub", []byte(pub), 0644)
if err != nil {
return "", "", fmt.Errorf("Failed to write pub file - %s", err)
}
return pub, priv, nil
}
// GenKeyPair returns a freshly created public/private key pair and an optional error
func GenKeyPair() (string, string, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return "", "", err
}
privateKeyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}
var private bytes.Buffer
if err := pem.Encode(&private, privateKeyPEM); err != nil {
return "", "", err
}
// generate public key
pub, err := ssh.NewPublicKey(&privateKey.PublicKey)
if err != nil {
return "", "", err
}
public := ssh.MarshalAuthorizedKey(pub)
return string(public), private.String(), nil
}