github.com/hooklift/terraform@v0.11.0-beta1.0.20171117000744-6786c1361ffe/helper/schema/resource_diff.go (about) 1 package schema 2 3 import ( 4 "errors" 5 "fmt" 6 "reflect" 7 "strings" 8 "sync" 9 10 "github.com/hashicorp/terraform/terraform" 11 ) 12 13 // newValueWriter is a minor re-implementation of MapFieldWriter to include 14 // keys that should be marked as computed, to represent the new part of a 15 // pseudo-diff. 16 type newValueWriter struct { 17 *MapFieldWriter 18 19 // A list of keys that should be marked as computed. 20 computedKeys map[string]bool 21 22 // A lock to prevent races on writes. The underlying writer will have one as 23 // well - this is for computed keys. 24 lock sync.Mutex 25 26 // To be used with init. 27 once sync.Once 28 } 29 30 // init performs any initialization tasks for the newValueWriter. 31 func (w *newValueWriter) init() { 32 if w.computedKeys == nil { 33 w.computedKeys = make(map[string]bool) 34 } 35 } 36 37 // WriteField overrides MapValueWriter's WriteField, adding the ability to flag 38 // the address as computed. 39 func (w *newValueWriter) WriteField(address []string, value interface{}, computed bool) error { 40 // Fail the write if we have a non-nil value and computed is true. 41 // NewComputed values should not have a value when written. 42 if value != nil && computed { 43 return errors.New("Non-nil value with computed set") 44 } 45 46 if err := w.MapFieldWriter.WriteField(address, value); err != nil { 47 return err 48 } 49 50 w.once.Do(w.init) 51 52 w.lock.Lock() 53 defer w.lock.Unlock() 54 if computed { 55 w.computedKeys[strings.Join(address, ".")] = true 56 } 57 return nil 58 } 59 60 // ComputedKeysMap returns the underlying computed keys map. 61 func (w *newValueWriter) ComputedKeysMap() map[string]bool { 62 w.once.Do(w.init) 63 return w.computedKeys 64 } 65 66 // newValueReader is a minor re-implementation of MapFieldReader and is the 67 // read counterpart to MapValueWriter, allowing the read of keys flagged as 68 // computed to accommodate the diff override logic in ResourceDiff. 69 type newValueReader struct { 70 *MapFieldReader 71 72 // The list of computed keys from a newValueWriter. 73 computedKeys map[string]bool 74 } 75 76 // ReadField reads the values from the underlying writer, returning the 77 // computed value if it is found as well. 78 func (r *newValueReader) ReadField(address []string) (FieldReadResult, error) { 79 addrKey := strings.Join(address, ".") 80 v, err := r.MapFieldReader.ReadField(address) 81 if err != nil { 82 return FieldReadResult{}, err 83 } 84 for computedKey := range r.computedKeys { 85 if childAddrOf(addrKey, computedKey) { 86 if strings.HasSuffix(addrKey, ".#") { 87 // This is a count value for a list or set that has been marked as 88 // computed, or a sub-list/sub-set of a complex resource that has 89 // been marked as computed. We need to pass through to other readers 90 // so that an accurate previous count can be fetched for the diff. 91 v.Exists = false 92 } 93 v.Computed = true 94 } 95 } 96 97 return v, nil 98 } 99 100 // ResourceDiff is used to query and make custom changes to an in-flight diff. 101 // It can be used to veto particular changes in the diff, customize the diff 102 // that has been created, or diff values not controlled by config. 103 // 104 // The object functions similar to ResourceData, however most notably lacks 105 // Set, SetPartial, and Partial, as it should be used to change diff values 106 // only. Most other first-class ResourceData functions exist, namely Get, 107 // GetOk, HasChange, and GetChange exist. 108 // 109 // All functions in ResourceDiff, save for ForceNew, can only be used on 110 // computed fields. 111 type ResourceDiff struct { 112 // The schema for the resource being worked on. 113 schema map[string]*Schema 114 115 // The current config for this resource. 116 config *terraform.ResourceConfig 117 118 // The state for this resource as it exists post-refresh, after the initial 119 // diff. 120 state *terraform.InstanceState 121 122 // The diff created by Terraform. This diff is used, along with state, 123 // config, and custom-set diff data, to provide a multi-level reader 124 // experience similar to ResourceData. 125 diff *terraform.InstanceDiff 126 127 // The internal reader structure that contains the state, config, the default 128 // diff, and the new diff. 129 multiReader *MultiLevelFieldReader 130 131 // A writer that writes overridden new fields. 132 newWriter *newValueWriter 133 134 // Tracks which keys have been updated by ResourceDiff to ensure that the 135 // diff does not get re-run on keys that were not touched, or diffs that were 136 // just removed (re-running on the latter would just roll back the removal). 137 updatedKeys map[string]bool 138 } 139 140 // newResourceDiff creates a new ResourceDiff instance. 141 func newResourceDiff(schema map[string]*Schema, config *terraform.ResourceConfig, state *terraform.InstanceState, diff *terraform.InstanceDiff) *ResourceDiff { 142 d := &ResourceDiff{ 143 config: config, 144 state: state, 145 diff: diff, 146 schema: schema, 147 } 148 149 d.newWriter = &newValueWriter{ 150 MapFieldWriter: &MapFieldWriter{Schema: d.schema}, 151 } 152 readers := make(map[string]FieldReader) 153 var stateAttributes map[string]string 154 if d.state != nil { 155 stateAttributes = d.state.Attributes 156 readers["state"] = &MapFieldReader{ 157 Schema: d.schema, 158 Map: BasicMapReader(stateAttributes), 159 } 160 } 161 if d.config != nil { 162 readers["config"] = &ConfigFieldReader{ 163 Schema: d.schema, 164 Config: d.config, 165 } 166 } 167 if d.diff != nil { 168 readers["diff"] = &DiffFieldReader{ 169 Schema: d.schema, 170 Diff: d.diff, 171 Source: &MultiLevelFieldReader{ 172 Levels: []string{"state", "config"}, 173 Readers: readers, 174 }, 175 } 176 } 177 readers["newDiff"] = &newValueReader{ 178 MapFieldReader: &MapFieldReader{ 179 Schema: d.schema, 180 Map: BasicMapReader(d.newWriter.Map()), 181 }, 182 computedKeys: d.newWriter.ComputedKeysMap(), 183 } 184 d.multiReader = &MultiLevelFieldReader{ 185 Levels: []string{ 186 "state", 187 "config", 188 "diff", 189 "newDiff", 190 }, 191 192 Readers: readers, 193 } 194 195 d.updatedKeys = make(map[string]bool) 196 197 return d 198 } 199 200 // UpdatedKeys returns the keys that were updated by this ResourceDiff run. 201 // These are the only keys that a diff should be re-calculated for. 202 func (d *ResourceDiff) UpdatedKeys() []string { 203 var s []string 204 for k := range d.updatedKeys { 205 s = append(s, k) 206 } 207 return s 208 } 209 210 // Clear wipes the diff for a particular key. It is called by ResourceDiff's 211 // functionality to remove any possibility of conflicts, but can be called on 212 // its own to just remove a specific key from the diff completely. 213 // 214 // Note that this does not wipe an override. This function is only allowed on 215 // computed keys. 216 func (d *ResourceDiff) Clear(key string) error { 217 if err := d.checkKey(key, "Clear"); err != nil { 218 return err 219 } 220 221 return d.clear(key) 222 } 223 224 func (d *ResourceDiff) clear(key string) error { 225 // Check the schema to make sure that this key exists first. 226 if _, ok := d.schema[key]; !ok { 227 return fmt.Errorf("%s is not a valid key", key) 228 } 229 for k := range d.diff.Attributes { 230 if strings.HasPrefix(k, key) { 231 delete(d.diff.Attributes, k) 232 } 233 } 234 return nil 235 } 236 237 // diffChange helps to implement resourceDiffer and derives its change values 238 // from ResourceDiff's own change data, in addition to existing diff, config, and state. 239 func (d *ResourceDiff) diffChange(key string) (interface{}, interface{}, bool, bool) { 240 old, new := d.getChange(key) 241 242 if !old.Exists { 243 old.Value = nil 244 } 245 if !new.Exists { 246 new.Value = nil 247 } 248 249 return old.Value, new.Value, !reflect.DeepEqual(old.Value, new.Value), new.Computed 250 } 251 252 // SetNew is used to set a new diff value for the mentioned key. The value must 253 // be correct for the attribute's schema (mostly relevant for maps, lists, and 254 // sets). The original value from the state is used as the old value. 255 // 256 // This function is only allowed on computed attributes. 257 func (d *ResourceDiff) SetNew(key string, value interface{}) error { 258 if err := d.checkKey(key, "SetNew"); err != nil { 259 return err 260 } 261 262 return d.setDiff(key, value, false) 263 } 264 265 // SetNewComputed functions like SetNew, except that it blanks out a new value 266 // and marks it as computed. 267 // 268 // This function is only allowed on computed attributes. 269 func (d *ResourceDiff) SetNewComputed(key string) error { 270 if err := d.checkKey(key, "SetNewComputed"); err != nil { 271 return err 272 } 273 274 return d.setDiff(key, nil, true) 275 } 276 277 // setDiff performs common diff setting behaviour. 278 func (d *ResourceDiff) setDiff(key string, new interface{}, computed bool) error { 279 if err := d.clear(key); err != nil { 280 return err 281 } 282 283 if err := d.newWriter.WriteField(strings.Split(key, "."), new, computed); err != nil { 284 return fmt.Errorf("Cannot set new diff value for key %s: %s", key, err) 285 } 286 287 d.updatedKeys[key] = true 288 289 return nil 290 } 291 292 // ForceNew force-flags ForceNew in the schema for a specific key, and 293 // re-calculates its diff, effectively causing this attribute to force a new 294 // resource. 295 // 296 // Keep in mind that forcing a new resource will force a second run of the 297 // resource's CustomizeDiff function (with a new ResourceDiff) once the current 298 // one has completed. This second run is performed without state. This behavior 299 // will be the same as if a new resource is being created and is performed to 300 // ensure that the diff looks like the diff for a new resource as much as 301 // possible. CustomizeDiff should expect such a scenario and act correctly. 302 // 303 // This function is a no-op/error if there is no diff. 304 // 305 // Note that the change to schema is permanent for the lifecycle of this 306 // specific ResourceDiff instance. 307 func (d *ResourceDiff) ForceNew(key string) error { 308 if !d.HasChange(key) { 309 return fmt.Errorf("ForceNew: No changes for %s", key) 310 } 311 312 _, new := d.GetChange(key) 313 d.schema[key].ForceNew = true 314 return d.setDiff(key, new, false) 315 } 316 317 // Get hands off to ResourceData.Get. 318 func (d *ResourceDiff) Get(key string) interface{} { 319 r, _ := d.GetOk(key) 320 return r 321 } 322 323 // GetChange gets the change between the state and diff, checking first to see 324 // if a overridden diff exists. 325 // 326 // This implementation differs from ResourceData's in the way that we first get 327 // results from the exact levels for the new diff, then from state and diff as 328 // per normal. 329 func (d *ResourceDiff) GetChange(key string) (interface{}, interface{}) { 330 old, new := d.getChange(key) 331 return old.Value, new.Value 332 } 333 334 // GetOk functions the same way as ResourceData.GetOk, but it also checks the 335 // new diff levels to provide data consistent with the current state of the 336 // customized diff. 337 func (d *ResourceDiff) GetOk(key string) (interface{}, bool) { 338 r := d.get(strings.Split(key, "."), "newDiff") 339 exists := r.Exists && !r.Computed 340 if exists { 341 // If it exists, we also want to verify it is not the zero-value. 342 value := r.Value 343 zero := r.Schema.Type.Zero() 344 345 if eq, ok := value.(Equal); ok { 346 exists = !eq.Equal(zero) 347 } else { 348 exists = !reflect.DeepEqual(value, zero) 349 } 350 } 351 352 return r.Value, exists 353 } 354 355 // HasChange checks to see if there is a change between state and the diff, or 356 // in the overridden diff. 357 func (d *ResourceDiff) HasChange(key string) bool { 358 old, new := d.GetChange(key) 359 360 // If the type implements the Equal interface, then call that 361 // instead of just doing a reflect.DeepEqual. An example where this is 362 // needed is *Set 363 if eq, ok := old.(Equal); ok { 364 return !eq.Equal(new) 365 } 366 367 return !reflect.DeepEqual(old, new) 368 } 369 370 // Id returns the ID of this resource. 371 // 372 // Note that technically, ID does not change during diffs (it either has 373 // already changed in the refresh, or will change on update), hence we do not 374 // support updating the ID or fetching it from anything else other than state. 375 func (d *ResourceDiff) Id() string { 376 var result string 377 378 if d.state != nil { 379 result = d.state.ID 380 } 381 return result 382 } 383 384 // getChange gets values from two different levels, designed for use in 385 // diffChange, HasChange, and GetChange. 386 // 387 // This implementation differs from ResourceData's in the way that we first get 388 // results from the exact levels for the new diff, then from state and diff as 389 // per normal. 390 func (d *ResourceDiff) getChange(key string) (getResult, getResult) { 391 old := d.get(strings.Split(key, "."), "state") 392 var new getResult 393 for p := range d.updatedKeys { 394 if childAddrOf(key, p) { 395 new = d.getExact(strings.Split(key, "."), "newDiff") 396 goto done 397 } 398 } 399 new = d.get(strings.Split(key, "."), "newDiff") 400 done: 401 return old, new 402 } 403 404 // get performs the appropriate multi-level reader logic for ResourceDiff, 405 // starting at source. Refer to newResourceDiff for the level order. 406 func (d *ResourceDiff) get(addr []string, source string) getResult { 407 result, err := d.multiReader.ReadFieldMerge(addr, source) 408 if err != nil { 409 panic(err) 410 } 411 412 return d.finalizeResult(addr, result) 413 } 414 415 // getExact gets an attribute from the exact level referenced by source. 416 func (d *ResourceDiff) getExact(addr []string, source string) getResult { 417 result, err := d.multiReader.ReadFieldExact(addr, source) 418 if err != nil { 419 panic(err) 420 } 421 422 return d.finalizeResult(addr, result) 423 } 424 425 // finalizeResult does some post-processing of the result produced by get and getExact. 426 func (d *ResourceDiff) finalizeResult(addr []string, result FieldReadResult) getResult { 427 // If the result doesn't exist, then we set the value to the zero value 428 var schema *Schema 429 if schemaL := addrToSchema(addr, d.schema); len(schemaL) > 0 { 430 schema = schemaL[len(schemaL)-1] 431 } 432 433 if result.Value == nil && schema != nil { 434 result.Value = result.ValueOrZero(schema) 435 } 436 437 // Transform the FieldReadResult into a getResult. It might be worth 438 // merging these two structures one day. 439 return getResult{ 440 Value: result.Value, 441 ValueProcessed: result.ValueProcessed, 442 Computed: result.Computed, 443 Exists: result.Exists, 444 Schema: schema, 445 } 446 } 447 448 // childAddrOf does a comparison of two addresses to see if one is the child of 449 // the other. 450 func childAddrOf(child, parent string) bool { 451 cs := strings.Split(child, ".") 452 ps := strings.Split(parent, ".") 453 if len(ps) > len(cs) { 454 return false 455 } 456 return reflect.DeepEqual(ps, cs[:len(ps)]) 457 } 458 459 // checkKey checks the key to make sure it exists and is computed. 460 func (d *ResourceDiff) checkKey(key, caller string) error { 461 s, ok := d.schema[key] 462 if !ok { 463 return fmt.Errorf("%s: invalid key: %s", caller, key) 464 } 465 if !s.Computed { 466 return fmt.Errorf("%s only operates on computed keys - %s is not one", caller, key) 467 } 468 return nil 469 }