Repository navigation
Expand file tree
/
Copy pathCmdWatchInstallation.go
More file actions
3296 lines (2920 loc) · 111 KB
/
Copy pathCmdWatchInstallation.go
File metadata and controls
3296 lines (2920 loc) · 111 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
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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2025 IBM Corp
//
// 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
//
// http://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 main provides the watch-installation command implementation.
//
// This file implements the watch-installation command which monitors OpenShift
// cluster installations and manages associated infrastructure resources. The command
// continuously watches for changes in cluster VMs and automatically updates:
//
// - DNS records for cluster nodes and services
// - HAProxy load balancer configuration
// - DHCP server configuration (optional)
// - Bastion server setup and metadata
//
// The command accepts the following flags:
// - cloud: The cloud to use in clouds.yaml (required)
// - domainName: The DNS domain to use (required)
// - bastionMetadata: Root directory where OpenShift cluster installs are located (required)
// - bastionRsa: The RSA filename for the bastion VM (required)
// - enableDhcpd: Enable the DHCP server (true/false, default: false)
// - dhcpServer: Which DHCP server to manage when enableDhcpd=true: "dhcpd" (default) or "kea"
// - dhcpInterface: The interface name for the DHCP server (required if enableDhcpd=true)
// - dhcpSubnet: The subnet for DHCP requests (required if enableDhcpd=true)
// - dhcpNetmask: The netmask for DHCP requests (required if enableDhcpd=true)
// - dhcpRouter: The router for DHCP requests (required if enableDhcpd=true)
// - dhcpDnsServers: The DNS servers for DHCP requests (required if enableDhcpd=true)
// - dhcpServerId: The DNS server identifier for DHCP requests (required if enableDhcpd=true)
// - statsUser: HAProxy stats username (leave empty to disable stats)
// - statsPassword: HAProxy stats password
// - shouldDebug: Enable debug output (true/false, default: false)
//
// The command runs continuously, waking up every 30 seconds to check for changes
// in the cluster infrastructure and updating configurations as needed.
//
// Example usage:
// ./tool watch-installation --cloud mycloud --domainName example.com \
// --bastionMetadata /path/to/metadata --bastionRsa /path/to/key.rsa --shouldDebug true
package main
import (
"bufio"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io/fs"
"net"
"os"
"os/signal"
"path/filepath"
"regexp"
"slices"
"strings"
"sync"
"syscall"
"time"
"github.com/gophercloud/gophercloud/v2/openstack/compute/v2/servers"
"github.com/IBM/go-sdk-core/v5/core"
"github.com/IBM/networking-go-sdk/dnsrecordsv1"
"github.com/IBM/networking-go-sdk/zonesv1"
"github.com/IBM/platform-services-go-sdk/globalcatalogv1"
"github.com/IBM/platform-services-go-sdk/resourcecontrollerv2"
"k8s.io/apimachinery/pkg/util/sets"
"github.com/sirupsen/logrus"
)
const (
// Flag names for watch-installation command
flagWatchInstallationCloud = "cloud"
flagWatchInstallationDomainName = "domainName"
flagWatchInstallationBastionMetadata = "bastionMetadata"
flagWatchInstallationBastionRsa = "bastionRsa"
flagWatchInstallationEnableDhcpd = "enableDhcpd"
flagWatchInstallationDhcpServer = "dhcpServer"
flagWatchInstallationDhcpInterface = "dhcpInterface"
flagWatchInstallationDhcpSubnet = "dhcpSubnet"
flagWatchInstallationDhcpNetmask = "dhcpNetmask"
flagWatchInstallationDhcpRouter = "dhcpRouter"
flagWatchInstallationDhcpDnsServers = "dhcpDnsServers"
flagWatchInstallationDhcpServerId = "dhcpServerId"
flagWatchInstallationShouldDebug = "shouldDebug"
flagWatchInstallationLog = "log"
// Flag default values
defaultWatchInstallationDomainName = ""
defaultWatchInstallationBastionMetadata = ""
defaultWatchInstallationBastionRsa = ""
defaultWatchInstallationEnableDhcpd = "false"
defaultWatchInstallationDhcpServer = dhcpServerDhcpd
defaultWatchInstallationDhcpInterface = ""
defaultWatchInstallationDhcpSubnet = ""
defaultWatchInstallationDhcpNetmask = ""
defaultWatchInstallationDhcpRouter = ""
defaultWatchInstallationDhcpDnsServers = ""
defaultWatchInstallationDhcpServerId = ""
defaultWatchInstallationShouldDebug = "false"
defaultWatchInstallationLog = ""
// Usage messages
usageWatchInstallationCloud = "The cloud name to use in clouds.yaml (can be specified multiple times)"
usageWatchInstallationDomainName = "The DNS domain to use"
usageWatchInstallationBastionMetadata = "A root directory where OpenShift clusters installs are located"
usageWatchInstallationBastionRsa = "The RSA filename for the bastion VM to use"
usageWatchInstallationEnableDhcpd = "Should enable the DHCP server"
usageWatchInstallationDhcpServer = "The DHCP server to manage: dhcpd or kea"
usageWatchInstallationDhcpInterface = "The interface name for the dhcpd server"
usageWatchInstallationDhcpSubnet = "The subnet for a DHCP request"
usageWatchInstallationDhcpNetmask = "The netmask for a DHCP request"
usageWatchInstallationDhcpRouter = "The router for a DHCP request"
usageWatchInstallationDhcpDnsServers = "The DNS servers for a DHCP request"
usageWatchInstallationDhcpServerId = "The DNS server identifier for a DHCP request"
usageWatchInstallationShouldDebug = "Should output debug output"
usageWatchInstallationLog = "The filename to log all output to"
// Supported DHCP servers
dhcpServerDhcpd = "dhcpd"
dhcpServerKea = "kea"
// Error message prefix
errPrefixWatchInstallation = "Error: "
// Timing constants
watchSleepDuration = 30 * time.Second
watchIterationTimeout = 5 * time.Minute
bastionContextTimeout = 10 * time.Minute
// Network constants
listenPort = ":8080"
)
// scanner := bufio.NewScanner(conn)
// for scanner.Scan() {
// data = scanner.Text()
// vs
// reader := bufio.NewReader(conn)
// for {
// data, err = reader.ReadString('\n')
// vs
// stringArray is a custom type to hold an array of strings.
// It implements the flag.Value interface to support multiple flag values.
type stringArray []string
// String implements the flag.Value interface's String method.
// It returns a comma-separated string of all values.
func (s *stringArray) String() string {
return strings.Join(*s, ",")
}
// Set implements the flag.Value interface's Set method.
// It appends the provided value to the string array.
func (s *stringArray) Set(value string) error {
*s = append(*s, value)
return nil
}
// bastionInformation holds configuration and state information for a bastion server.
// It contains metadata about the cluster installation and connection details.
type bastionInformation struct {
Valid bool // Whether the bastion information is valid
Metadata string // Path to metadata file
Username string // SSH username for bastion; determined at runtime by
// sshDetermineUsername and written by updateBastionInformations
InstallerRsa string // Path to RSA key for installer
ClusterName string // Name of the OpenShift cluster
InfraID string // Infrastructure ID of the cluster
IPAddress string // IP address of the bastion server
NumVMs int // Number of VMs in the cluster
}
// WatchInstallationConfig holds all configuration parameters for the watch-installation command.
// It consolidates all command-line flags and derived configuration into a single structure
// for easier management and testing.
type WatchInstallationConfig struct {
// Cloud configuration
Clouds []string // List of cloud names to use from clouds.yaml
// DNS configuration
DomainName string // DNS domain name for the cluster
// Bastion configuration
BastionMetadataDir string // Root directory where OpenShift cluster installs are located
BastionRsa string // Path to RSA key file for bastion VM
// DHCP configuration
EnableDhcpd bool // Whether to enable the DHCP server
DhcpServer string // Which DHCP server to manage: "dhcpd" (default when empty) or "kea"
DhcpInterface string // Network interface name for DHCP server
DhcpSubnet string // Subnet for DHCP requests
DhcpNetmask string // Netmask for DHCP requests
DhcpRouter string // Router IP address for DHCP requests
DhcpDnsServers string // Comma-separated list of DNS servers for DHCP requests
DhcpServerId string // DHCP server identifier (IP address)
// HAProxy configuration
StatsUser string // HAProxy statistics username (empty to disable stats)
StatsPassword string // HAProxy statistics password
// Operational configuration
ShouldDebug bool // Whether to enable debug output
LogFile string // Filename to log all output to
// Runtime configuration (not from flags)
APIKey string // IBM Cloud API key from environment
// Internal use
ResolvedImageName string // The OpenStack image name in case the user specified a UUID
BastionRsaPub string // Contents of the RSA public key for local SSH setup (mutually exclusive with ServerIP)
}
// Validate performs comprehensive validation of all configuration parameters.
// It checks required fields, validates formats, and ensures consistency between related fields.
//
// Returns:
// - error: An error describing the first validation failure, or nil if all validations pass
func (c *WatchInstallationConfig) Validate() error {
// Validate cloud names
if len(c.Clouds) == 0 {
return fmt.Errorf("at least one cloud name must be specified")
}
for i, cloud := range c.Clouds {
if cloud == "" {
return fmt.Errorf("cloud name at index %d is empty", i)
}
if err := validateCloudName(cloud); err != nil {
return fmt.Errorf("invalid cloud name at index %d: %w", i, err)
}
}
// Validate required string fields
if c.DomainName == "" {
return fmt.Errorf("domain name is required")
}
if c.BastionMetadataDir == "" {
return fmt.Errorf("bastion metadata directory is required")
}
if c.BastionRsa == "" {
return fmt.Errorf("bastion RSA key path is required")
}
// File path validation
if _, err := os.Stat(c.BastionRsa); err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("bastionRsa: file not found: %q", c.BastionRsa)
} else {
return fmt.Errorf("bastionRsa: cannot access file: %w", err)
}
}
bastionRsaPub := c.BastionRsa + ".pub"
bastionRsaPubValid := true
if _, err := os.Stat(bastionRsaPub); err != nil {
bastionRsaPubValid = false
}
if bastionRsaPubValid {
content, err := os.ReadFile(bastionRsaPub)
if err == nil {
c.BastionRsaPub = string(content)
}
}
// Validate domain name format
if err := validateDomainName(c.DomainName); err != nil {
return fmt.Errorf("invalid domain name: %w", err)
}
// Validate DHCP configuration if enabled
if c.EnableDhcpd {
switch c.DhcpServer {
case "", dhcpServerDhcpd, dhcpServerKea:
default:
return fmt.Errorf("DHCP server must be %q or %q, got %q", dhcpServerDhcpd, dhcpServerKea, c.DhcpServer)
}
if c.DhcpInterface == "" {
return fmt.Errorf("DHCP interface is required when DHCP is enabled")
}
if c.DhcpSubnet == "" {
return fmt.Errorf("DHCP subnet is required when DHCP is enabled")
}
if c.DhcpNetmask == "" {
return fmt.Errorf("DHCP netmask is required when DHCP is enabled")
}
if c.DhcpRouter == "" {
return fmt.Errorf("DHCP router is required when DHCP is enabled")
}
if c.DhcpDnsServers == "" {
return fmt.Errorf("DHCP DNS servers are required when DHCP is enabled")
}
if c.DhcpServerId == "" {
return fmt.Errorf("DHCP server ID is required when DHCP is enabled")
}
// Validate DHCP parameter formats
if err := validateInterfaceName(c.DhcpInterface); err != nil {
return fmt.Errorf("invalid DHCP interface: %w", err)
}
if err := validateIPAddress(c.DhcpSubnet); err != nil {
return fmt.Errorf("invalid DHCP subnet: %w", err)
}
if err := validateNetmask(c.DhcpNetmask); err != nil {
return fmt.Errorf("invalid DHCP netmask: %w", err)
}
if err := validateIPAddress(c.DhcpRouter); err != nil {
return fmt.Errorf("invalid DHCP router: %w", err)
}
if err := validateDNSServerList(c.DhcpDnsServers); err != nil {
return fmt.Errorf("invalid DHCP DNS servers: %w", err)
}
if err := validateIPAddress(c.DhcpServerId); err != nil {
return fmt.Errorf("invalid DHCP server ID: %w", err)
}
}
// Validate HAProxy stats credentials
if err := validateHAProxyCredentials(c.StatsUser, c.StatsPassword); err != nil {
return fmt.Errorf("invalid HAProxy stats credentials: %w", err)
}
return nil
}
// validateIPAddress validates that a string is a valid IP address (IPv4 or IPv6).
//
// Parameters:
// - ip: The IP address string to validate
//
// Returns:
// - error: An error if the IP address is invalid, nil otherwise
func validateIPAddress(ip string) error {
if net.ParseIP(ip) == nil {
return fmt.Errorf("invalid IP address: %s", ip)
}
return nil
}
// validateNetmask validates that a string is a valid IPv4 netmask.
//
// A valid netmask must be a valid IP address and must have all 1s followed by all 0s
// in binary representation (e.g., 255.255.255.0 is valid, 255.255.0.255 is not).
//
// Parameters:
// - netmask: The netmask string to validate
//
// Returns:
// - error: An error if the netmask is invalid, nil otherwise
func validateNetmask(netmask string) error {
ip := net.ParseIP(netmask)
if ip == nil {
return fmt.Errorf("invalid netmask: %s", netmask)
}
// Convert to 4-byte representation
ip4 := ip.To4()
if ip4 == nil {
return fmt.Errorf("netmask must be IPv4: %s", netmask)
}
// Verify it's a valid netmask (all 1s followed by all 0s in binary)
// Convert to uint32 and verify
maskUint := uint32(ip4[0])<<24 | uint32(ip4[1])<<16 | uint32(ip4[2])<<8 | uint32(ip4[3])
// A valid netmask has all 1s on the left, all 0s on the right
// Invert it, add 1, should be a power of 2 (or 0 for all 1s mask)
inverted := ^maskUint
if inverted != 0 && (inverted&(inverted+1)) != 0 {
return fmt.Errorf("netmask has non-contiguous bits: %s", netmask)
}
return nil
}
// validateDomainName validates that a string is a valid DNS domain name.
//
// The validation follows RFC 1035 rules:
// - Maximum length of 253 characters
// - Labels separated by dots
// - Each label: 1-63 characters, alphanumeric and hyphens
// - Labels cannot start or end with hyphen
//
// Parameters:
// - domain: The domain name string to validate
//
// Returns:
// - error: An error if the domain name is invalid, nil otherwise
func validateDomainName(domain string) error {
if len(domain) == 0 {
return fmt.Errorf("domain name cannot be empty")
}
if len(domain) > 253 {
return fmt.Errorf("domain name too long (max 253 characters): %s", domain)
}
// RFC 1035 domain name validation
// Each label must be 1-63 characters, alphanumeric and hyphens
// Cannot start or end with hyphen
domainRegex := regexp.MustCompile(`^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?$`)
if !domainRegex.MatchString(domain) {
return fmt.Errorf("invalid domain name format: %s", domain)
}
return nil
}
// validateDNSServerList validates a comma-separated list of DNS server IP addresses.
//
// Parameters:
// - servers: Comma-separated list of DNS server IP addresses
//
// Returns:
// - error: An error if any DNS server IP is invalid, nil otherwise
func validateDNSServerList(servers string) error {
if servers == "" {
return fmt.Errorf("DNS server list cannot be empty")
}
serverList := strings.Split(servers, ",")
for _, server := range serverList {
server = strings.TrimSpace(server)
if server == "" {
return fmt.Errorf("DNS server list contains empty entry")
}
if err := validateIPAddress(server); err != nil {
return fmt.Errorf("invalid DNS server in list: %w", err)
}
}
return nil
}
// validateHAProxyUsername validates a HAProxy statistics username.
//
// Valid usernames must:
// - Be 1-64 characters long
// - Contain only alphanumeric characters, hyphens, underscores, and periods
// - Not contain characters that could cause HAProxy config injection
//
// Parameters:
// - username: The username string to validate
//
// Returns:
// - error: An error if the username is invalid, nil otherwise
func validateHAProxyUsername(username string) error {
if username == "" {
return nil // Empty username is allowed (disables stats)
}
if len(username) > 64 {
return fmt.Errorf("username too long (max 64 characters): %d", len(username))
}
// Allow alphanumeric, dash, underscore, and period
usernameRegex := regexp.MustCompile(`^[a-zA-Z0-9_.-]+$`)
if !usernameRegex.MatchString(username) {
return fmt.Errorf("invalid username format (only alphanumeric, dash, underscore, period allowed): %s", username)
}
// Reject suspicious patterns that could be used for injection
if strings.Contains(username, "..") || strings.Contains(username, "--") {
return fmt.Errorf("username contains suspicious patterns: %s", username)
}
return nil
}
// validateHAProxyPassword validates a HAProxy statistics password.
//
// Valid passwords must:
// - Be 1-128 characters long
// - Not contain characters that could cause HAProxy config injection
// - Not contain newlines, carriage returns, or null bytes
// - Not contain unescaped quotes or backslashes
//
// Parameters:
// - password: The password string to validate
//
// Returns:
// - error: An error if the password is invalid, nil otherwise
func validateHAProxyPassword(password string) error {
if password == "" {
return nil // Empty password is allowed (disables stats)
}
if len(password) > 128 {
return fmt.Errorf("password too long (max 128 characters): %d", len(password))
}
// Reject control characters and characters that could break HAProxy config
for i, r := range password {
if r == '\n' || r == '\r' || r == '\x00' {
return fmt.Errorf("password contains invalid control character at position %d", i)
}
// Reject unescaped quotes and backslashes that could break config
if r == '"' || r == '\'' || r == '\\' {
return fmt.Errorf("password contains invalid character '%c' at position %d (quotes and backslashes not allowed)", r, i)
}
// Reject hash/comment characters that could inject config
if r == '#' {
return fmt.Errorf("password contains invalid character '#' at position %d", i)
}
}
return nil
}
// validateHAProxyCredentials validates both username and password together.
//
// This function ensures that if one credential is provided, both must be provided,
// and both must pass individual validation.
//
// Parameters:
// - username: The username to validate
// - password: The password to validate
//
// Returns:
// - error: An error if the credentials are invalid, nil otherwise
func validateHAProxyCredentials(username, password string) error {
// Both empty is valid (stats disabled)
if username == "" && password == "" {
return nil
}
// If one is provided, both must be provided
if username == "" && password != "" {
return fmt.Errorf("password provided but username is empty")
}
if username != "" && password == "" {
return fmt.Errorf("username provided but password is empty")
}
// Validate username
if err := validateHAProxyUsername(username); err != nil {
return fmt.Errorf("invalid HAProxy stats username: %w", err)
}
// Validate password
if err := validateHAProxyPassword(password); err != nil {
return fmt.Errorf("invalid HAProxy stats password: %w", err)
}
return nil
}
// validateInterfaceName validates that a string is a valid network interface name.
//
// Valid interface names contain only alphanumeric characters, hyphens, underscores,
// and periods. This prevents command injection through interface names.
//
// Parameters:
// - iface: The interface name string to validate
//
// Returns:
// - error: An error if the interface name is invalid, nil otherwise
func validateInterfaceName(iface string) error {
if iface == "" {
return fmt.Errorf("interface name cannot be empty")
}
// Allow alphanumeric, dash, underscore, and period (common in interface names)
ifaceRegex := regexp.MustCompile(`^[a-zA-Z0-9_.-]+$`)
if !ifaceRegex.MatchString(iface) {
return fmt.Errorf("invalid interface name (only alphanumeric, dash, underscore, period allowed): %s", iface)
}
// Additional safety: reject names that look like command injection attempts
if strings.Contains(iface, "..") || strings.Contains(iface, "//") {
return fmt.Errorf("interface name contains suspicious patterns: %s", iface)
}
return nil
}
// stdoutHook is a custom logrus Hook that writes warnings, errors, fatals, and panics to stdout.
type stdoutHook struct {
formatter logrus.Formatter
}
func (h *stdoutHook) Levels() []logrus.Level {
return []logrus.Level{
logrus.WarnLevel,
logrus.ErrorLevel,
logrus.FatalLevel,
logrus.PanicLevel,
}
}
func (h *stdoutHook) Fire(entry *logrus.Entry) error {
serialized, err := h.formatter.Format(entry)
if err != nil {
return err
}
_, err = os.Stdout.Write(serialized)
return err
}
// watchInstallationCommand executes the watch-installation command with the given flags and arguments.
//
// This function continuously monitors OpenShift cluster installations and manages associated
// infrastructure resources including DNS records, HAProxy configuration, and optionally DHCP
// server configuration. It runs in an infinite loop, checking for changes every 30 seconds.
//
// Parameters:
// - watchInstallationFlags: The FlagSet containing command-line flags (must not be nil)
// - args: Command-line arguments to parse
//
// Returns:
// - error: Any error encountered during flag parsing, validation, or operation execution
//
// Example usage:
//
// err := watchInstallationCommand(flagSet, []string{
// "--cloud", "mycloud",
// "--domainName", "example.com",
// "--bastionMetadata", "/path/to/metadata",
// "--bastionRsa", "/path/to/key.rsa",
// })
func watchInstallationCommand(watchInstallationFlags *flag.FlagSet, args []string) error {
err := innerWatchInstallationCommand(watchInstallationFlags, args)
if err != nil {
fmt.Printf("%+v\n", err)
if watchInstallationFlags != nil {
watchInstallationFlags.Usage()
}
}
return err
}
// innerWatchInstallationCommand is the main implementation of the watch-installation command.
//
// Parameters:
// - watchInstallationFlags: The FlagSet containing command-line flags (must not be nil)
// - args: Command-line arguments to parse
//
// Returns:
// - error: Any error encountered during flag parsing, validation, or operation execution
//
// The function executes the following steps:
// 1. Validates that the FlagSet is not nil
// 2. Displays program version information
// 3. Retrieves the IBM Cloud API key from the IBMCLOUD_API_KEY environment variable
// 4. Defines and parses command-line flags
// 5. Parses boolean flags (enableDhcpd, shouldDebug)
// 6. Initialises the logger, then flushes any pre-logger messages
// 7. Validates the fully populated configuration
// 8. Sets up OS signal handling (SIGINT, SIGTERM) for graceful shutdown
// 9. Spawns the metadata listener goroutine on listenPort (:8080)
//
// 10. Performs an initial monitoring iteration immediately
// 11. Enters a ticker-based loop (every 30 s) that:
// - Runs performMonitoringIteration on each tick
// - Returns on shutdown signal or listener failure
func innerWatchInstallationCommand(watchInstallationFlags *flag.FlagSet, args []string) error {
var (
preLog strings.Builder
clouds cloudFlags
knownServers = sets.Set[string]{}
knownBastions []bastionInformation
err error
)
// Validate input parameters
if watchInstallationFlags == nil {
return fmt.Errorf("%sflag set cannot be nil", errPrefixWatchInstallation)
}
// Display version information
fmt.Fprintf(os.Stderr, "Program version is %v, release = %v\n", version, release)
// Create a pre-debug log before we know that debugging is enabled
fmt.Fprintf(&preLog, "Starting watch-installation command\n")
// Create configuration structure
config := &WatchInstallationConfig{
APIKey: os.Getenv("IBMCLOUD_API_KEY"),
}
// Define command-line flags
watchInstallationFlags.Var(&clouds, flagWatchInstallationCloud, usageWatchInstallationCloud)
ptrDomainName := watchInstallationFlags.String(flagWatchInstallationDomainName, defaultWatchInstallationDomainName, usageWatchInstallationDomainName)
ptrBastionMetadata := watchInstallationFlags.String(flagWatchInstallationBastionMetadata, defaultWatchInstallationBastionMetadata, usageWatchInstallationBastionMetadata)
ptrBastionRsa := watchInstallationFlags.String(flagWatchInstallationBastionRsa, defaultWatchInstallationBastionRsa, usageWatchInstallationBastionRsa)
ptrEnableDhcpd := watchInstallationFlags.String(flagWatchInstallationEnableDhcpd, defaultWatchInstallationEnableDhcpd, usageWatchInstallationEnableDhcpd)
ptrDhcpServer := watchInstallationFlags.String(flagWatchInstallationDhcpServer, defaultWatchInstallationDhcpServer, usageWatchInstallationDhcpServer)
ptrDhcpInterface := watchInstallationFlags.String(flagWatchInstallationDhcpInterface, defaultWatchInstallationDhcpInterface, usageWatchInstallationDhcpInterface)
ptrDhcpSubnet := watchInstallationFlags.String(flagWatchInstallationDhcpSubnet, defaultWatchInstallationDhcpSubnet, usageWatchInstallationDhcpSubnet)
ptrDhcpNetmask := watchInstallationFlags.String(flagWatchInstallationDhcpNetmask, defaultWatchInstallationDhcpNetmask, usageWatchInstallationDhcpNetmask)
ptrDhcpRouter := watchInstallationFlags.String(flagWatchInstallationDhcpRouter, defaultWatchInstallationDhcpRouter, usageWatchInstallationDhcpRouter)
ptrDhcpDnsServers := watchInstallationFlags.String(flagWatchInstallationDhcpDnsServers, defaultWatchInstallationDhcpDnsServers, usageWatchInstallationDhcpDnsServers)
ptrDhcpServerId := watchInstallationFlags.String(flagWatchInstallationDhcpServerId, defaultWatchInstallationDhcpServerId, usageWatchInstallationDhcpServerId)
ptrShouldDebug := watchInstallationFlags.String(flagWatchInstallationShouldDebug, defaultWatchInstallationShouldDebug, usageWatchInstallationShouldDebug)
ptrLogFile := watchInstallationFlags.String(flagWatchInstallationLog, defaultWatchInstallationLog, usageWatchInstallationLog)
ptrStatsUser := watchInstallationFlags.String("statsUser", "", "HAProxy stats username (leave empty to disable stats)")
ptrStatsPassword := watchInstallationFlags.String("statsPassword", "", "HAProxy stats password")
// Parse command-line arguments
err = watchInstallationFlags.Parse(args)
if err != nil {
return fmt.Errorf("%sfailed to parse flags: %w", errPrefixWatchInstallation, err)
}
// Populate configuration from parsed flags
config.Clouds = []string(clouds)
config.DomainName = *ptrDomainName
config.BastionMetadataDir = *ptrBastionMetadata
config.BastionRsa = *ptrBastionRsa
config.DhcpServer = strings.ToLower(*ptrDhcpServer)
config.DhcpInterface = *ptrDhcpInterface
config.DhcpSubnet = *ptrDhcpSubnet
config.DhcpNetmask = *ptrDhcpNetmask
config.DhcpRouter = *ptrDhcpRouter
config.DhcpDnsServers = *ptrDhcpDnsServers
config.DhcpServerId = *ptrDhcpServerId
config.StatsUser = *ptrStatsUser
config.StatsPassword = *ptrStatsPassword
config.LogFile = *ptrLogFile
// Parse enableDhcpd flag
fmt.Fprintf(&preLog, "Parsing DHCP configuration\n")
switch strings.ToLower(*ptrEnableDhcpd) {
case boolTrue:
config.EnableDhcpd = true
fmt.Fprintf(&preLog, "DHCP server enabled\n")
case boolFalse:
config.EnableDhcpd = false
fmt.Fprintf(&preLog, "DHCP server disabled\n")
default:
return fmt.Errorf("%s%s must be 'true' or 'false', got '%s'", errPrefixWatchInstallation, flagWatchInstallationEnableDhcpd, *ptrEnableDhcpd)
}
// Parse debug flag
shouldDebug, err := parseBoolFlag(*ptrShouldDebug, flagWatchInstallationShouldDebug)
if err != nil {
return fmt.Errorf("%s%w", errPrefixWatchInstallation, err)
}
config.ShouldDebug = shouldDebug
// Initialize logger
log = initLogger(config.ShouldDebug)
if config.LogFile != "" {
if log.Hooks == nil {
log.Hooks = make(logrus.LevelHooks)
}
file, err := os.OpenFile(config.LogFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
return fmt.Errorf("%sfailed to open log file %q: %w", errPrefixWatchInstallation, config.LogFile, err)
}
defer file.Close()
log.Out = file
log.AddHook(&stdoutHook{formatter: log.Formatter})
}
if config.ShouldDebug {
log.Debugf("Debug mode enabled")
}
// Dump the prelogged lines now that log has been initialized!
scanner := bufio.NewScanner(strings.NewReader(preLog.String()))
for scanner.Scan() {
line := scanner.Text()
log.Println(line)
}
// Validate configuration using the config's Validate method
log.Infof("Validating configuration")
if err := config.Validate(); err != nil {
return fmt.Errorf("%s%w", errPrefixWatchInstallation, err)
}
log.Infof("Configuration validated successfully")
// Log configuration details
for i, cloud := range config.Clouds {
log.Debugf("Cloud[%d]: %s", i, cloud)
}
log.Debugf("Domain name: %s", config.DomainName)
log.Debugf("Bastion metadata dir: %s", config.BastionMetadataDir)
log.Debugf("Bastion RSA: %s", config.BastionRsa)
if config.EnableDhcpd {
log.Debugf("DHCP server: %s", config.DhcpServer)
log.Debugf("DHCP interface: %s", config.DhcpInterface)
log.Debugf("DHCP subnet: %s", config.DhcpSubnet)
log.Debugf("DHCP netmask: %s", config.DhcpNetmask)
log.Debugf("DHCP router: %s", config.DhcpRouter)
log.Debugf("DHCP DNS servers: %s", config.DhcpDnsServers)
log.Debugf("DHCP server ID: %s", config.DhcpServerId)
}
if config.StatsUser != "" && config.StatsPassword != "" {
log.Infof("HAProxy stats enabled with username: %s", config.StatsUser)
} else {
log.Infof("HAProxy stats disabled (no credentials provided)")
}
// Set up signal handling for graceful shutdown
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
// Create error channel for listener goroutine
listenerErrChan := make(chan error, 1)
// Spawn metadata listener goroutine
log.Infof("Starting metadata listener on port %s", listenPort)
go func() {
if err := listenForCommands(ctx, config); err != nil {
log.Errorf("Command listener failed: %v", err)
listenerErrChan <- err
}
}()
// Enter monitoring loop with graceful shutdown support
log.Infof("Entering monitoring loop")
ticker := time.NewTicker(watchSleepDuration)
defer ticker.Stop()
// Perform initial check immediately
if knownBastions, err = performMonitoringIteration(ctx, config, &knownServers, knownBastions); err != nil {
log.Errorf("[ERROR] Initial monitoring iteration failed: %v", err)
// Continue to loop rather than failing immediately
}
for {
select {
case <-ctx.Done():
log.Infof("Received shutdown signal, cleaning up...")
return performGracefulShutdown()
case err := <-listenerErrChan:
log.Errorf("[ERROR] Listener failed: %v", err)
return fmt.Errorf("command listener failed: %w", err)
case <-ticker.C:
log.Infof("Waking up to check for changes")
if knownBastions, err = performMonitoringIteration(ctx, config, &knownServers, knownBastions); err != nil {
log.Errorf("[ERROR] Monitoring iteration failed: %v", err)
// Continue monitoring despite errors
}
}
}
}
// performMonitoringIteration executes a single monitoring iteration.
//
// The function wraps all work in a 5-minute child context (watchIterationTimeout)
// so that a hung OpenStack call does not block indefinitely.
//
// Steps performed on every call:
// 1. Gather bastion information from the metadata directory
// 2. Retrieve all OpenStack servers across all configured clouds
// 3. Build the current server set (bootstrap/master/worker nodes with IPs)
// 4. Diff against knownServers to find added and deleted servers
// 5. If no changes are detected, return early (knownServers and bastions unchanged)
// 6. Update knownServers to the new set
// 7. Update bastion configurations via updateBastionInformations
// 8. If DHCP is enabled: regenerate the configuration for the selected server
// (dhcpd: /tmp/dhcpd.conf -> /etc/dhcp/dhcpd.conf, restart dhcpd.service;
// kea: /tmp/kea-dhcp4.conf -> /etc/kea/kea-dhcp4.conf, restart kea-dhcp4.service)
// 9. Update HAProxy configuration on each valid bastion via haproxyCfg
//
// 10. If an IBM Cloud API key is available: manage DNS records via dnsRecords
//
// Parameters:
// - ctx: Parent context for cancellation and timeout
// - config: Configuration containing all parameters
// - knownServers: Pointer to the set of known server names (mutated in place on changes)
// - knownBastions: Bastion information from the previous iteration (used for username caching)
//
// Returns:
// - []bastionInformation: Updated bastion information slice for the next iteration
// - error: Any error encountered during the iteration; nil on success or no-op early return
func performMonitoringIteration(ctx context.Context, config *WatchInstallationConfig, knownServers *sets.Set[string], knownBastions []bastionInformation) ([]bastionInformation, error) {
// Create iteration context with timeout
iterCtx, iterCancel := context.WithTimeout(ctx, watchIterationTimeout)
defer iterCancel()
// Convert clouds to cloudFlags type
clouds := cloudFlags(config.Clouds)
// Gather bastion information from metadata directories
log.Infof("Gathering bastion information from: %s", config.BastionMetadataDir)
bastionInformations, err := gatherBastionInformations(config.BastionMetadataDir, config.BastionRsa)
if err != nil {
return nil, fmt.Errorf("failed to gather bastion information: %w", err)
}
log.Debugf("bastionInformations [%d] = %+v", len(bastionInformations), bastionInformations)
log.Infof("Found %d bastion(s)", len(bastionInformations))
// Retrieve all servers from OpenStack
log.Infof("Retrieving all servers from clouds: %+v", clouds)
allServers, err := getAllServers(iterCtx, clouds)
if err != nil {
return nil, fmt.Errorf("failed to get all servers: %w", err)
}
log.Infof("Retrieved %d server(s)", len(allServers))
// Detect changes in server set
newServerSet := getServerSet(allServers)
addedServersSet := newServerSet.Difference(*knownServers)
deletedServerSet := knownServers.Difference(newServerSet)
log.Debugf("knownServers = %+v", *knownServers)
log.Debugf("newServerSet = %+v", newServerSet)
log.Debugf("addedServersSet = %+v", addedServersSet)
log.Debugf("deletedServerSet = %+v", deletedServerSet)
// If no changes detected, return early
if addedServersSet.Len() == 0 && deletedServerSet.Len() == 0 {
log.Infof("No server changes detected")
return bastionInformations, nil
}
// Update known servers set
log.Infof("Server changes detected: %d added, %d deleted", addedServersSet.Len(), deletedServerSet.Len())
*knownServers = newServerSet
// Update bastion configurations
log.Infof("Updating bastion configurations")
err = updateBastionInformations(iterCtx, clouds, bastionInformations, knownBastions)
if err != nil {
return nil, fmt.Errorf("failed to update bastion information: %w", err)
}
log.Infof("Bastion configurations updated successfully")
// Update DHCP configuration if enabled
log.Debugf("enableDhcpd = %v", config.EnableDhcpd)
if config.EnableDhcpd {
var (
filename string
destination string
serviceName string
generate func() error
)
log.Infof("Updating DHCP configuration (server: %s)", config.DhcpServer)
switch config.DhcpServer {
case dhcpServerKea:
filename = "/tmp/kea-dhcp4.conf"
destination = "/etc/kea/kea-dhcp4.conf"
serviceName = "kea-dhcp4.service"
generate = func() error {
return keaConf(iterCtx,
filename,
clouds,
config.DomainName,
config.DhcpInterface,
config.DhcpSubnet,
config.DhcpNetmask,
config.DhcpRouter,
config.DhcpDnsServers,
config.DhcpServerId,
)
}
default:
filename = "/tmp/dhcpd.conf"
destination = "/etc/dhcp/dhcpd.conf"
serviceName = "dhcpd.service"
generate = func() error {
return dhcpdConf(iterCtx,
filename,
clouds,
config.DomainName,
config.DhcpInterface,
config.DhcpSubnet,
config.DhcpNetmask,
config.DhcpRouter,
config.DhcpDnsServers,
config.DhcpServerId,
)
}
}
err = generate()
if err != nil {
return nil, fmt.Errorf("failed to generate DHCP configuration: %w", err)
}
log.Infof("DHCP configuration generated: %s", filename)
log.Infof("Copying DHCP configuration to %s", destination)
err = runSplitCommand([]string{