-
Notifications
You must be signed in to change notification settings - Fork 15
/
resource_nat.go
234 lines (188 loc) · 6.99 KB
/
resource_nat.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package ddcloud
import (
"fmt"
"log"
"strconv"
"strings"
"time"
"github.com/DimensionDataResearch/dd-cloud-compute-terraform/retry"
"github.com/DimensionDataResearch/go-dd-cloud-compute/compute"
"github.com/hashicorp/terraform/helper/schema"
)
const (
resourceKeyNATNetworkDomainID = "networkdomain"
resourceKeyNATPrivateAddress = "private_ipv4"
resourceKeyNATPublicAddress = "public_ipv4"
resourceCreateTimeoutNAT = 30 * time.Minute
resourceUpdateTimeoutNAT = 10 * time.Minute
resourceDeleteTimeoutNAT = 15 * time.Minute
)
func resourceNAT() *schema.Resource {
return &schema.Resource{
Exists: resourceNATExists,
Create: resourceNATCreate,
Read: resourceNATRead,
Update: resourceNATUpdate,
Delete: resourceNATDelete,
Schema: map[string]*schema.Schema{
resourceKeyNATNetworkDomainID: &schema.Schema{
Type: schema.TypeString,
ForceNew: true,
Required: true,
Description: "The Id of the network domain that the NAT rule applies to.",
},
resourceKeyNATPrivateAddress: &schema.Schema{
Type: schema.TypeString,
ForceNew: true,
Required: true,
Description: "The private (internal) IPv4 address.",
},
resourceKeyNATPublicAddress: &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
Default: nil,
Description: "The public (external) IPv4 address.",
},
},
}
}
// Check if a NAT resource exists.
func resourceNATExists(data *schema.ResourceData, provider interface{}) (bool, error) {
id := data.Id()
log.Printf("Check if NAT rule '%s' exists.", id)
providerState := provider.(*providerState)
apiClient := providerState.Client()
natRule, err := apiClient.GetNATRule(id)
if err != nil {
return false, err
}
exists := natRule != nil
log.Printf("NAT rule '%s' exists: %t.", id, exists)
return exists, nil
}
// Create a NAT resource.
func resourceNATCreate(data *schema.ResourceData, provider interface{}) error {
var err error
propertyHelper := propertyHelper(data)
networkDomainID := data.Get(resourceKeyNATNetworkDomainID).(string)
privateIP := data.Get(resourceKeyNATPrivateAddress).(string)
publicIP := propertyHelper.GetOptionalString(resourceKeyNATPublicAddress, false)
publicIPDescription := "<computed>"
if publicIP != nil {
publicIPDescription = *publicIP
}
log.Printf("Create NAT rule (from public IP '%s' to private IP '%s') in network domain '%s'.", publicIPDescription, privateIP, networkDomainID)
providerState := provider.(*providerState)
apiClient := providerState.Client()
var (
natRuleID string
createError error
)
operationDescription := fmt.Sprintf("Create NAT rule (from public IP '%s' to private IP '%s')", publicIPDescription, privateIP)
err = providerState.RetryAction(operationDescription, func(context retry.Context) {
asyncLock := providerState.AcquireAsyncOperationLock(operationDescription)
defer asyncLock.Release()
natRuleID, createError = apiClient.AddNATRule(networkDomainID, privateIP, publicIP)
if createError != nil {
if compute.IsResourceBusyError(createError) {
context.Retry()
} else if compute.IsNoIPAddressAvailableError(createError) {
log.Printf("There are no free public IPv4 addresses in network domain '%s'; requesting allocation of a new address block...", networkDomainID)
publicIPBlock, addBlockError := addPublicIPBlock(networkDomainID, apiClient)
if addBlockError != nil {
context.Fail(addBlockError)
return
}
log.Printf("Allocated a new public IPv4 address block '%s' (%d addresses, starting at '%s').",
publicIPBlock.ID, publicIPBlock.Size, publicIPBlock.BaseIP,
)
context.Retry() // We'll use the new block next time around.
} else {
context.Fail(createError)
}
}
})
if err != nil {
return err
}
data.SetId(natRuleID)
log.Printf("Successfully created NAT rule '%s'.", natRuleID)
natRule, err := apiClient.GetNATRule(natRuleID)
if err != nil {
return err
}
if natRule == nil {
return fmt.Errorf("Cannot find newly-added NAT rule '%s'.", natRuleID)
}
data.Set(resourceKeyNATPublicAddress, natRule.ExternalIPAddress)
return nil
}
// Read a NAT resource.
func resourceNATRead(data *schema.ResourceData, provider interface{}) error {
id := data.Id()
networkDomainID := data.Get(resourceKeyNATNetworkDomainID).(string)
privateIP := data.Get(resourceKeyNATPrivateAddress).(string)
publicIP := data.Get(resourceKeyNATPublicAddress).(string)
log.Printf("Read NAT '%s' (private IP = '%s', public IP = '%s') in network domain '%s'.", id, privateIP, publicIP, networkDomainID)
apiClient := provider.(*providerState).Client()
natRule, err := apiClient.GetNATRule(id)
if err != nil {
return err
}
if natRule == nil {
data.SetId("") // NAT rule has been deleted
return nil
}
return nil
}
// Update a NAT resource.
func resourceNATUpdate(data *schema.ResourceData, provider interface{}) error {
id := data.Id()
networkDomainID := data.Get(resourceKeyNATNetworkDomainID).(string)
privateIP := data.Get(resourceKeyNATPrivateAddress).(string)
publicIP := data.Get(resourceKeyNATPublicAddress).(string)
log.Printf("Update NAT '%s' (private IP = '%s', public IP = '%s') in network domain '%s' - nothing to update (NAT rules are read-only)", id, privateIP, publicIP, networkDomainID)
return nil
}
// Delete a NAT resource.
func resourceNATDelete(data *schema.ResourceData, provider interface{}) error {
id := data.Id()
networkDomainID := data.Get(resourceKeyNATNetworkDomainID).(string)
privateIP := data.Get(resourceKeyNATPrivateAddress).(string)
publicIP := data.Get(resourceKeyNATPublicAddress).(string)
log.Printf("Delete NAT '%s' (private IP = '%s', public IP = '%s') in network domain '%s'.", id, privateIP, publicIP, networkDomainID)
providerState := provider.(*providerState)
apiClient := providerState.Client()
operationDescription := fmt.Sprintf("Delete NAT '%s", id)
return providerState.RetryAction(operationDescription, func(context retry.Context) {
// CloudControl has issues if more than one asynchronous operation is initated at a time (returns UNEXPECTED_ERROR).
asyncLock := providerState.AcquireAsyncOperationLock(operationDescription)
defer asyncLock.Release() // Released at the end of the current attempt.
err := apiClient.DeleteNATRule(id)
if err != nil {
if compute.IsResourceBusyError(err) {
context.Retry()
} else {
context.Fail(err)
}
}
})
}
func calculateBlockAddresses(block compute.PublicIPBlock) ([]string, error) {
addresses := make([]string, block.Size)
baseAddressComponents := strings.Split(block.BaseIP, ".")
if len(baseAddressComponents) != 4 {
return addresses, fmt.Errorf("Invalid base IP address '%s'.", block.BaseIP)
}
baseOctet, err := strconv.Atoi(baseAddressComponents[3])
if err != nil {
return addresses, err
}
for index := range addresses {
// Increment the last octet to determine the next address in the block.
baseAddressComponents[3] = strconv.Itoa(baseOctet + index)
addresses[index] = strings.Join(baseAddressComponents, ".")
}
return addresses, nil
}