Remembers each config key's path and construct a relevant exception message in case of missing keys. The assumption is all access keys are present in a well-formed kube-config.
| 554 | |
| 555 | |
| 556 | class ConfigNode: |
| 557 | """Remembers each config key's path and construct a relevant exception |
| 558 | message in case of missing keys. The assumption is all access keys are |
| 559 | present in a well-formed kube-config.""" |
| 560 | |
| 561 | def __init__(self, name, value, path=None): |
| 562 | self.name = name |
| 563 | self.value = value |
| 564 | self.path = path |
| 565 | |
| 566 | def __contains__(self, key): |
| 567 | return key in self.value |
| 568 | |
| 569 | def __len__(self): |
| 570 | return len(self.value) |
| 571 | |
| 572 | def safe_get(self, key): |
| 573 | if (isinstance(self.value, list) and isinstance(key, int) or |
| 574 | key in self.value): |
| 575 | return self.value[key] |
| 576 | |
| 577 | def __getitem__(self, key): |
| 578 | v = self.safe_get(key) |
| 579 | if v is None: |
| 580 | raise ConfigException( |
| 581 | 'Invalid kube-config file. Expected key %s in %s' |
| 582 | % (key, self.name)) |
| 583 | if isinstance(v, dict) or isinstance(v, list): |
| 584 | return ConfigNode('%s/%s' % (self.name, key), v, self.path) |
| 585 | else: |
| 586 | return v |
| 587 | |
| 588 | def get_with_name(self, name, safe=False): |
| 589 | if not isinstance(self.value, list): |
| 590 | raise ConfigException( |
| 591 | 'Invalid kube-config file. Expected %s to be a list' |
| 592 | % self.name) |
| 593 | result = None |
| 594 | for v in self.value: |
| 595 | if 'name' not in v: |
| 596 | raise ConfigException( |
| 597 | 'Invalid kube-config file. ' |
| 598 | 'Expected all values in %s list to have \'name\' key' |
| 599 | % self.name) |
| 600 | if v['name'] == name: |
| 601 | if result is None: |
| 602 | result = v |
| 603 | else: |
| 604 | raise ConfigException( |
| 605 | 'Invalid kube-config file. ' |
| 606 | 'Expected only one object with name %s in %s list' |
| 607 | % (name, self.name)) |
| 608 | if result is not None: |
| 609 | if isinstance(result, ConfigNode): |
| 610 | return result |
| 611 | else: |
| 612 | return ConfigNode( |
| 613 | '%s[name=%s]' % |
no outgoing calls