diff --git a/api/v1beta1/zz_generated.conversion.go b/api/v1beta1/zz_generated.conversion.go index 16331b3613..7eed081c55 100644 --- a/api/v1beta1/zz_generated.conversion.go +++ b/api/v1beta1/zz_generated.conversion.go @@ -562,6 +562,7 @@ func autoConvert_v1beta2_IBMPowerVSClusterSpec_To_v1beta1_IBMPowerVSClusterSpec( // WARNING: in.ResourceGroup requires manual conversion: does not exist in peer-type // WARNING: in.VPC requires manual conversion: does not exist in peer-type // WARNING: in.VPCSubnets requires manual conversion: does not exist in peer-type + // WARNING: in.VPCSecurityGroups requires manual conversion: does not exist in peer-type // WARNING: in.TransitGateway requires manual conversion: does not exist in peer-type // WARNING: in.LoadBalancers requires manual conversion: does not exist in peer-type // WARNING: in.CosInstance requires manual conversion: does not exist in peer-type @@ -587,6 +588,7 @@ func autoConvert_v1beta2_IBMPowerVSClusterStatus_To_v1beta1_IBMPowerVSClusterSta // WARNING: in.DHCPServer requires manual conversion: does not exist in peer-type // WARNING: in.VPC requires manual conversion: does not exist in peer-type // WARNING: in.VPCSubnet requires manual conversion: does not exist in peer-type + // WARNING: in.VPCSecurityGroups requires manual conversion: does not exist in peer-type // WARNING: in.TransitGateway requires manual conversion: does not exist in peer-type // WARNING: in.COSInstance requires manual conversion: does not exist in peer-type // WARNING: in.LoadBalancers requires manual conversion: does not exist in peer-type diff --git a/api/v1beta2/conditions_consts.go b/api/v1beta2/conditions_consts.go index 1ded21813f..a3cda55973 100644 --- a/api/v1beta2/conditions_consts.go +++ b/api/v1beta2/conditions_consts.go @@ -85,6 +85,11 @@ const ( // NetworkReconciliationFailedReason used when an error occurs during network reconciliation. NetworkReconciliationFailedReason = "NetworkReconciliationFailed" + // VPCSecurityGroupReadyCondition reports on the successful reconciliation of a VPC. + VPCSecurityGroupReadyCondition capiv1beta1.ConditionType = "VPCSecurityGroupReady" + // VPCSecurityGroupReconciliationFailedReason used when an error occurs during VPC reconciliation. + VPCSecurityGroupReconciliationFailedReason = "VPCSecurityGroupReconciliationFailed" + // VPCReadyCondition reports on the successful reconciliation of a VPC. VPCReadyCondition capiv1beta1.ConditionType = "VPCReady" // VPCReconciliationFailedReason used when an error occurs during VPC reconciliation. diff --git a/api/v1beta2/ibmpowervscluster_types.go b/api/v1beta2/ibmpowervscluster_types.go index 65efbf5cd1..4254ff91a7 100644 --- a/api/v1beta2/ibmpowervscluster_types.go +++ b/api/v1beta2/ibmpowervscluster_types.go @@ -103,6 +103,10 @@ type IBMPowerVSClusterSpec struct { // +optional VPCSubnets []Subnet `json:"vpcSubnets,omitempty"` + // securityGroups to attach it to the VPC resource + // +optional + VPCSecurityGroups []SecurityGroup `json:"vpcSecurityGroups,omitempty"` + // transitGateway contains information about IBM Cloud TransitGateway // IBM Cloud TransitGateway helps in establishing network connectivity between IBM Cloud Power VS and VPC infrastructure // more information about TransitGateway can be found here https://www.ibm.com/products/transit-gateway. @@ -200,6 +204,9 @@ type IBMPowerVSClusterStatus struct { // vpcSubnet is reference to IBM Cloud VPC subnet. VPCSubnet map[string]ResourceReference `json:"vpcSubnet,omitempty"` + // vpcSecurityGroups is reference to IBM Cloud VPC security group. + VPCSecurityGroups map[string]VPCSecurityGroupStatus `json:"vpcSecurityGroups,omitempty"` + // transitGateway is reference to IBM Cloud TransitGateway. TransitGateway *ResourceReference `json:"transitGateway,omitempty"` diff --git a/api/v1beta2/ibmvpccluster_types.go b/api/v1beta2/ibmvpccluster_types.go index 945f34ea58..9836b86015 100644 --- a/api/v1beta2/ibmvpccluster_types.go +++ b/api/v1beta2/ibmvpccluster_types.go @@ -93,6 +93,17 @@ type AdditionalListenerSpec struct { Port int64 `json:"port"` } +// VPCSecurityGroupStatus defines a vpc security group resource status with its id and respective rule's ids. +type VPCSecurityGroupStatus struct { + // id represents the id of the resource. + ID *string `json:"id,omitempty"` + // rules contains the id of rules created under the security group + RuleIDs []*string `json:"rules,omitempty"` + // +kubebuilder:default=false + // controllerCreated indicates whether the resource is created by the controller. + ControllerCreated *bool `json:"controllerCreated,omitempty"` +} + // VPCLoadBalancerStatus defines the status VPC load balancer. type VPCLoadBalancerStatus struct { // id of VPC load balancer. diff --git a/api/v1beta2/zz_generated.deepcopy.go b/api/v1beta2/zz_generated.deepcopy.go index e234e2bdfb..b5fbeb551e 100644 --- a/api/v1beta2/zz_generated.deepcopy.go +++ b/api/v1beta2/zz_generated.deepcopy.go @@ -193,6 +193,13 @@ func (in *IBMPowerVSClusterSpec) DeepCopyInto(out *IBMPowerVSClusterSpec) { (*in)[i].DeepCopyInto(&(*out)[i]) } } + if in.VPCSecurityGroups != nil { + in, out := &in.VPCSecurityGroups, &out.VPCSecurityGroups + *out = make([]SecurityGroup, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } if in.TransitGateway != nil { in, out := &in.TransitGateway, &out.TransitGateway *out = new(TransitGateway) @@ -262,6 +269,13 @@ func (in *IBMPowerVSClusterStatus) DeepCopyInto(out *IBMPowerVSClusterStatus) { (*out)[key] = *val.DeepCopy() } } + if in.VPCSecurityGroups != nil { + in, out := &in.VPCSecurityGroups, &out.VPCSecurityGroups + *out = make(map[string]VPCSecurityGroupStatus, len(*in)) + for key, val := range *in { + (*out)[key] = *val.DeepCopy() + } + } if in.TransitGateway != nil { in, out := &in.TransitGateway, &out.TransitGateway *out = new(ResourceReference) @@ -1665,6 +1679,42 @@ func (in *VPCResourceReference) DeepCopy() *VPCResourceReference { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *VPCSecurityGroupStatus) DeepCopyInto(out *VPCSecurityGroupStatus) { + *out = *in + if in.ID != nil { + in, out := &in.ID, &out.ID + *out = new(string) + **out = **in + } + if in.RuleIDs != nil { + in, out := &in.RuleIDs, &out.RuleIDs + *out = make([]*string, len(*in)) + for i := range *in { + if (*in)[i] != nil { + in, out := &(*in)[i], &(*out)[i] + *out = new(string) + **out = **in + } + } + } + if in.ControllerCreated != nil { + in, out := &in.ControllerCreated, &out.ControllerCreated + *out = new(bool) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VPCSecurityGroupStatus. +func (in *VPCSecurityGroupStatus) DeepCopy() *VPCSecurityGroupStatus { + if in == nil { + return nil + } + out := new(VPCSecurityGroupStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VPCVolume) DeepCopyInto(out *VPCVolume) { *out = *in diff --git a/cloud/scope/powervs_cluster.go b/cloud/scope/powervs_cluster.go index a05af53fee..87335b6c64 100644 --- a/cloud/scope/powervs_cluster.go +++ b/cloud/scope/powervs_cluster.go @@ -20,6 +20,8 @@ import ( "context" "errors" "fmt" + "reflect" + "strconv" "strings" "github.com/go-logr/logr" @@ -463,6 +465,31 @@ func (s *PowerVSClusterScope) SetVPCSubnetID(name string, resource infrav1beta2. s.IBMPowerVSCluster.Status.VPCSubnet[name] = resource } +// GetVPCSecurityGroupID returns the VPC security group id. +func (s *PowerVSClusterScope) GetVPCSecurityGroupID(name string) (*string, []*string) { + if s.IBMPowerVSCluster.Status.VPCSecurityGroups == nil { + return nil, nil + } + if val, ok := s.IBMPowerVSCluster.Status.VPCSecurityGroups[name]; ok { + return val.ID, val.RuleIDs + } + return nil, nil +} + +// SetVPCSecurityGroupID set the VPC security group id. +func (s *PowerVSClusterScope) SetVPCSecurityGroupID(name string, resource infrav1beta2.VPCSecurityGroupStatus) { + s.V(3).Info("Setting VPC security group status", "name", name, "resource", resource) + if s.IBMPowerVSCluster.Status.VPCSecurityGroups == nil { + s.IBMPowerVSCluster.Status.VPCSecurityGroups = make(map[string]infrav1beta2.VPCSecurityGroupStatus) + } + if val, ok := s.IBMPowerVSCluster.Status.VPCSecurityGroups[name]; ok { + if val.ControllerCreated != nil && *val.ControllerCreated { + resource.ControllerCreated = val.ControllerCreated + } + } + s.IBMPowerVSCluster.Status.VPCSecurityGroups[name] = resource +} + // TransitGateway returns the cluster Transit Gateway information. func (s *PowerVSClusterScope) TransitGateway() *infrav1beta2.TransitGateway { return s.IBMPowerVSCluster.Spec.TransitGateway @@ -1129,6 +1156,382 @@ func (s *PowerVSClusterScope) createVPCSubnet(subnet infrav1beta2.Subnet) (*stri return subnetDetails.ID, nil } +// ReconcileVPCSecurityGroup reconciles VPC security group. +func (s *PowerVSClusterScope) ReconcileVPCSecurityGroup() (bool, error) { + for _, securityGroup := range s.IBMPowerVSCluster.Spec.VPCSecurityGroups { + securityGroupID, securityGroupRuleIDs := s.GetVPCSecurityGroupID(*securityGroup.Name) + if securityGroupID != nil { + if _, _, err := s.IBMVPCClient.GetSecurityGroup(&vpcv1.GetSecurityGroupOptions{ + ID: securityGroupID, + }); err != nil { + return true, err + } + for _, rule := range securityGroupRuleIDs { + if _, _, err := s.IBMVPCClient.GetSecurityGroupRule(&vpcv1.GetSecurityGroupRuleOptions{ + SecurityGroupID: securityGroupID, + ID: rule, + }); err != nil { + return true, err + } + } + continue + } + + securityGroupDet, ruleIDs, err := s.validateVPCSecurityGroup(securityGroup) + if err != nil { + return true, fmt.Errorf("error validating existing security group: %v", err) + } + if securityGroupDet != nil { + s.Logger.Info("Security group already exists", "name", *securityGroupDet.Name) + s.SetVPCSecurityGroupID(*securityGroupDet.Name, infrav1beta2.VPCSecurityGroupStatus{ + ID: securityGroupDet.ID, + RuleIDs: ruleIDs, + ControllerCreated: ptr.To(false), + }) + + continue + } + + securityGroupID, err = s.createVPCSecurityGroup(securityGroup) + if err != nil { + return true, fmt.Errorf("error creating security group: %v", err) + } + ruleIDs, err = s.createVPCSecurityGroupRules(securityGroup, securityGroupID) + if err != nil { + return true, fmt.Errorf("error creating security group rules: %v", err) + } + s.SetVPCSecurityGroupID(*securityGroup.Name, infrav1beta2.VPCSecurityGroupStatus{ + ID: securityGroupID, + RuleIDs: ruleIDs, + ControllerCreated: ptr.To(true), + }) + } + + return false, nil +} + +// createVPCSecurityGroupRule creates a specific rule for a existing security group. +func (s *PowerVSClusterScope) createVPCSecurityGroupRule(securityGroupID, direction, protocol *string, portMin, portMax *int64, remote infrav1beta2.SecurityGroupRuleRemote) (*string, error) { + setRemote := func(remote infrav1beta2.SecurityGroupRuleRemote, remoteOption *vpcv1.SecurityGroupRuleRemotePrototype) error { + switch remote.RemoteType { + case infrav1beta2.SecurityGroupRuleRemoteTypeCIDR: + cidrSubnet, err := s.IBMVPCClient.GetVPCSubnetByName(*remote.CIDRSubnetName) + if err != nil { + return fmt.Errorf("error retrieving vpc subnet by name '%s' for getting cidr block: %v", *remote.CIDRSubnetName, err) + } + if cidrSubnet == nil { + return fmt.Errorf("subnet by name '%s' not exist", *remote.CIDRSubnetName) + } + s.V(3).Info("Creating security group rule", "securityGroupID", *securityGroupID, "direction", *direction, "protocol", *protocol, "cidrBlockSubnet", *remote.CIDRSubnetName, "cidr", *cidrSubnet.Ipv4CIDRBlock) + remoteOption.CIDRBlock = cidrSubnet.Ipv4CIDRBlock + case infrav1beta2.SecurityGroupRuleRemoteTypeIP: + s.V(3).Info("Creating security group rule", "securityGroupID", *securityGroupID, "direction", *direction, "protocol", *protocol, "ip", *remote.IP) + remoteOption.Address = remote.IP + case infrav1beta2.SecurityGroupRuleRemoteTypeSG: + sg, err := s.IBMVPCClient.GetSecurityGroupByName(*remote.SecurityGroupName) + if err != nil { + return fmt.Errorf("error getting security group by name '%s' details to create security group rule: %v", *remote.SecurityGroupName, err) + } + if sg.Name != nil { + return fmt.Errorf("security group by name '%s' not exist", *remote.SecurityGroupName) + } + s.V(3).Info("Creating security group rule", "securityGroupID", *securityGroupID, "direction", *direction, "protocol", *protocol, "securityGroup", *remote.SecurityGroupName, "securityGroupCRN", *sg.CRN) + remoteOption.CRN = sg.CRN + default: + s.V(3).Info("Creating security group rule", "securityGroupID", *securityGroupID, "direction", *direction, "protocol", *protocol, "cidr", "0.0.0.0/0") + remoteOption.CIDRBlock = ptr.To("0.0.0.0/0") + } + + return nil + } + + remoteOption := &vpcv1.SecurityGroupRuleRemotePrototype{} + if err := setRemote(remote, remoteOption); err != nil { + return nil, fmt.Errorf("error while setting remote option to create security group rule: %v", err) + } + + options := vpcv1.CreateSecurityGroupRuleOptions{ + SecurityGroupID: securityGroupID, + } + + options.SetSecurityGroupRulePrototype(&vpcv1.SecurityGroupRulePrototype{ + Direction: direction, + Protocol: protocol, + PortMin: portMin, + PortMax: portMax, + Remote: remoteOption, + }) + + var ruleID *string + ruleIntf, _, err := s.IBMVPCClient.CreateSecurityGroupRule(&options) + if err != nil { + return nil, err + } + + switch reflect.TypeOf(ruleIntf).String() { + case "*vpcv1.SecurityGroupRuleSecurityGroupRuleProtocolAll": + rule := ruleIntf.(*vpcv1.SecurityGroupRuleSecurityGroupRuleProtocolAll) + ruleID = rule.ID + case "*vpcv1.SecurityGroupRuleSecurityGroupRuleProtocolTcpudp": + rule := ruleIntf.(*vpcv1.SecurityGroupRuleSecurityGroupRuleProtocolTcpudp) + ruleID = rule.ID + case "*vpcv1.SecurityGroupRuleSecurityGroupRuleProtocolIcmp": + rule := ruleIntf.(*vpcv1.SecurityGroupRuleSecurityGroupRuleProtocolIcmp) + ruleID = rule.ID + } + + return ruleID, nil +} + +// createVPCSecurityGroupRules creates rules for a security group. +func (s *PowerVSClusterScope) createVPCSecurityGroupRules(securityGroupSpec infrav1beta2.SecurityGroup, securityGroupID *string) ([]*string, error) { + ruleIDs := []*string{} + s.Logger.Info("Creating security group rules") + + for _, rule := range securityGroupSpec.Rules { + var protocol *string + var portMax, portMin *int64 + + direction := ptr.To(string(rule.Direction)) + switch rule.Direction { + case infrav1beta2.SecurityGroupRuleDirectionInbound: + protocol = ptr.To(string(rule.Source.Protocol)) + if rule.Source.PortRange != nil { + portMin = ptr.To(int64(rule.Source.PortRange.MinimumPort)) + portMax = ptr.To(int64(rule.Source.PortRange.MaximumPort)) + } + + for _, remote := range rule.Source.Remotes { + id, err := s.createVPCSecurityGroupRule(securityGroupID, direction, protocol, portMin, portMax, remote) + if err != nil { + return nil, fmt.Errorf("error creating security group rule: %v", err) + } + ruleIDs = append(ruleIDs, id) + } + case infrav1beta2.SecurityGroupRuleDirectionOutbound: + protocol = ptr.To(string(rule.Destination.Protocol)) + if rule.Destination.PortRange != nil { + portMin = ptr.To(int64(rule.Destination.PortRange.MinimumPort)) + portMax = ptr.To(int64(rule.Destination.PortRange.MaximumPort)) + } + + for _, remote := range rule.Destination.Remotes { + id, err := s.createVPCSecurityGroupRule(securityGroupID, direction, protocol, portMin, portMax, remote) + if err != nil { + return nil, fmt.Errorf("error creating security group rule: %v", err) + } + ruleIDs = append(ruleIDs, id) + } + } + } + + return ruleIDs, nil +} + +// createVPCSecurityGroup creates a VPC security group. +func (s *PowerVSClusterScope) createVPCSecurityGroup(spec infrav1beta2.SecurityGroup) (*string, error) { + s.Logger.Info("Creating security group", "name", *spec.Name) + + options := &vpcv1.CreateSecurityGroupOptions{ + VPC: &vpcv1.VPCIdentity{ + ID: s.GetVPCID(), + }, + Name: spec.Name, + ResourceGroup: &vpcv1.ResourceGroupIdentity{ + ID: ptr.To(s.GetResourceGroupID()), + }, + } + + securityGroup, _, err := s.IBMVPCClient.CreateSecurityGroup(options) + if err != nil { + return nil, err + } + // To-Do: Add tags to VPC security group, need to implement the client for "github.com/IBM/platform-services-go-sdk/globaltaggingv1". + + return securityGroup.ID, nil +} + +// validateVPCSecurityGroupRuleRemote compares a specific security group rule's remote with the spec and existing security group rule's remote. +func (s *PowerVSClusterScope) validateVPCSecurityGroupRuleRemote(originalSGRemote *vpcv1.SecurityGroupRuleRemote, expectedSGRemote infrav1beta2.SecurityGroupRuleRemote) (bool, error) { + var match bool + + switch expectedSGRemote.RemoteType { + case infrav1beta2.SecurityGroupRuleRemoteTypeAny: + if originalSGRemote.CIDRBlock != nil && *originalSGRemote.CIDRBlock == "0.0.0.0/0" { + match = true + } + case infrav1beta2.SecurityGroupRuleRemoteTypeIP: + if originalSGRemote.Address != nil && *originalSGRemote.Address == *expectedSGRemote.IP { + match = true + } + case infrav1beta2.SecurityGroupRuleRemoteTypeCIDR: + cidrSubnet, err := s.IBMVPCClient.GetVPCSubnetByName(*expectedSGRemote.CIDRSubnetName) + if err != nil { + return false, fmt.Errorf("error retrieving vpc subnet by name '%s' for getting cidr block: %v", *expectedSGRemote.CIDRSubnetName, err) + } + + if originalSGRemote.CIDRBlock != nil && cidrSubnet != nil && *originalSGRemote.CIDRBlock == *cidrSubnet.Ipv4CIDRBlock { + match = true + } + case infrav1beta2.SecurityGroupRuleRemoteTypeSG: + securityGroup, err := s.IBMVPCClient.GetSecurityGroupByName(*expectedSGRemote.SecurityGroupName) + if err != nil { + return false, fmt.Errorf("error retrieving id for resource group '%s': %v", *expectedSGRemote.SecurityGroupName, err) + } + + if originalSGRemote.CRN != nil && securityGroup.Name != nil && *originalSGRemote.CRN == *securityGroup.CRN { + match = true + } + } + + return match, nil +} + +// validateSecurityGroupRule compares a specific security group's rule with the spec and existing security group's rule. +func (s *PowerVSClusterScope) validateSecurityGroupRule(originalSecurityGroup *vpcv1.SecurityGroup, direction infrav1beta2.SecurityGroupRuleDirection, protocol string, portMin, portMax int64, icmpCode, icmpType *string, remote infrav1beta2.SecurityGroupRuleRemote) (ruleID *string, match bool, err error) { + updateError := func(e error) { + err = fmt.Errorf("error validating security group rule remote: %v", e) + } + + for _, ogRuleIntf := range originalSecurityGroup.Rules { + switch reflect.TypeOf(ogRuleIntf).String() { + case "*vpcv1.SecurityGroupRuleSecurityGroupRuleProtocolAll": + ogRule := ogRuleIntf.(*vpcv1.SecurityGroupRuleSecurityGroupRuleProtocolAll) + ruleID = ogRule.ID + + if *ogRule.Direction == string(direction) && *ogRule.Protocol == protocol { + ogRemote := ogRule.Remote.(*vpcv1.SecurityGroupRuleRemote) + match, err = s.validateVPCSecurityGroupRuleRemote(ogRemote, remote) + if err != nil { + updateError(err) + return nil, false, err + } + } + case "*vpcv1.SecurityGroupRuleSecurityGroupRuleProtocolTcpudp": + ogRule := ogRuleIntf.(*vpcv1.SecurityGroupRuleSecurityGroupRuleProtocolTcpudp) + ruleID = ogRule.ID + + if *ogRule.Direction == string(direction) && *ogRule.Protocol == protocol && *ogRule.PortMax == portMax && *ogRule.PortMin == portMin { + ogRemote := ogRule.Remote.(*vpcv1.SecurityGroupRuleRemote) + match, err = s.validateVPCSecurityGroupRuleRemote(ogRemote, remote) + if err != nil { + updateError(err) + return nil, false, err + } + } + case "*vpcv1.SecurityGroupRuleSecurityGroupRuleProtocolIcmp": + ogRule := ogRuleIntf.(*vpcv1.SecurityGroupRuleSecurityGroupRuleProtocolIcmp) + code, _ := strconv.Atoi(*icmpCode) + iType, _ := strconv.Atoi(*icmpType) + ruleID = ogRule.ID + + if *ogRule.Direction == string(direction) && *ogRule.Protocol == protocol && *ogRule.Code == int64(code) && *ogRule.Type == int64(iType) { + ogRemote := ogRule.Remote.(*vpcv1.SecurityGroupRuleRemote) + match, err = s.validateVPCSecurityGroupRuleRemote(ogRemote, remote) + if err != nil { + updateError(err) + return nil, false, err + } + } + } + if match { + break + } + } + + return ruleID, match, nil +} + +// validateVPCSecurityGroupRules compares a specific security group rules spec with the existing security group's rules. +func (s *PowerVSClusterScope) validateVPCSecurityGroupRules(originalSecurityGroup *vpcv1.SecurityGroup, expectedSecurityGroup infrav1beta2.SecurityGroup) ([]*string, bool, error) { + ruleIDs := []*string{} + for _, expectedRule := range expectedSecurityGroup.Rules { + direction := expectedRule.Direction + var protocol string + var portMin, portMax int64 + + switch direction { + case infrav1beta2.SecurityGroupRuleDirectionInbound: + protocol = string(expectedRule.Source.Protocol) + portMin = int64(expectedRule.Source.PortRange.MinimumPort) + portMax = int64(expectedRule.Source.PortRange.MaximumPort) + icmpCode := expectedRule.Source.ICMPCode + icmpType := expectedRule.Source.ICMPType + + for _, remote := range expectedRule.Source.Remotes { + id, match, err := s.validateSecurityGroupRule(originalSecurityGroup, direction, protocol, portMin, portMax, icmpCode, icmpType, remote) + if err != nil { + return nil, false, fmt.Errorf("error validating security group rule: %v", err) + } + if !match { + return nil, false, nil + } + ruleIDs = append(ruleIDs, id) + } + case infrav1beta2.SecurityGroupRuleDirectionOutbound: + protocol = string(expectedRule.Destination.Protocol) + portMin = int64(expectedRule.Destination.PortRange.MinimumPort) + portMax = int64(expectedRule.Destination.PortRange.MaximumPort) + icmpCode := expectedRule.Destination.ICMPCode + icmpType := expectedRule.Destination.ICMPType + + for _, remote := range expectedRule.Destination.Remotes { + id, match, err := s.validateSecurityGroupRule(originalSecurityGroup, direction, protocol, portMin, portMax, icmpCode, icmpType, remote) + if err != nil { + return nil, false, fmt.Errorf("error validating security group rule: %v", err) + } + if !match { + return nil, false, nil + } + ruleIDs = append(ruleIDs, id) + } + } + } + + return ruleIDs, true, nil +} + +// validateVPCSecurityGroup validates the security group and it's rules provided by user via spec. +func (s *PowerVSClusterScope) validateVPCSecurityGroup(securityGroup infrav1beta2.SecurityGroup) (*vpcv1.SecurityGroup, []*string, error) { + var securityGroupDet *vpcv1.SecurityGroup + var err error + + if securityGroup.Name != nil { + sg, err := s.IBMVPCClient.GetSecurityGroupByName(*securityGroup.Name) + if err != nil { + return nil, nil, err + } + if sg.ID == nil { + return nil, nil, nil + } + securityGroupDet = &sg + } else { + securityGroupDet, _, err = s.IBMVPCClient.GetSecurityGroup(&vpcv1.GetSecurityGroupOptions{ + ID: securityGroup.ID, + }) + if err != nil { + return nil, nil, err + } + if securityGroupDet == nil { + return nil, nil, fmt.Errorf("could not find vpc with provided id '%v'", securityGroup.ID) + } + } + + if *securityGroupDet.VPC.ID != *s.GetVPCID() { + return nil, nil, fmt.Errorf("security group by name exist but not attached to VPC") + } + + ruleIDs, ok, err := s.validateVPCSecurityGroupRules(securityGroupDet, securityGroup) + if err != nil { + return nil, nil, fmt.Errorf("error validating security group rules: %v", err) + } + if !ok { + return nil, nil, fmt.Errorf("security group by name exist but rules are not matching") + } + + return securityGroupDet, ruleIDs, nil +} + // ReconcileTransitGateway reconcile transit gateway. func (s *PowerVSClusterScope) ReconcileTransitGateway() (bool, error) { if s.GetTransitGatewayID() != nil { @@ -1841,6 +2244,34 @@ func (s *PowerVSClusterScope) DeleteLoadBalancer() (bool, error) { return false, nil } +// DeleteVPCSecurityGroup deletes VPC security group. +func (s *PowerVSClusterScope) DeleteVPCSecurityGroup() (bool, error) { + for _, securityGroup := range s.IBMPowerVSCluster.Status.VPCSecurityGroups { + if securityGroup.ID == nil || securityGroup.ControllerCreated == nil || !*securityGroup.ControllerCreated { + continue + } + if _, _, err := s.IBMVPCClient.GetSecurityGroup(&vpcv1.GetSecurityGroupOptions{ + ID: securityGroup.ID, + }); err != nil { + if strings.Contains(err.Error(), "not found") { + s.Info("VPC security group successfully deleted", "ID", securityGroup.ID) + return false, nil + } + return false, fmt.Errorf("error fetching the security group: %w", err) + } + + s.Logger.Info("Deleting VPC security group", "ID", *securityGroup.ID) + options := &vpcv1.DeleteSecurityGroupOptions{ + ID: securityGroup.ID, + } + if _, err := s.IBMVPCClient.DeleteSecurityGroup(options); err != nil { + return false, err + } + return true, nil + } + return false, nil +} + // DeleteVPCSubnet deletes VPC subnet. func (s *PowerVSClusterScope) DeleteVPCSubnet() (bool, error) { for _, subnet := range s.IBMPowerVSCluster.Status.VPCSubnet { diff --git a/config/crd/bases/infrastructure.cluster.x-k8s.io_ibmpowervsclusters.yaml b/config/crd/bases/infrastructure.cluster.x-k8s.io_ibmpowervsclusters.yaml index ad94420e44..bc166ccddf 100644 --- a/config/crd/bases/infrastructure.cluster.x-k8s.io_ibmpowervsclusters.yaml +++ b/config/crd/bases/infrastructure.cluster.x-k8s.io_ibmpowervsclusters.yaml @@ -434,6 +434,348 @@ spec: it is expected to set the region, not setting will result in webhook error. type: string type: object + vpcSecurityGroups: + description: securityGroups to attach it to the VPC resource + items: + description: SecurityGroup defines a VPC Security Group that should + exist or be created within the specified VPC, with the specified + Security Group Rules. + properties: + id: + description: id of the Security Group. + type: string + name: + description: name of the Security Group. + type: string + resourceGroup: + description: resourceGroup of the Security Group. + type: string + rules: + description: rules are the Security Group Rules for the Security + Group. + items: + description: SecurityGroupRule defines a VPC Security Group + Rule for a specified Security Group. + properties: + action: + description: action defines whether to allow or deny traffic + defined by the Security Group Rule. + enum: + - allow + - deny + type: string + destination: + description: |- + destination is a SecurityGroupRulePrototype which defines the destination of outbound traffic for the Security Group Rule. + Only used when direction is SecurityGroupRuleDirectionOutbound. + properties: + icmpCode: + description: |- + icmpCode is the ICMP code for the Rule. + Only used when Protocol is SecurityGroupProtocolICMP. + type: string + icmpType: + description: |- + icmpType is the ICMP type for the Rule. + Only used when Protocol is SecurityGroupProtocolICMP. + type: string + portRange: + description: portRange is a range of ports allowed + for the Rule's remote. + properties: + maximumPort: + description: maximumPort is the inclusive upper + range of ports. + maximum: 65535 + minimum: 1 + type: integer + minimumPort: + description: minimumPort is the inclusive lower + range of ports. + maximum: 65535 + minimum: 1 + type: integer + type: object + x-kubernetes-validations: + - message: maximum port must be greater than or equal + to minimum port + rule: self.maximumPort >= self.minimumPort + protocol: + description: protocol defines the traffic protocol + used for the Security Group Rule. + enum: + - all + - icmp + - tcp + - udp + type: string + remotes: + description: |- + remotes is a set of SecurityGroupRuleRemote's that define the traffic allowed by the Rule's remote. + Specifying multiple SecurityGroupRuleRemote's creates a unique Security Group Rule with the shared Protocol, PortRange, etc. + This allows for easier management of Security Group Rule's for sets of CIDR's, IP's, etc. + items: + description: |- + SecurityGroupRuleRemote defines a VPC Security Group Rule's remote details. + The type of remote defines the additional remote details where are used for defining the remote. + properties: + cidrSubnetName: + description: |- + cidrSubnetName is the name of the VPC Subnet to retrieve the CIDR from, to use for the remote's destination/source. + Only used when remoteType is SecurityGroupRuleRemoteTypeCIDR. + type: string + ip: + description: |- + ip is the IP to use for the remote's destination/source. + Only used when remoteType is SecurityGroupRuleRemoteTypeIP. + type: string + remoteType: + description: remoteType defines the type of + filter to define for the remote's destination/source. + enum: + - any + - cidr + - ip + - sg + type: string + securityGroupName: + description: |- + securityGroupName is the name of the VPC Security Group to use for the remote's destination/source. + Only used when remoteType is SecurityGroupRuleRemoteTypeSG + type: string + required: + - remoteType + type: object + x-kubernetes-validations: + - message: cidrSubnetName, ip, and securityGroupName + are not valid for SecurityGroupRuleRemoteTypeAny + remoteType + rule: 'self.remoteType == ''any'' ? (!has(self.cidrSubnetName) + && !has(self.ip) && !has(self.securityGroupName)) + : true' + - message: only cidrSubnetName is valid for SecurityGroupRuleRemoteTypeCIDR + remoteType + rule: 'self.remoteType == ''cidr'' ? (has(self.cidrSubnetName) + && !has(self.ip) && !has(self.securityGroupName)) + : true' + - message: only ip is valid for SecurityGroupRuleRemoteTypeIP + remoteType + rule: 'self.remoteType == ''ip'' ? (has(self.ip) + && !has(self.cidrSubnetName) && !has(self.securityGroupName)) + : true' + - message: only securityGroupName is valid for SecurityGroupRuleRemoteTypeSG + remoteType + rule: 'self.remoteType == ''sg'' ? (has(self.securityGroupName) + && !has(self.cidrSubnetName) && !has(self.ip)) + : true' + type: array + required: + - protocol + - remotes + type: object + x-kubernetes-validations: + - message: icmpCode and icmpType are only supported for + SecurityGroupRuleProtocolIcmp protocol + rule: 'self.protocol != ''icmp'' ? (!has(self.icmpCode) + && !has(self.icmpType)) : true' + - message: portRange is not valid for SecurityGroupRuleProtocolAll + protocol + rule: 'self.protocol == ''all'' ? !has(self.portRange) + : true' + - message: portRange is not valid for SecurityGroupRuleProtocolIcmp + protocol + rule: 'self.protocol == ''icmp'' ? !has(self.portRange) + : true' + direction: + description: direction defines whether the traffic is + inbound or outbound for the Security Group Rule. + enum: + - inbound + - outbound + type: string + securityGroupID: + description: securityGroupID is the ID of the Security + Group for the Security Group Rule. + type: string + source: + description: |- + source is a SecurityGroupRulePrototype which defines the source of inbound traffic for the Security Group Rule. + Only used when direction is SecurityGroupRuleDirectionInbound. + properties: + icmpCode: + description: |- + icmpCode is the ICMP code for the Rule. + Only used when Protocol is SecurityGroupProtocolICMP. + type: string + icmpType: + description: |- + icmpType is the ICMP type for the Rule. + Only used when Protocol is SecurityGroupProtocolICMP. + type: string + portRange: + description: portRange is a range of ports allowed + for the Rule's remote. + properties: + maximumPort: + description: maximumPort is the inclusive upper + range of ports. + maximum: 65535 + minimum: 1 + type: integer + minimumPort: + description: minimumPort is the inclusive lower + range of ports. + maximum: 65535 + minimum: 1 + type: integer + type: object + x-kubernetes-validations: + - message: maximum port must be greater than or equal + to minimum port + rule: self.maximumPort >= self.minimumPort + protocol: + description: protocol defines the traffic protocol + used for the Security Group Rule. + enum: + - all + - icmp + - tcp + - udp + type: string + remotes: + description: |- + remotes is a set of SecurityGroupRuleRemote's that define the traffic allowed by the Rule's remote. + Specifying multiple SecurityGroupRuleRemote's creates a unique Security Group Rule with the shared Protocol, PortRange, etc. + This allows for easier management of Security Group Rule's for sets of CIDR's, IP's, etc. + items: + description: |- + SecurityGroupRuleRemote defines a VPC Security Group Rule's remote details. + The type of remote defines the additional remote details where are used for defining the remote. + properties: + cidrSubnetName: + description: |- + cidrSubnetName is the name of the VPC Subnet to retrieve the CIDR from, to use for the remote's destination/source. + Only used when remoteType is SecurityGroupRuleRemoteTypeCIDR. + type: string + ip: + description: |- + ip is the IP to use for the remote's destination/source. + Only used when remoteType is SecurityGroupRuleRemoteTypeIP. + type: string + remoteType: + description: remoteType defines the type of + filter to define for the remote's destination/source. + enum: + - any + - cidr + - ip + - sg + type: string + securityGroupName: + description: |- + securityGroupName is the name of the VPC Security Group to use for the remote's destination/source. + Only used when remoteType is SecurityGroupRuleRemoteTypeSG + type: string + required: + - remoteType + type: object + x-kubernetes-validations: + - message: cidrSubnetName, ip, and securityGroupName + are not valid for SecurityGroupRuleRemoteTypeAny + remoteType + rule: 'self.remoteType == ''any'' ? (!has(self.cidrSubnetName) + && !has(self.ip) && !has(self.securityGroupName)) + : true' + - message: only cidrSubnetName is valid for SecurityGroupRuleRemoteTypeCIDR + remoteType + rule: 'self.remoteType == ''cidr'' ? (has(self.cidrSubnetName) + && !has(self.ip) && !has(self.securityGroupName)) + : true' + - message: only ip is valid for SecurityGroupRuleRemoteTypeIP + remoteType + rule: 'self.remoteType == ''ip'' ? (has(self.ip) + && !has(self.cidrSubnetName) && !has(self.securityGroupName)) + : true' + - message: only securityGroupName is valid for SecurityGroupRuleRemoteTypeSG + remoteType + rule: 'self.remoteType == ''sg'' ? (has(self.securityGroupName) + && !has(self.cidrSubnetName) && !has(self.ip)) + : true' + type: array + required: + - protocol + - remotes + type: object + x-kubernetes-validations: + - message: icmpCode and icmpType are only supported for + SecurityGroupRuleProtocolIcmp protocol + rule: 'self.protocol != ''icmp'' ? (!has(self.icmpCode) + && !has(self.icmpType)) : true' + - message: portRange is not valid for SecurityGroupRuleProtocolAll + protocol + rule: 'self.protocol == ''all'' ? !has(self.portRange) + : true' + - message: portRange is not valid for SecurityGroupRuleProtocolIcmp + protocol + rule: 'self.protocol == ''icmp'' ? !has(self.portRange) + : true' + required: + - action + - direction + type: object + x-kubernetes-validations: + - message: both destination and source cannot be provided + rule: (has(self.destination) && !has(self.source)) || (!has(self.destination) + && has(self.source)) + - message: source must be set for SecurityGroupRuleDirectionInbound + direction + rule: 'self.direction == ''inbound'' ? has(self.source) + : true' + - message: destination is not valid for SecurityGroupRuleDirectionInbound + direction + rule: 'self.direction == ''inbound'' ? !has(self.destination) + : true' + - message: destination must be set for SecurityGroupRuleDirectionOutbound + direction + rule: 'self.direction == ''outbound'' ? has(self.destination) + : true' + - message: source is not valid for SecurityGroupRuleDirectionOutbound + direction + rule: 'self.direction == ''outbound'' ? !has(self.source) + : true' + type: array + tags: + description: tags are tags to add to the Security Group. + items: + type: string + type: array + vpc: + description: vpc is the IBM Cloud VPC for the Security Group. + properties: + id: + description: id of resource. + maxLength: 64 + minLength: 1 + pattern: ^[-0-9a-z_]+$ + type: string + name: + description: name of resource. + maxLength: 63 + minLength: 1 + pattern: ^([a-z]|[a-z][-a-z0-9]*[a-z0-9])$ + type: string + region: + description: |- + region of IBM Cloud VPC. + when powervs.cluster.x-k8s.io/create-infra=true annotation is set on IBMPowerVSCluster resource, + it is expected to set the region, not setting will result in webhook error. + type: string + type: object + type: object + x-kubernetes-validations: + - message: either an id or name must be specified + rule: has(self.id) || has(self.name) + type: array vpcSubnets: description: |- vpcSubnets contains information about IBM Cloud VPC Subnet resources. @@ -634,6 +976,29 @@ spec: description: id represents the id of the resource. type: string type: object + vpcSecurityGroups: + additionalProperties: + description: VPCSecurityGroupStatus defines a vpc security group + resource status with its id and respective rule's ids. + properties: + controllerCreated: + default: false + description: controllerCreated indicates whether the resource + is created by the controller. + type: boolean + id: + description: id represents the id of the resource. + type: string + rules: + description: rules contains the id of rules created under the + security group + items: + type: string + type: array + type: object + description: vpcSecurityGroups is reference to IBM Cloud VPC security + group. + type: object vpcSubnet: additionalProperties: description: ResourceReference identifies a resource with id. diff --git a/config/crd/bases/infrastructure.cluster.x-k8s.io_ibmpowervsclustertemplates.yaml b/config/crd/bases/infrastructure.cluster.x-k8s.io_ibmpowervsclustertemplates.yaml index fa43d35190..7a96b47773 100644 --- a/config/crd/bases/infrastructure.cluster.x-k8s.io_ibmpowervsclustertemplates.yaml +++ b/config/crd/bases/infrastructure.cluster.x-k8s.io_ibmpowervsclustertemplates.yaml @@ -465,6 +465,354 @@ spec: it is expected to set the region, not setting will result in webhook error. type: string type: object + vpcSecurityGroups: + description: securityGroups to attach it to the VPC resource + items: + description: SecurityGroup defines a VPC Security Group + that should exist or be created within the specified VPC, + with the specified Security Group Rules. + properties: + id: + description: id of the Security Group. + type: string + name: + description: name of the Security Group. + type: string + resourceGroup: + description: resourceGroup of the Security Group. + type: string + rules: + description: rules are the Security Group Rules for + the Security Group. + items: + description: SecurityGroupRule defines a VPC Security + Group Rule for a specified Security Group. + properties: + action: + description: action defines whether to allow or + deny traffic defined by the Security Group Rule. + enum: + - allow + - deny + type: string + destination: + description: |- + destination is a SecurityGroupRulePrototype which defines the destination of outbound traffic for the Security Group Rule. + Only used when direction is SecurityGroupRuleDirectionOutbound. + properties: + icmpCode: + description: |- + icmpCode is the ICMP code for the Rule. + Only used when Protocol is SecurityGroupProtocolICMP. + type: string + icmpType: + description: |- + icmpType is the ICMP type for the Rule. + Only used when Protocol is SecurityGroupProtocolICMP. + type: string + portRange: + description: portRange is a range of ports + allowed for the Rule's remote. + properties: + maximumPort: + description: maximumPort is the inclusive + upper range of ports. + maximum: 65535 + minimum: 1 + type: integer + minimumPort: + description: minimumPort is the inclusive + lower range of ports. + maximum: 65535 + minimum: 1 + type: integer + type: object + x-kubernetes-validations: + - message: maximum port must be greater than + or equal to minimum port + rule: self.maximumPort >= self.minimumPort + protocol: + description: protocol defines the traffic + protocol used for the Security Group Rule. + enum: + - all + - icmp + - tcp + - udp + type: string + remotes: + description: |- + remotes is a set of SecurityGroupRuleRemote's that define the traffic allowed by the Rule's remote. + Specifying multiple SecurityGroupRuleRemote's creates a unique Security Group Rule with the shared Protocol, PortRange, etc. + This allows for easier management of Security Group Rule's for sets of CIDR's, IP's, etc. + items: + description: |- + SecurityGroupRuleRemote defines a VPC Security Group Rule's remote details. + The type of remote defines the additional remote details where are used for defining the remote. + properties: + cidrSubnetName: + description: |- + cidrSubnetName is the name of the VPC Subnet to retrieve the CIDR from, to use for the remote's destination/source. + Only used when remoteType is SecurityGroupRuleRemoteTypeCIDR. + type: string + ip: + description: |- + ip is the IP to use for the remote's destination/source. + Only used when remoteType is SecurityGroupRuleRemoteTypeIP. + type: string + remoteType: + description: remoteType defines the + type of filter to define for the remote's + destination/source. + enum: + - any + - cidr + - ip + - sg + type: string + securityGroupName: + description: |- + securityGroupName is the name of the VPC Security Group to use for the remote's destination/source. + Only used when remoteType is SecurityGroupRuleRemoteTypeSG + type: string + required: + - remoteType + type: object + x-kubernetes-validations: + - message: cidrSubnetName, ip, and securityGroupName + are not valid for SecurityGroupRuleRemoteTypeAny + remoteType + rule: 'self.remoteType == ''any'' ? (!has(self.cidrSubnetName) + && !has(self.ip) && !has(self.securityGroupName)) + : true' + - message: only cidrSubnetName is valid + for SecurityGroupRuleRemoteTypeCIDR + remoteType + rule: 'self.remoteType == ''cidr'' ? (has(self.cidrSubnetName) + && !has(self.ip) && !has(self.securityGroupName)) + : true' + - message: only ip is valid for SecurityGroupRuleRemoteTypeIP + remoteType + rule: 'self.remoteType == ''ip'' ? (has(self.ip) + && !has(self.cidrSubnetName) && !has(self.securityGroupName)) + : true' + - message: only securityGroupName is valid + for SecurityGroupRuleRemoteTypeSG remoteType + rule: 'self.remoteType == ''sg'' ? (has(self.securityGroupName) + && !has(self.cidrSubnetName) && !has(self.ip)) + : true' + type: array + required: + - protocol + - remotes + type: object + x-kubernetes-validations: + - message: icmpCode and icmpType are only supported + for SecurityGroupRuleProtocolIcmp protocol + rule: 'self.protocol != ''icmp'' ? (!has(self.icmpCode) + && !has(self.icmpType)) : true' + - message: portRange is not valid for SecurityGroupRuleProtocolAll + protocol + rule: 'self.protocol == ''all'' ? !has(self.portRange) + : true' + - message: portRange is not valid for SecurityGroupRuleProtocolIcmp + protocol + rule: 'self.protocol == ''icmp'' ? !has(self.portRange) + : true' + direction: + description: direction defines whether the traffic + is inbound or outbound for the Security Group + Rule. + enum: + - inbound + - outbound + type: string + securityGroupID: + description: securityGroupID is the ID of the + Security Group for the Security Group Rule. + type: string + source: + description: |- + source is a SecurityGroupRulePrototype which defines the source of inbound traffic for the Security Group Rule. + Only used when direction is SecurityGroupRuleDirectionInbound. + properties: + icmpCode: + description: |- + icmpCode is the ICMP code for the Rule. + Only used when Protocol is SecurityGroupProtocolICMP. + type: string + icmpType: + description: |- + icmpType is the ICMP type for the Rule. + Only used when Protocol is SecurityGroupProtocolICMP. + type: string + portRange: + description: portRange is a range of ports + allowed for the Rule's remote. + properties: + maximumPort: + description: maximumPort is the inclusive + upper range of ports. + maximum: 65535 + minimum: 1 + type: integer + minimumPort: + description: minimumPort is the inclusive + lower range of ports. + maximum: 65535 + minimum: 1 + type: integer + type: object + x-kubernetes-validations: + - message: maximum port must be greater than + or equal to minimum port + rule: self.maximumPort >= self.minimumPort + protocol: + description: protocol defines the traffic + protocol used for the Security Group Rule. + enum: + - all + - icmp + - tcp + - udp + type: string + remotes: + description: |- + remotes is a set of SecurityGroupRuleRemote's that define the traffic allowed by the Rule's remote. + Specifying multiple SecurityGroupRuleRemote's creates a unique Security Group Rule with the shared Protocol, PortRange, etc. + This allows for easier management of Security Group Rule's for sets of CIDR's, IP's, etc. + items: + description: |- + SecurityGroupRuleRemote defines a VPC Security Group Rule's remote details. + The type of remote defines the additional remote details where are used for defining the remote. + properties: + cidrSubnetName: + description: |- + cidrSubnetName is the name of the VPC Subnet to retrieve the CIDR from, to use for the remote's destination/source. + Only used when remoteType is SecurityGroupRuleRemoteTypeCIDR. + type: string + ip: + description: |- + ip is the IP to use for the remote's destination/source. + Only used when remoteType is SecurityGroupRuleRemoteTypeIP. + type: string + remoteType: + description: remoteType defines the + type of filter to define for the remote's + destination/source. + enum: + - any + - cidr + - ip + - sg + type: string + securityGroupName: + description: |- + securityGroupName is the name of the VPC Security Group to use for the remote's destination/source. + Only used when remoteType is SecurityGroupRuleRemoteTypeSG + type: string + required: + - remoteType + type: object + x-kubernetes-validations: + - message: cidrSubnetName, ip, and securityGroupName + are not valid for SecurityGroupRuleRemoteTypeAny + remoteType + rule: 'self.remoteType == ''any'' ? (!has(self.cidrSubnetName) + && !has(self.ip) && !has(self.securityGroupName)) + : true' + - message: only cidrSubnetName is valid + for SecurityGroupRuleRemoteTypeCIDR + remoteType + rule: 'self.remoteType == ''cidr'' ? (has(self.cidrSubnetName) + && !has(self.ip) && !has(self.securityGroupName)) + : true' + - message: only ip is valid for SecurityGroupRuleRemoteTypeIP + remoteType + rule: 'self.remoteType == ''ip'' ? (has(self.ip) + && !has(self.cidrSubnetName) && !has(self.securityGroupName)) + : true' + - message: only securityGroupName is valid + for SecurityGroupRuleRemoteTypeSG remoteType + rule: 'self.remoteType == ''sg'' ? (has(self.securityGroupName) + && !has(self.cidrSubnetName) && !has(self.ip)) + : true' + type: array + required: + - protocol + - remotes + type: object + x-kubernetes-validations: + - message: icmpCode and icmpType are only supported + for SecurityGroupRuleProtocolIcmp protocol + rule: 'self.protocol != ''icmp'' ? (!has(self.icmpCode) + && !has(self.icmpType)) : true' + - message: portRange is not valid for SecurityGroupRuleProtocolAll + protocol + rule: 'self.protocol == ''all'' ? !has(self.portRange) + : true' + - message: portRange is not valid for SecurityGroupRuleProtocolIcmp + protocol + rule: 'self.protocol == ''icmp'' ? !has(self.portRange) + : true' + required: + - action + - direction + type: object + x-kubernetes-validations: + - message: both destination and source cannot be provided + rule: (has(self.destination) && !has(self.source)) + || (!has(self.destination) && has(self.source)) + - message: source must be set for SecurityGroupRuleDirectionInbound + direction + rule: 'self.direction == ''inbound'' ? has(self.source) + : true' + - message: destination is not valid for SecurityGroupRuleDirectionInbound + direction + rule: 'self.direction == ''inbound'' ? !has(self.destination) + : true' + - message: destination must be set for SecurityGroupRuleDirectionOutbound + direction + rule: 'self.direction == ''outbound'' ? has(self.destination) + : true' + - message: source is not valid for SecurityGroupRuleDirectionOutbound + direction + rule: 'self.direction == ''outbound'' ? !has(self.source) + : true' + type: array + tags: + description: tags are tags to add to the Security Group. + items: + type: string + type: array + vpc: + description: vpc is the IBM Cloud VPC for the Security + Group. + properties: + id: + description: id of resource. + maxLength: 64 + minLength: 1 + pattern: ^[-0-9a-z_]+$ + type: string + name: + description: name of resource. + maxLength: 63 + minLength: 1 + pattern: ^([a-z]|[a-z][-a-z0-9]*[a-z0-9])$ + type: string + region: + description: |- + region of IBM Cloud VPC. + when powervs.cluster.x-k8s.io/create-infra=true annotation is set on IBMPowerVSCluster resource, + it is expected to set the region, not setting will result in webhook error. + type: string + type: object + type: object + x-kubernetes-validations: + - message: either an id or name must be specified + rule: has(self.id) || has(self.name) + type: array vpcSubnets: description: |- vpcSubnets contains information about IBM Cloud VPC Subnet resources. diff --git a/controllers/ibmpowervscluster_controller.go b/controllers/ibmpowervscluster_controller.go index 584382b9d3..1804900150 100644 --- a/controllers/ibmpowervscluster_controller.go +++ b/controllers/ibmpowervscluster_controller.go @@ -189,6 +189,18 @@ func (r *IBMPowerVSClusterReconciler) reconcile(clusterScope *scope.PowerVSClust } conditions.MarkTrue(powerVSCluster, infrav1beta2.VPCSubnetReadyCondition) + // reconcile VPC security group + clusterScope.Info("Reconciling VPC security group") + if requeue, err := clusterScope.ReconcileVPCSecurityGroup(); err != nil { + clusterScope.Error(err, "failed to reconcile VPC security group") + conditions.MarkFalse(powerVSCluster, infrav1beta2.VPCSecurityGroupReadyCondition, infrav1beta2.VPCSecurityGroupReconciliationFailedReason, capiv1beta1.ConditionSeverityError, err.Error()) + return reconcile.Result{}, err + } else if requeue { + clusterScope.Info("VPC security group creation is pending, requeuing") + return reconcile.Result{RequeueAfter: 15 * time.Second}, nil + } + conditions.MarkTrue(powerVSCluster, infrav1beta2.VPCSecurityGroupReadyCondition) + // reconcile Transit Gateway clusterScope.Info("Reconciling Transit Gateway") if requeue, err := clusterScope.ReconcileTransitGateway(); err != nil { @@ -279,6 +291,14 @@ func (r *IBMPowerVSClusterReconciler) reconcileDelete(ctx context.Context, clust return reconcile.Result{RequeueAfter: 1 * time.Minute}, nil } + clusterScope.Info("Deleting VPC security group") + if requeue, err := clusterScope.DeleteVPCSecurityGroup(); err != nil { + allErrs = append(allErrs, errors.Wrapf(err, "failed to delete VPC subnet")) + } else if requeue { + clusterScope.Info("VPC subnet deletion is pending, requeuing") + return reconcile.Result{RequeueAfter: 15 * time.Second}, nil + } + clusterScope.Info("Deleting VPC subnet") if requeue, err := clusterScope.DeleteVPCSubnet(); err != nil { allErrs = append(allErrs, errors.Wrapf(err, "failed to delete VPC subnet")) diff --git a/pkg/cloud/services/vpc/mock/vpc_generated.go b/pkg/cloud/services/vpc/mock/vpc_generated.go index 370da61389..2d30e29aae 100644 --- a/pkg/cloud/services/vpc/mock/vpc_generated.go +++ b/pkg/cloud/services/vpc/mock/vpc_generated.go @@ -119,6 +119,22 @@ func (mr *MockVpcMockRecorder) CreatePublicGateway(options any) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreatePublicGateway", reflect.TypeOf((*MockVpc)(nil).CreatePublicGateway), options) } +// CreateSecurityGroup mocks base method. +func (m *MockVpc) CreateSecurityGroup(options *vpcv1.CreateSecurityGroupOptions) (*vpcv1.SecurityGroup, *core.DetailedResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CreateSecurityGroup", options) + ret0, _ := ret[0].(*vpcv1.SecurityGroup) + ret1, _ := ret[1].(*core.DetailedResponse) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 +} + +// CreateSecurityGroup indicates an expected call of CreateSecurityGroup. +func (mr *MockVpcMockRecorder) CreateSecurityGroup(options any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateSecurityGroup", reflect.TypeOf((*MockVpc)(nil).CreateSecurityGroup), options) +} + // CreateSecurityGroupRule mocks base method. func (m *MockVpc) CreateSecurityGroupRule(options *vpcv1.CreateSecurityGroupRuleOptions) (vpcv1.SecurityGroupRuleIntf, *core.DetailedResponse, error) { m.ctrl.T.Helper() @@ -227,6 +243,21 @@ func (mr *MockVpcMockRecorder) DeletePublicGateway(options any) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePublicGateway", reflect.TypeOf((*MockVpc)(nil).DeletePublicGateway), options) } +// DeleteSecurityGroup mocks base method. +func (m *MockVpc) DeleteSecurityGroup(options *vpcv1.DeleteSecurityGroupOptions) (*core.DetailedResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DeleteSecurityGroup", options) + ret0, _ := ret[0].(*core.DetailedResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// DeleteSecurityGroup indicates an expected call of DeleteSecurityGroup. +func (mr *MockVpcMockRecorder) DeleteSecurityGroup(options any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteSecurityGroup", reflect.TypeOf((*MockVpc)(nil).DeleteSecurityGroup), options) +} + // DeleteSubnet mocks base method. func (m *MockVpc) DeleteSubnet(options *vpcv1.DeleteSubnetOptions) (*core.DetailedResponse, error) { m.ctrl.T.Helper() @@ -320,6 +351,53 @@ func (mr *MockVpcMockRecorder) GetLoadBalancerByName(loadBalancerName any) *gomo return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetLoadBalancerByName", reflect.TypeOf((*MockVpc)(nil).GetLoadBalancerByName), loadBalancerName) } +// GetSecurityGroup mocks base method. +func (m *MockVpc) GetSecurityGroup(options *vpcv1.GetSecurityGroupOptions) (*vpcv1.SecurityGroup, *core.DetailedResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetSecurityGroup", options) + ret0, _ := ret[0].(*vpcv1.SecurityGroup) + ret1, _ := ret[1].(*core.DetailedResponse) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 +} + +// GetSecurityGroup indicates an expected call of GetSecurityGroup. +func (mr *MockVpcMockRecorder) GetSecurityGroup(options any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSecurityGroup", reflect.TypeOf((*MockVpc)(nil).GetSecurityGroup), options) +} + +// GetSecurityGroupByName mocks base method. +func (m *MockVpc) GetSecurityGroupByName(name string) (vpcv1.SecurityGroup, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetSecurityGroupByName", name) + ret0, _ := ret[0].(vpcv1.SecurityGroup) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetSecurityGroupByName indicates an expected call of GetSecurityGroupByName. +func (mr *MockVpcMockRecorder) GetSecurityGroupByName(name any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSecurityGroupByName", reflect.TypeOf((*MockVpc)(nil).GetSecurityGroupByName), name) +} + +// GetSecurityGroupRule mocks base method. +func (m *MockVpc) GetSecurityGroupRule(options *vpcv1.GetSecurityGroupRuleOptions) (vpcv1.SecurityGroupRuleIntf, *core.DetailedResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetSecurityGroupRule", options) + ret0, _ := ret[0].(vpcv1.SecurityGroupRuleIntf) + ret1, _ := ret[1].(*core.DetailedResponse) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 +} + +// GetSecurityGroupRule indicates an expected call of GetSecurityGroupRule. +func (mr *MockVpcMockRecorder) GetSecurityGroupRule(options any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSecurityGroupRule", reflect.TypeOf((*MockVpc)(nil).GetSecurityGroupRule), options) +} + // GetSubnet mocks base method. func (m *MockVpc) GetSubnet(arg0 *vpcv1.GetSubnetOptions) (*vpcv1.Subnet, *core.DetailedResponse, error) { m.ctrl.T.Helper() @@ -493,6 +571,22 @@ func (mr *MockVpcMockRecorder) ListLoadBalancers(options any) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListLoadBalancers", reflect.TypeOf((*MockVpc)(nil).ListLoadBalancers), options) } +// ListSecurityGroups mocks base method. +func (m *MockVpc) ListSecurityGroups(options *vpcv1.ListSecurityGroupsOptions) (*vpcv1.SecurityGroupCollection, *core.DetailedResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ListSecurityGroups", options) + ret0, _ := ret[0].(*vpcv1.SecurityGroupCollection) + ret1, _ := ret[1].(*core.DetailedResponse) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 +} + +// ListSecurityGroups indicates an expected call of ListSecurityGroups. +func (mr *MockVpcMockRecorder) ListSecurityGroups(options any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListSecurityGroups", reflect.TypeOf((*MockVpc)(nil).ListSecurityGroups), options) +} + // ListSubnets mocks base method. func (m *MockVpc) ListSubnets(options *vpcv1.ListSubnetsOptions) (*vpcv1.SubnetCollection, *core.DetailedResponse, error) { m.ctrl.T.Helper() diff --git a/pkg/cloud/services/vpc/service.go b/pkg/cloud/services/vpc/service.go index 69d025b58c..a07ef44398 100644 --- a/pkg/cloud/services/vpc/service.go +++ b/pkg/cloud/services/vpc/service.go @@ -18,11 +18,11 @@ package vpc import ( "fmt" + "sigs.k8s.io/cluster-api-provider-ibmcloud/pkg/cloud/services/authenticator" "github.com/IBM/go-sdk-core/v5/core" "github.com/IBM/vpc-go-sdk/vpcv1" - "sigs.k8s.io/cluster-api-provider-ibmcloud/pkg/cloud/services/authenticator" "sigs.k8s.io/cluster-api-provider-ibmcloud/pkg/cloud/services/utils" ) @@ -337,6 +337,61 @@ func (s *Service) GetSubnetAddrPrefix(vpcID, zone string) (string, error) { return "", fmt.Errorf("not found a valid CIDR for VPC %s in zone %s", vpcID, zone) } +// CreateSecurityGroup creates a new security group. +func (s *Service) CreateSecurityGroup(options *vpcv1.CreateSecurityGroupOptions) (*vpcv1.SecurityGroup, *core.DetailedResponse, error) { + return s.vpcService.CreateSecurityGroup(options) +} + +// DeleteSecurityGroup deletes the security group passed. +func (s *Service) DeleteSecurityGroup(options *vpcv1.DeleteSecurityGroupOptions) (*core.DetailedResponse, error) { + return s.vpcService.DeleteSecurityGroup(options) +} + +// ListSecurityGroups lists security group. +func (s *Service) ListSecurityGroups(options *vpcv1.ListSecurityGroupsOptions) (*vpcv1.SecurityGroupCollection, *core.DetailedResponse, error) { + return s.vpcService.ListSecurityGroups(options) +} + +// GetSecurityGroup gets a specific security group by id. +func (s *Service) GetSecurityGroup(options *vpcv1.GetSecurityGroupOptions) (*vpcv1.SecurityGroup, *core.DetailedResponse, error) { + return s.vpcService.GetSecurityGroup(options) +} + +// GetSecurityGroupByName gets a specific security group by name. +func (s *Service) GetSecurityGroupByName(name string) (vpcv1.SecurityGroup, error) { + var securityGroup vpcv1.SecurityGroup + + securityGroupPager, err := s.vpcService.NewSecurityGroupsPager(&vpcv1.ListSecurityGroupsOptions{}) + if err != nil { + return vpcv1.SecurityGroup{}, fmt.Errorf("error listing security group: %v", err) + } + + for { + if !securityGroupPager.HasNext() { + break + } + + securityGroups, err := securityGroupPager.GetNext() + if err != nil { + return vpcv1.SecurityGroup{}, fmt.Errorf("error retrieving next page of security groups: %v", err) + } + + for _, sg := range securityGroups { + if *sg.Name == name { + securityGroup = sg + break + } + } + } + + return securityGroup, nil +} + +// GetSecurityGroupRule gets a specific security group rule. +func (s *Service) GetSecurityGroupRule(options *vpcv1.GetSecurityGroupRuleOptions) (vpcv1.SecurityGroupRuleIntf, *core.DetailedResponse, error) { + return s.vpcService.GetSecurityGroupRule(options) +} + // NewService returns a new VPC Service. func NewService(svcEndpoint string) (Vpc, error) { service := &Service{} diff --git a/pkg/cloud/services/vpc/vpc.go b/pkg/cloud/services/vpc/vpc.go index f6ebffbefd..63cb916bdd 100644 --- a/pkg/cloud/services/vpc/vpc.go +++ b/pkg/cloud/services/vpc/vpc.go @@ -59,4 +59,10 @@ type Vpc interface { GetVPCSubnetByName(subnetName string) (*vpcv1.Subnet, error) GetLoadBalancerByName(loadBalancerName string) (*vpcv1.LoadBalancer, error) GetSubnetAddrPrefix(vpcID, zone string) (string, error) + CreateSecurityGroup(options *vpcv1.CreateSecurityGroupOptions) (*vpcv1.SecurityGroup, *core.DetailedResponse, error) + DeleteSecurityGroup(options *vpcv1.DeleteSecurityGroupOptions) (*core.DetailedResponse, error) + ListSecurityGroups(options *vpcv1.ListSecurityGroupsOptions) (*vpcv1.SecurityGroupCollection, *core.DetailedResponse, error) + GetSecurityGroup(options *vpcv1.GetSecurityGroupOptions) (*vpcv1.SecurityGroup, *core.DetailedResponse, error) + GetSecurityGroupByName(name string) (vpcv1.SecurityGroup, error) + GetSecurityGroupRule(options *vpcv1.GetSecurityGroupRuleOptions) (vpcv1.SecurityGroupRuleIntf, *core.DetailedResponse, error) }